diff --git a/.appveyor.yml b/.appveyor.yml deleted file mode 100644 index 247a550d9f0..00000000000 --- a/.appveyor.yml +++ /dev/null @@ -1,17 +0,0 @@ -environment: - matrix: - - TARGET: x86_64-pc-windows-msvc - - TARGET: i686-pc-windows-msvc - - TARGET: x86_64-pc-windows-gnu - - TARGET: i686-pc-windows-gnu - RUST_BACKTRACE: full -install: - - curl -sSf -o rustup-init.exe https://win.rustup.rs/ - - rustup-init.exe -y --default-host %TARGET% - - set PATH=%PATH%;C:\Users\appveyor\.cargo\bin - - rustc -vV - - cargo -vV -build: false -test_script: - - cargo build --verbose --features yaml - - cargo test --verbose --features yaml diff --git a/.azure-pipelines.yml b/.azure-pipelines.yml new file mode 100644 index 00000000000..464b792f2cb --- /dev/null +++ b/.azure-pipelines.yml @@ -0,0 +1,61 @@ +name: $(Build.BuildId) +trigger: + # Always build master + - v2-master +pr: + # Enable building pull requests. + - v2-master +stages: + - stage: Testing + jobs: + - job: + variables: + rust: 1.36.0 + strategy: + matrix: + Windows 32-bit (MSVC): + image: vs2017-win2016 + target: i686-pc-windows-msvc + Windows 64-bit (MSVC): + image: vs2017-win2016 + target: x86_64-pc-windows-msvc + Windows 32-bit (MinGW): + image: vs2017-win2016 + target: i686-pc-windows-gnu + Windows 64-bit (MinGW): + image: vs2017-win2016 + target: x86_64-pc-windows-gnu + pool: + vmImage: $(image) + steps: + - checkout: self + fetchDepth: 1 + path: clap + displayName: Checkout repository + - task: Cache@2 + inputs: + key: cargo | "$(rust)" | $(target) | Cargo.toml + path: C:\Rust\.cargo + displayName: Caching cargo + - task: Cache@2 + inputs: + key: compiled | "$(rust)" | $(target) | Cargo.toml + path: target + displayName: Caching compiled + - script: rustup default $(rust)-$(target) + displayName: Install rust + - script: cargo test --no-default-features + displayName: Test without default features + env: + RUST_BACKTRACE: full + - script: cargo test --features "yaml unstable" + displayName: Test with most features + env: + RUST_BACKTRACE: full + - script: | + rmdir /Q /S C:\Rust\.cargo\registry\src + rmdir /Q /S target\.rustc_info.json + rmdir /Q /S target\debug\examples + rmdir /Q /S target\debug\incremental + displayName: Cleaning for cache + continueOnError: true diff --git a/.mention-bot b/.mention-bot deleted file mode 100644 index f339f59cd0f..00000000000 --- a/.mention-bot +++ /dev/null @@ -1,9 +0,0 @@ -{ - "findPotentialReviewers": false, - "alwaysNotifyForPaths": [ - { - "name": "kbknapp", - "files": ["**/*.rs", "**/*.md", "*"] - } - ] -} diff --git a/.travis.yml b/.travis.yml index 30ee1359169..f3cf7b7e046 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,67 +1,66 @@ -sudo: true +os: linux language: rust -cache: - directories: - - $HOME/.cargo - - $HOME/.rustup +cache: cargo before_cache: - - rm -rf /home/travis/.cargo/registry -rust: - - nightly - - nightly-2019-06-18 - - beta - - stable - - 1.33.0 -matrix: - allow_failures: - - rust: nightly - nightly-2019-06-18: - - script: cargo clippy -before_script: - - | - pip install git+git://github.com/kbknapp/travis-cargo.git --user && - export PATH=$HOME/.local/bin:$PATH - - | - if [[ "$TRAVIS_RUST_VERSION" == "1.13.0" ]]; then - echo "Old Rust detected, removing version-sync dependency" - sed -i "/^version-sync =/d" Cargo.toml - rm "tests/version-numbers.rs" - fi + - find target/debug -type f -maxdepth 1 -delete + - rm -rf target/.rustc_info.json + - rm -rf target/debug/examples + - rm -rf target/debug/incremental + - rm -rf target/tests/target/debug/incremental + - rm -rf target/tests/target/debug/deps/{clap*, trybuild*} + - rm -rf target/debug/{deps,.fingerpint}/clap* + - find target/debug/deps -name "clap*" -exec rm -rf {} + + - ls -1 examples/ | sed -e 's/\.rs$//' | xargs -I "{{}}" find target/debug/deps -name "{{}}*" -exec rm -rf {} + + - ls -1 tests/ | sed -e 's/\.rs$//' | xargs -I "{{}}" find target/debug/deps -name "{{}}*" -exec rm -rf {} + +rust: stable +branches: + only: + # Always build master & Enable building pull requests. + - v2-master +jobs: + allow_failures: + - rust: nightly + - env: + - SHARD=coverage + fast_finish: true + include: + - os: osx + rust: 1.36.0 + - rust: 1.36.0 + - {} + - rust: beta + - rust: nightly + - env: + - SHARD=lint + before_script: + - rustup component add clippy + - rustup component add rustfmt + script: + - echo "Checking codebase with Clippy release `cargo clippy --version`." + - cargo clippy --lib --features "yaml unstable" + - cargo clippy --tests --examples --features "yaml unstable" + - cargo fmt -- --check + - rust: nightly + env: + - SHARD=bench + script: + - cargo bench + - env: + - SHARD=coverage + addons: + apt: + packages: + - libssl-dev + - cmake + - pkg-config + - zlib1g-dev + update: true + before_script: + - cargo install cargo-tarpaulin + script: + - cargo tarpaulin --features "yaml unstable" --ciserver travis-ci --coveralls $TRAVIS_JOB_ID script: - - | - travis-cargo --only stable test -- --verbose --no-default-features && - travis-cargo --skip nightly test -- --verbose --features "yaml unstable" && - travis-cargo --only nightly test -- --verbose --features "yaml unstable nightly" && - travis-cargo --only nightly bench -- --no-run -addons: - apt: - packages: - - binutils-dev - - libcurl4-openssl-dev - - libelf-dev - - libdw-dev - - libiberty-dev - - cmake - - gcc - - zlib1g-dev -after_success: - - | - wget https://github.com/SimonKagstrom/kcov/archive/master.tar.gz && - tar xzf master.tar.gz && - cd kcov-master && - mkdir build && - cd build && - cmake .. && - make && - sudo make install && - cd ../.. && - rm -rf kcov-master && - cargo clean && - cargo test --no-run --features "yaml unstable" && - for file in target/debug/*-*; do mkdir -p "target/cov/$(basename $file)"; kcov --exclude-pattern=/.cargo --verify "target/cov/$(basename $file)" "$file"; done && - kcov --coveralls-id=$TRAVIS_JOB_ID --merge target/cov target/cov/* && - echo "Uploaded code coverage" -env: - global: - - TRAVIS_CARGO_NIGHTLY_FEATURE=lints - - secure: JLBlgHY6OEmhJ8woewNJHmuBokTNUv7/WvLkJGV8xk0t6bXBwSU0jNloXwlH7FiQTc4TccX0PumPDD4MrMgxIAVFPmmmlQOCmdpYP4tqZJ8xo189E5zk8lKF5OyaVYCs5SMmFC3cxCsKjfwGIexNu3ck5Uhwe9jI0tqgkgM3URA= + - cargo test --no-default-features + - cargo test --features yaml unstable +notifications: + email: false diff --git a/CHANGELOG.md b/CHANGELOG.md index 65cec2d89f7..965b653ac5f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ #### Minimum Required Rust -* As of this release, `clap` requires `rustc 1.33.0` or greater. +* As of this release, `clap` requires `rustc 1.36.0` or greater. ## v2.33.0 (2019-04-06) diff --git a/README.md b/README.md index 5a0840211ee..e3a91424679 100644 --- a/README.md +++ b/README.md @@ -455,9 +455,9 @@ This is inherently an unresolvable crate graph in Cargo right now. Cargo require #### Minimum Version of Rust -`clap` will officially support current stable Rust, minus two releases, but may work with prior releases as well. For example, current stable Rust at the time of this writing is 1.35.0, meaning `clap` is guaranteed to compile with 1.33.0 and beyond. +`clap` will officially support current stable Rust, minus two releases, but may work with prior releases as well. For example, current stable Rust at the time of this writing is 1.41.0, meaning `clap` is guaranteed to compile with 1.39.0 and beyond. -At the 1.36.0 stable release, `clap` will be guaranteed to compile with 1.34.0 and beyond, etc. +At the 1.42.0 stable release, `clap` will be guaranteed to compile with 1.40.0 and beyond, etc. Upon bumping the minimum version of Rust (assuming it's within the stable-2 range), it *must* be clearly annotated in the `CHANGELOG.md` diff --git a/benches/02_simple.rs b/benches/02_simple.rs index 010fa866fa7..aa9fd483d93 100644 --- a/benches/02_simple.rs +++ b/benches/02_simple.rs @@ -8,20 +8,21 @@ use clap::{App, Arg}; use test::Bencher; macro_rules! create_app { - () => ({ + () => {{ App::new("claptests") - .version("0.1") - .about("tests clap library") - .author("Kevin K. ") - .args_from_usage("-f --flag 'tests flags' + .version("0.1") + .about("tests clap library") + .author("Kevin K. ") + .args_from_usage( + "-f --flag 'tests flags' -o --option=[opt] 'tests options' - [positional] 'tests positional'") - }) + [positional] 'tests positional'", + ) + }}; } #[bench] fn build_app(b: &mut Bencher) { - b.iter(|| create_app!()); } diff --git a/benches/03_complex.rs b/benches/03_complex.rs index b00fc4eac56..744d7dd6910 100644 --- a/benches/03_complex.rs +++ b/benches/03_complex.rs @@ -4,7 +4,7 @@ extern crate clap; extern crate test; -use clap::{App, Arg, SubCommand, AppSettings}; +use clap::{App, AppSettings, Arg, SubCommand}; use test::Bencher; @@ -14,37 +14,45 @@ static OPT3_VALS: [&'static str; 2] = ["fast", "slow"]; static POS3_VALS: [&'static str; 2] = ["vi", "emacs"]; macro_rules! create_app { - () => ({ + () => {{ App::new("claptests") - .version("0.1") - .about("tests clap library") - .author("Kevin K. ") - .args_from_usage(ARGS) - .arg(Arg::from_usage("-f --flag... 'tests flags'") - .global(true)) - .args(&[ - Arg::from_usage("[flag2] -F 'tests flags with exclusions'").conflicts_with("flag").requires("option2"), - Arg::from_usage("--long-option-2 [option2] 'tests long options with exclusions'").conflicts_with("option").requires("positional2"), - Arg::from_usage("[positional2] 'tests positionals with exclusions'"), - Arg::from_usage("-O --Option [option3] 'tests options with specific value sets'").possible_values(&OPT3_VALS), - Arg::from_usage("[positional3]... 'tests positionals with specific values'").possible_values(&POS3_VALS), - Arg::from_usage("--multvals [one] [two] 'Tests multiple values, not mult occs'"), - Arg::from_usage("--multvalsmo... [one] [two] 'Tests multiple values, not mult occs'"), - Arg::from_usage("--minvals2 [minvals]... 'Tests 2 min vals'").min_values(2), - Arg::from_usage("--maxvals3 [maxvals]... 'Tests 3 max vals'").max_values(3) - ]) - .subcommand(SubCommand::with_name("subcmd") - .about("tests subcommands") - .version("0.1") - .author("Kevin K. ") - .arg_from_usage("-o --option [scoption]... 'tests options'") - .arg_from_usage("[scpositional] 'tests positionals'")) - }) + .version("0.1") + .about("tests clap library") + .author("Kevin K. ") + .args_from_usage(ARGS) + .arg(Arg::from_usage("-f --flag... 'tests flags'").global(true)) + .args(&[ + Arg::from_usage("[flag2] -F 'tests flags with exclusions'") + .conflicts_with("flag") + .requires("option2"), + Arg::from_usage("--long-option-2 [option2] 'tests long options with exclusions'") + .conflicts_with("option") + .requires("positional2"), + Arg::from_usage("[positional2] 'tests positionals with exclusions'"), + Arg::from_usage("-O --Option [option3] 'tests options with specific value sets'") + .possible_values(&OPT3_VALS), + Arg::from_usage("[positional3]... 'tests positionals with specific values'") + .possible_values(&POS3_VALS), + Arg::from_usage("--multvals [one] [two] 'Tests multiple values, not mult occs'"), + Arg::from_usage( + "--multvalsmo... [one] [two] 'Tests multiple values, not mult occs'", + ), + Arg::from_usage("--minvals2 [minvals]... 'Tests 2 min vals'").min_values(2), + Arg::from_usage("--maxvals3 [maxvals]... 'Tests 3 max vals'").max_values(3), + ]) + .subcommand( + SubCommand::with_name("subcmd") + .about("tests subcommands") + .version("0.1") + .author("Kevin K. ") + .arg_from_usage("-o --option [scoption]... 'tests options'") + .arg_from_usage("[scpositional] 'tests positionals'"), + ) + }}; } #[bench] fn create_app_from_usage(b: &mut Bencher) { - b.iter(|| create_app!()); } @@ -52,85 +60,115 @@ fn create_app_from_usage(b: &mut Bencher) { fn create_app_builder(b: &mut Bencher) { b.iter(|| { App::new("claptests") - .version("0.1") - .about("tests clap library") - .author("Kevin K. ") - .arg(Arg::with_name("opt") + .version("0.1") + .about("tests clap library") + .author("Kevin K. ") + .arg( + Arg::with_name("opt") .help("tests options") .short("o") .long("option") .takes_value(true) - .multiple(true)) - .arg(Arg::with_name("positional") + .multiple(true), + ) + .arg( + Arg::with_name("positional") .help("tests positionals") - .index(1)) - .arg(Arg::with_name("flag") - .short("f") - .help("tests flags") - .long("flag") - .multiple(true) - .global(true)) - .arg(Arg::with_name("flag2") + .index(1), + ) + .arg( + Arg::with_name("flag") + .short("f") + .help("tests flags") + .long("flag") + .multiple(true) + .global(true), + ) + .arg( + Arg::with_name("flag2") .short("F") .help("tests flags with exclusions") .conflicts_with("flag") - .requires("option2")) - .arg(Arg::with_name("option2") + .requires("option2"), + ) + .arg( + Arg::with_name("option2") .help("tests long options with exclusions") .conflicts_with("option") .requires("positional2") .takes_value(true) - .long("long-option-2")) - .arg(Arg::with_name("positional2") + .long("long-option-2"), + ) + .arg( + Arg::with_name("positional2") .index(3) - .help("tests positionals with exclusions")) - .arg(Arg::with_name("option3") + .help("tests positionals with exclusions"), + ) + .arg( + Arg::with_name("option3") .short("O") .long("Option") .takes_value(true) .help("tests options with specific value sets") - .possible_values(&OPT3_VALS)) - .arg(Arg::with_name("positional3") + .possible_values(&OPT3_VALS), + ) + .arg( + Arg::with_name("positional3") .multiple(true) .help("tests positionals with specific values") .index(4) - .possible_values(&POS3_VALS)) - .arg(Arg::with_name("multvals") + .possible_values(&POS3_VALS), + ) + .arg( + Arg::with_name("multvals") .long("multvals") .takes_value(true) .help("Tests multiple values, not mult occs") - .value_names(&["one", "two"])) - .arg(Arg::with_name("multvalsmo") + .value_names(&["one", "two"]), + ) + .arg( + Arg::with_name("multvalsmo") .long("multvalsmo") .takes_value(true) .multiple(true) .help("Tests multiple values, not mult occs") - .value_names(&["one", "two"])) - .arg(Arg::with_name("minvals") + .value_names(&["one", "two"]), + ) + .arg( + Arg::with_name("minvals") .long("minvals2") .multiple(true) .takes_value(true) .help("Tests 2 min vals") - .min_values(2)) - .arg(Arg::with_name("maxvals") + .min_values(2), + ) + .arg( + Arg::with_name("maxvals") .long("maxvals3") .takes_value(true) .multiple(true) .help("Tests 3 max vals") - .max_values(3)) - .subcommand(SubCommand::with_name("subcmd") + .max_values(3), + ) + .subcommand( + SubCommand::with_name("subcmd") .about("tests subcommands") .version("0.1") .author("Kevin K. ") - .arg(Arg::with_name("scoption") - .short("o") - .long("option") - .multiple(true) - .takes_value(true) - .help("tests options")) - .arg(Arg::with_name("scpositional") - .index(1) - .help("tests positionals"))); + .arg( + Arg::with_name("scoption") + .short("o") + .long("option") + .multiple(true) + .takes_value(true) + .help("tests options"), + ) + .arg( + Arg::with_name("scpositional") + .index(1) + .help("tests positionals"), + ), + ); }); } @@ -211,20 +249,75 @@ fn parse_sc_positional(b: &mut Bencher) { #[bench] fn parse_complex1(b: &mut Bencher) { - b.iter(|| create_app!().get_matches_from(vec!["myprog", "-ff", "-o", "option1", "arg1", "-O", "fast", "arg2", "--multvals", "one", "two", "emacs"])); + b.iter(|| { + create_app!().get_matches_from(vec![ + "myprog", + "-ff", + "-o", + "option1", + "arg1", + "-O", + "fast", + "arg2", + "--multvals", + "one", + "two", + "emacs", + ]) + }); } #[bench] fn parse_complex2(b: &mut Bencher) { - b.iter(|| create_app!().get_matches_from(vec!["myprog", "arg1", "-f", "arg2", "--long-option-2", "some", "-O", "slow", "--multvalsmo", "one", "two", "--minvals2", "3", "2", "1"])); + b.iter(|| { + create_app!().get_matches_from(vec![ + "myprog", + "arg1", + "-f", + "arg2", + "--long-option-2", + "some", + "-O", + "slow", + "--multvalsmo", + "one", + "two", + "--minvals2", + "3", + "2", + "1", + ]) + }); } #[bench] fn parse_complex2_with_args_negate_scs(b: &mut Bencher) { - b.iter(|| create_app!().setting(AppSettings::ArgsNegateSubcommands).get_matches_from(vec!["myprog", "arg1", "-f", "arg2", "--long-option-2", "some", "-O", "slow", "--multvalsmo", "one", "two", "--minvals2", "3", "2", "1"])); + b.iter(|| { + create_app!() + .setting(AppSettings::ArgsNegateSubcommands) + .get_matches_from(vec![ + "myprog", + "arg1", + "-f", + "arg2", + "--long-option-2", + "some", + "-O", + "slow", + "--multvalsmo", + "one", + "two", + "--minvals2", + "3", + "2", + "1", + ]) + }); } #[bench] fn parse_sc_complex(b: &mut Bencher) { - b.iter(|| create_app!().get_matches_from(vec!["myprog", "subcmd", "-f", "-o", "option1", "arg1"])); + b.iter(|| { + create_app!().get_matches_from(vec!["myprog", "subcmd", "-f", "-o", "option1", "arg1"]) + }); } diff --git a/benches/04_new_help.rs b/benches/04_new_help.rs index f033efb5a19..ad64fd87229 100644 --- a/benches/04_new_help.rs +++ b/benches/04_new_help.rs @@ -22,12 +22,16 @@ fn app_example1<'b, 'c>() -> App<'b, 'c> { .version("1.0") .author("Kevin K. ") .about("Does awesome things") - .args_from_usage("-c, --config=[FILE] 'Sets a custom config file' + .args_from_usage( + "-c, --config=[FILE] 'Sets a custom config file' 'Sets an optional output file' - -d... 'Turn debugging information on'") - .subcommand(SubCommand::with_name("test") - .about("does testing things") - .arg_from_usage("-l, --list 'lists test values'")) + -d... 'Turn debugging information on'", + ) + .subcommand( + SubCommand::with_name("test") + .about("does testing things") + .arg_from_usage("-l, --list 'lists test values'"), + ) } fn app_example2<'b, 'c>() -> App<'b, 'c> { @@ -39,21 +43,27 @@ fn app_example2<'b, 'c>() -> App<'b, 'c> { fn app_example3<'b, 'c>() -> App<'b, 'c> { App::new("MyApp") - .arg(Arg::with_name("debug") - .help("turn on debugging information") - .short("d")) - .args(&[Arg::with_name("config") - .help("sets the config file to use") - .takes_value(true) - .short("c") - .long("config"), - Arg::with_name("input") - .help("the input file to use") - .index(1) - .required(true)]) + .arg( + Arg::with_name("debug") + .help("turn on debugging information") + .short("d"), + ) + .args(&[ + Arg::with_name("config") + .help("sets the config file to use") + .takes_value(true) + .short("c") + .long("config"), + Arg::with_name("input") + .help("the input file to use") + .index(1) + .required(true), + ]) .arg_from_usage("--license 'display the license file'") - .args_from_usage("[output] 'Supply an output file to use' - -i, --int=[IFACE] 'Set an interface to use'") + .args_from_usage( + "[output] 'Supply an output file to use' + -i, --int=[IFACE] 'Set an interface to use'", + ) } fn app_example4<'b, 'c>() -> App<'b, 'c> { @@ -61,80 +71,96 @@ fn app_example4<'b, 'c>() -> App<'b, 'c> { .about("Parses an input file to do awesome things") .version("1.0") .author("Kevin K. ") - .arg(Arg::with_name("debug") - .help("turn on debugging information") - .short("d") - .long("debug")) - .arg(Arg::with_name("config") - .help("sets the config file to use") - .short("c") - .long("config")) - .arg(Arg::with_name("input") - .help("the input file to use") - .index(1) - .required(true)) + .arg( + Arg::with_name("debug") + .help("turn on debugging information") + .short("d") + .long("debug"), + ) + .arg( + Arg::with_name("config") + .help("sets the config file to use") + .short("c") + .long("config"), + ) + .arg( + Arg::with_name("input") + .help("the input file to use") + .index(1) + .required(true), + ) } fn app_example5<'b, 'c>() -> App<'b, 'c> { - App::new("MyApp").arg(Arg::with_name("awesome") - .help("turns up the awesome") - .short("a") - .long("awesome") - .multiple(true) - .requires("config") - .conflicts_with("output")) + App::new("MyApp").arg( + Arg::with_name("awesome") + .help("turns up the awesome") + .short("a") + .long("awesome") + .multiple(true) + .requires("config") + .conflicts_with("output"), + ) } fn app_example6<'b, 'c>() -> App<'b, 'c> { App::new("MyApp") - .arg(Arg::with_name("input") - .help("the input file to use") - .index(1) - .requires("config") - .conflicts_with("output") - .required(true)) - .arg(Arg::with_name("config") - .help("the config file to use") - .index(2)) + .arg( + Arg::with_name("input") + .help("the input file to use") + .index(1) + .requires("config") + .conflicts_with("output") + .required(true), + ) + .arg( + Arg::with_name("config") + .help("the config file to use") + .index(2), + ) } fn app_example7<'b, 'c>() -> App<'b, 'c> { App::new("MyApp") .arg(Arg::with_name("config")) .arg(Arg::with_name("output")) - .arg(Arg::with_name("input") - .help("the input file to use") - .takes_value(true) - .short("i") - .long("input") - .multiple(true) - .required(true) - .requires("config") - .conflicts_with("output")) + .arg( + Arg::with_name("input") + .help("the input file to use") + .takes_value(true) + .short("i") + .long("input") + .multiple(true) + .required(true) + .requires("config") + .conflicts_with("output"), + ) } fn app_example8<'b, 'c>() -> App<'b, 'c> { App::new("MyApp") .arg(Arg::with_name("config")) .arg(Arg::with_name("output")) - .arg(Arg::with_name("input") - .help("the input file to use") - .takes_value(true) - .short("i") - .long("input") - .multiple(true) - .required(true) - .requires("config") - .conflicts_with("output")) + .arg( + Arg::with_name("input") + .help("the input file to use") + .takes_value(true) + .short("i") + .long("input") + .multiple(true) + .required(true) + .requires("config") + .conflicts_with("output"), + ) } fn app_example10<'b, 'c>() -> App<'b, 'c> { - App::new("myapp") - .about("does awesome things") - .arg(Arg::with_name("CONFIG") + App::new("myapp").about("does awesome things").arg( + Arg::with_name("CONFIG") .help("The config file to use (default is \"config.json\")") .short("c") - .takes_value(true)) + .takes_value(true), + ) } #[bench] diff --git a/benches/05_ripgrep.rs b/benches/05_ripgrep.rs index 7db1552550b..56ee336f2a3 100644 --- a/benches/05_ripgrep.rs +++ b/benches/05_ripgrep.rs @@ -12,15 +12,19 @@ extern crate lazy_static; use clap::{App, AppSettings, Arg, ArgSettings}; -use test::Bencher; use std::collections::HashMap; use std::io::Cursor; +use test::Bencher; #[bench] -fn build_app_short(b: &mut Bencher) { b.iter(|| app_short()); } +fn build_app_short(b: &mut Bencher) { + b.iter(|| app_short()); +} #[bench] -fn build_app_long(b: &mut Bencher) { b.iter(|| app_long()); } +fn build_app_long(b: &mut Bencher) { + b.iter(|| app_long()); +} #[bench] fn build_help_short(b: &mut Bencher) { @@ -35,249 +39,194 @@ fn build_help_long(b: &mut Bencher) { } #[bench] -fn parse_clean(b: &mut Bencher) { b.iter(|| app_short().get_matches_from(vec!["rg", "pat"])); } +fn parse_clean(b: &mut Bencher) { + b.iter(|| app_short().get_matches_from(vec!["rg", "pat"])); +} #[bench] fn parse_complex(b: &mut Bencher) { b.iter(|| { - app_short().get_matches_from(vec!["rg", - "pat", - "-cFlN", - "-pqr=some", - "--null", - "--no-filename", - "--no-messages", - "-SH", - "-C5", - "--follow", - "-e some"]) + app_short().get_matches_from(vec![ + "rg", + "pat", + "-cFlN", + "-pqr=some", + "--null", + "--no-filename", + "--no-messages", + "-SH", + "-C5", + "--follow", + "-e some", + ]) }); } #[bench] fn parse_lots(b: &mut Bencher) { b.iter(|| { - app_short() - .get_matches_from(vec!["rg", "pat", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some"]) + app_short().get_matches_from(vec![ + "rg", "pat", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", + ]) }); } @@ -312,11 +261,14 @@ OPTIONS: {unified}"; /// Build a clap application with short help strings. -pub fn app_short() -> App<'static, 'static> { app(false, |k| USAGES[k].short) } +pub fn app_short() -> App<'static, 'static> { + app(false, |k| USAGES[k].short) +} /// Build a clap application with long help strings. -pub fn app_long() -> App<'static, 'static> { app(true, |k| USAGES[k].long) } - +pub fn app_long() -> App<'static, 'static> { + app(true, |k| USAGES[k].long) +} /// Build the help text of an application. fn build_help(app: &App) -> String { @@ -326,7 +278,6 @@ fn build_help(app: &App) -> String { String::from_utf8(content).unwrap() } - /// Build a clap application parameterized by usage strings. /// /// The function given should take a clap argument name and return a help @@ -335,9 +286,14 @@ fn build_help(app: &App) -> String { /// This is an intentionally stand-alone module so that it can be used easily /// in a `build.rs` script to build shell completion files. fn app(next_line_help: bool, doc: F) -> App<'static, 'static> - where F: Fn(&'static str) -> &'static str +where + F: Fn(&'static str) -> &'static str, { - let arg = |name| Arg::with_name(name).help(doc(name)).next_line_help(next_line_help); + let arg = |name| { + Arg::with_name(name) + .help(doc(name)) + .next_line_help(next_line_help) + }; let flag = |name| arg(name).long(name); App::new("ripgrep") @@ -354,67 +310,118 @@ fn app(next_line_help: bool, doc: F) -> App<'static, 'static> .arg(flag("help")) .arg(flag("version").short("V")) // First, set up primary positional/flag arguments. - .arg(arg("pattern") - .required_unless_one(&[ - "file", "files", "help-short", "help", "regexp", "type-list", - "version", - ])) + .arg(arg("pattern").required_unless_one(&[ + "file", + "files", + "help-short", + "help", + "regexp", + "type-list", + "version", + ])) .arg(arg("path").multiple(true)) - .arg(flag("regexp").short("e") - .takes_value(true).multiple(true).number_of_values(1) - .set(ArgSettings::AllowLeadingHyphen) - .value_name("pattern")) - .arg(flag("files") - // This should also conflict with `pattern`, but the first file - // path will actually be in `pattern`. - .conflicts_with_all(&["file", "regexp", "type-list"])) - .arg(flag("type-list") - .conflicts_with_all(&["file", "files", "pattern", "regexp"])) + .arg( + flag("regexp") + .short("e") + .takes_value(true) + .multiple(true) + .number_of_values(1) + .set(ArgSettings::AllowLeadingHyphen) + .value_name("pattern"), + ) + .arg( + flag("files") + // This should also conflict with `pattern`, but the first file + // path will actually be in `pattern`. + .conflicts_with_all(&["file", "regexp", "type-list"]), + ) + .arg(flag("type-list").conflicts_with_all(&["file", "files", "pattern", "regexp"])) // Second, set up common flags. .arg(flag("text").short("a")) .arg(flag("count").short("c")) - .arg(flag("color") - .value_name("WHEN") - .takes_value(true) - .hide_possible_values(true) - .possible_values(&["never", "auto", "always", "ansi"])) - .arg(flag("colors").value_name("SPEC") - .takes_value(true).multiple(true).number_of_values(1)) + .arg( + flag("color") + .value_name("WHEN") + .takes_value(true) + .hide_possible_values(true) + .possible_values(&["never", "auto", "always", "ansi"]), + ) + .arg( + flag("colors") + .value_name("SPEC") + .takes_value(true) + .multiple(true) + .number_of_values(1), + ) .arg(flag("fixed-strings").short("F")) - .arg(flag("glob").short("g") - .takes_value(true).multiple(true).number_of_values(1) - .value_name("GLOB")) + .arg( + flag("glob") + .short("g") + .takes_value(true) + .multiple(true) + .number_of_values(1) + .value_name("GLOB"), + ) .arg(flag("ignore-case").short("i")) .arg(flag("line-number").short("n")) .arg(flag("no-line-number").short("N")) .arg(flag("quiet").short("q")) - .arg(flag("type").short("t") - .takes_value(true).multiple(true).number_of_values(1) - .value_name("TYPE")) - .arg(flag("type-not").short("T") - .takes_value(true).multiple(true).number_of_values(1) - .value_name("TYPE")) - .arg(flag("unrestricted").short("u") - .multiple(true)) + .arg( + flag("type") + .short("t") + .takes_value(true) + .multiple(true) + .number_of_values(1) + .value_name("TYPE"), + ) + .arg( + flag("type-not") + .short("T") + .takes_value(true) + .multiple(true) + .number_of_values(1) + .value_name("TYPE"), + ) + .arg(flag("unrestricted").short("u").multiple(true)) .arg(flag("invert-match").short("v")) .arg(flag("word-regexp").short("w")) // Third, set up less common flags. - .arg(flag("after-context").short("A") - .value_name("NUM").takes_value(true) - .validator(validate_number)) - .arg(flag("before-context").short("B") - .value_name("NUM").takes_value(true) - .validator(validate_number)) - .arg(flag("context").short("C") - .value_name("NUM").takes_value(true) - .validator(validate_number)) + .arg( + flag("after-context") + .short("A") + .value_name("NUM") + .takes_value(true) + .validator(validate_number), + ) + .arg( + flag("before-context") + .short("B") + .value_name("NUM") + .takes_value(true) + .validator(validate_number), + ) + .arg( + flag("context") + .short("C") + .value_name("NUM") + .takes_value(true) + .validator(validate_number), + ) .arg(flag("column")) - .arg(flag("context-separator") - .value_name("SEPARATOR").takes_value(true)) + .arg( + flag("context-separator") + .value_name("SEPARATOR") + .takes_value(true), + ) .arg(flag("debug")) - .arg(flag("file").short("f") - .value_name("FILE").takes_value(true) - .multiple(true).number_of_values(1)) + .arg( + flag("file") + .short("f") + .value_name("FILE") + .takes_value(true) + .multiple(true) + .number_of_values(1), + ) .arg(flag("files-with-matches").short("l")) .arg(flag("files-without-match")) .arg(flag("with-filename").short("H")) @@ -422,16 +429,27 @@ fn app(next_line_help: bool, doc: F) -> App<'static, 'static> .arg(flag("heading").overrides_with("no-heading")) .arg(flag("no-heading").overrides_with("heading")) .arg(flag("hidden")) - .arg(flag("ignore-file") - .value_name("FILE").takes_value(true) - .multiple(true).number_of_values(1)) + .arg( + flag("ignore-file") + .value_name("FILE") + .takes_value(true) + .multiple(true) + .number_of_values(1), + ) .arg(flag("follow").short("L")) - .arg(flag("max-count") - .short("m").value_name("NUM").takes_value(true) - .validator(validate_number)) - .arg(flag("maxdepth") - .value_name("NUM").takes_value(true) - .validator(validate_number)) + .arg( + flag("max-count") + .short("m") + .value_name("NUM") + .takes_value(true) + .validator(validate_number), + ) + .arg( + flag("maxdepth") + .value_name("NUM") + .takes_value(true) + .validator(validate_number), + ) .arg(flag("mmap")) .arg(flag("no-messages")) .arg(flag("no-mmap")) @@ -439,22 +457,43 @@ fn app(next_line_help: bool, doc: F) -> App<'static, 'static> .arg(flag("no-ignore-parent")) .arg(flag("no-ignore-vcs")) .arg(flag("null")) - .arg(flag("path-separator").value_name("SEPARATOR").takes_value(true)) + .arg( + flag("path-separator") + .value_name("SEPARATOR") + .takes_value(true), + ) .arg(flag("pretty").short("p")) - .arg(flag("replace").short("r").value_name("ARG").takes_value(true)) + .arg( + flag("replace") + .short("r") + .value_name("ARG") + .takes_value(true), + ) .arg(flag("case-sensitive").short("s")) .arg(flag("smart-case").short("S")) .arg(flag("sort-files")) - .arg(flag("threads") - .short("j").value_name("ARG").takes_value(true) - .validator(validate_number)) + .arg( + flag("threads") + .short("j") + .value_name("ARG") + .takes_value(true) + .validator(validate_number), + ) .arg(flag("vimgrep")) - .arg(flag("type-add") - .value_name("TYPE").takes_value(true) - .multiple(true).number_of_values(1)) - .arg(flag("type-clear") - .value_name("TYPE").takes_value(true) - .multiple(true).number_of_values(1)) + .arg( + flag("type-add") + .value_name("TYPE") + .takes_value(true) + .multiple(true) + .number_of_values(1), + ) + .arg( + flag("type-clear") + .value_name("TYPE") + .takes_value(true) + .multiple(true) + .number_of_values(1), + ) } struct Usage { @@ -467,60 +506,86 @@ macro_rules! doc { doc!($map, $name, $short, $short) }; ($map:expr, $name:expr, $short:expr, $long:expr) => { - $map.insert($name, Usage { - short: $short, - long: concat!($long, "\n "), - }); + $map.insert( + $name, + Usage { + short: $short, + long: concat!($long, "\n "), + }, + ); }; } lazy_static! { static ref USAGES: HashMap<&'static str, Usage> = { let mut h = HashMap::new(); - doc!(h, "help-short", - "Show short help output.", - "Show short help output. Use --help to show more details."); - doc!(h, "help", - "Show verbose help output.", - "When given, more details about flags are provided."); - doc!(h, "version", - "Prints version information."); - - doc!(h, "pattern", - "A regular expression used for searching.", - "A regular expression used for searching. Multiple patterns \ - may be given. To match a pattern beginning with a -, use [-]."); - doc!(h, "regexp", - "A regular expression used for searching.", - "A regular expression used for searching. Multiple patterns \ - may be given. To match a pattern beginning with a -, use [-]."); - doc!(h, "path", - "A file or directory to search.", - "A file or directory to search. Directories are searched \ - recursively."); - doc!(h, "files", - "Print each file that would be searched.", - "Print each file that would be searched without actually \ + doc!( + h, + "help-short", + "Show short help output.", + "Show short help output. Use --help to show more details." + ); + doc!( + h, + "help", + "Show verbose help output.", + "When given, more details about flags are provided." + ); + doc!(h, "version", "Prints version information."); + + doc!( + h, + "pattern", + "A regular expression used for searching.", + "A regular expression used for searching. Multiple patterns \ + may be given. To match a pattern beginning with a -, use [-]." + ); + doc!( + h, + "regexp", + "A regular expression used for searching.", + "A regular expression used for searching. Multiple patterns \ + may be given. To match a pattern beginning with a -, use [-]." + ); + doc!( + h, + "path", + "A file or directory to search.", + "A file or directory to search. Directories are searched \ + recursively." + ); + doc!( + h, + "files", + "Print each file that would be searched.", + "Print each file that would be searched without actually \ performing the search. This is useful to determine whether a \ - particular file is being searched or not."); - doc!(h, "type-list", - "Show all supported file types.", - "Show all supported file types and their corresponding globs."); - - doc!(h, "text", - "Search binary files as if they were text."); - doc!(h, "count", - "Only show count of matches for each file."); - doc!(h, "color", - "When to use color. [default: auto]", - "When to use color in the output. The possible values are \ + particular file is being searched or not." + ); + doc!( + h, + "type-list", + "Show all supported file types.", + "Show all supported file types and their corresponding globs." + ); + + doc!(h, "text", "Search binary files as if they were text."); + doc!(h, "count", "Only show count of matches for each file."); + doc!( + h, + "color", + "When to use color. [default: auto]", + "When to use color in the output. The possible values are \ never, auto, always or ansi. The default is auto. When always \ is used, coloring is attempted based on your environment. When \ ansi used, coloring is forcefully done using ANSI escape color \ - codes."); - doc!(h, "colors", - "Configure color settings and styles.", - "This flag specifies color settings for use in the output. \ + codes." + ); + doc!( + h, + "colors", + "Configure color settings and styles.", + "This flag specifies color settings for use in the output. \ This flag may be provided multiple times. Settings are applied \ iteratively. Colors are limited to one of eight choices: \ red, blue, green, cyan, magenta, yellow, white and black. \ @@ -532,216 +597,331 @@ lazy_static! { settings for {type}.\n\nFor example, the following command will \ change the match color to magenta and the background color for \ line numbers to yellow:\n\n\ - rg --colors 'match:fg:magenta' --colors 'line:bg:yellow' foo."); - doc!(h, "fixed-strings", - "Treat the pattern as a literal string.", - "Treat the pattern as a literal string instead of a regular \ + rg --colors 'match:fg:magenta' --colors 'line:bg:yellow' foo." + ); + doc!( + h, + "fixed-strings", + "Treat the pattern as a literal string.", + "Treat the pattern as a literal string instead of a regular \ expression. When this flag is used, special regular expression \ - meta characters such as (){}*+. do not need to be escaped."); - doc!(h, "glob", - "Include or exclude files/directories.", - "Include or exclude files/directories for searching that \ + meta characters such as (){}*+. do not need to be escaped." + ); + doc!( + h, + "glob", + "Include or exclude files/directories.", + "Include or exclude files/directories for searching that \ match the given glob. This always overrides any other \ ignore logic. Multiple glob flags may be used. Globbing \ rules match .gitignore globs. Precede a glob with a ! \ - to exclude it."); - doc!(h, "ignore-case", - "Case insensitive search.", - "Case insensitive search. This is overridden by \ - --case-sensitive."); - doc!(h, "line-number", - "Show line numbers.", - "Show line numbers (1-based). This is enabled by default when \ - searching in a tty."); - doc!(h, "no-line-number", - "Suppress line numbers.", - "Suppress line numbers. This is enabled by default when NOT \ - searching in a tty."); - doc!(h, "quiet", - "Do not print anything to stdout.", - "Do not print anything to stdout. If a match is found in a file, \ + to exclude it." + ); + doc!( + h, + "ignore-case", + "Case insensitive search.", + "Case insensitive search. This is overridden by \ + --case-sensitive." + ); + doc!( + h, + "line-number", + "Show line numbers.", + "Show line numbers (1-based). This is enabled by default when \ + searching in a tty." + ); + doc!( + h, + "no-line-number", + "Suppress line numbers.", + "Suppress line numbers. This is enabled by default when NOT \ + searching in a tty." + ); + doc!( + h, + "quiet", + "Do not print anything to stdout.", + "Do not print anything to stdout. If a match is found in a file, \ stop searching. This is useful when ripgrep is used only for \ - its exit code."); - doc!(h, "type", - "Only search files matching TYPE.", - "Only search files matching TYPE. Multiple type flags may be \ + its exit code." + ); + doc!( + h, + "type", + "Only search files matching TYPE.", + "Only search files matching TYPE. Multiple type flags may be \ provided. Use the --type-list flag to list all available \ - types."); - doc!(h, "type-not", - "Do not search files matching TYPE.", - "Do not search files matching TYPE. Multiple type-not flags may \ + types." + ); + doc!( + h, + "type-not", + "Do not search files matching TYPE.", + "Do not search files matching TYPE. Multiple type-not flags may \ be provided. Use the --type-list flag to list all available \ - types."); - doc!(h, "unrestricted", - "Reduce the level of \"smart\" searching.", - "Reduce the level of \"smart\" searching. A single -u \ + types." + ); + doc!( + h, + "unrestricted", + "Reduce the level of \"smart\" searching.", + "Reduce the level of \"smart\" searching. A single -u \ won't respect .gitignore (etc.) files. Two -u flags will \ additionally search hidden files and directories. Three \ -u flags will additionally search binary files. -uu is \ roughly equivalent to grep -r and -uuu is roughly \ - equivalent to grep -a -r."); - doc!(h, "invert-match", - "Invert matching.", - "Invert matching. Show lines that don't match given patterns."); - doc!(h, "word-regexp", - "Only show matches surrounded by word boundaries.", - "Only show matches surrounded by word boundaries. This is \ + equivalent to grep -a -r." + ); + doc!( + h, + "invert-match", + "Invert matching.", + "Invert matching. Show lines that don't match given patterns." + ); + doc!( + h, + "word-regexp", + "Only show matches surrounded by word boundaries.", + "Only show matches surrounded by word boundaries. This is \ equivalent to putting \\b before and after all of the search \ - patterns."); - - doc!(h, "after-context", - "Show NUM lines after each match."); - doc!(h, "before-context", - "Show NUM lines before each match."); - doc!(h, "context", - "Show NUM lines before and after each match."); - doc!(h, "column", - "Show column numbers", - "Show column numbers (1-based). This only shows the column \ + patterns." + ); + + doc!(h, "after-context", "Show NUM lines after each match."); + doc!(h, "before-context", "Show NUM lines before each match."); + doc!(h, "context", "Show NUM lines before and after each match."); + doc!( + h, + "column", + "Show column numbers", + "Show column numbers (1-based). This only shows the column \ numbers for the first match on each line. This does not try \ to account for Unicode. One byte is equal to one column. This \ - implies --line-number."); - doc!(h, "context-separator", - "Set the context separator string. [default: --]", - "The string used to separate non-contiguous context lines in the \ + implies --line-number." + ); + doc!( + h, + "context-separator", + "Set the context separator string. [default: --]", + "The string used to separate non-contiguous context lines in the \ output. Escape sequences like \\x7F or \\t may be used. The \ - default value is --."); - doc!(h, "debug", - "Show debug messages.", - "Show debug messages. Please use this when filing a bug report."); - doc!(h, "file", - "Search for patterns from the given file.", - "Search for patterns from the given file, with one pattern per \ + default value is --." + ); + doc!( + h, + "debug", + "Show debug messages.", + "Show debug messages. Please use this when filing a bug report." + ); + doc!( + h, + "file", + "Search for patterns from the given file.", + "Search for patterns from the given file, with one pattern per \ line. When this flag is used or multiple times or in \ combination with the -e/--regexp flag, then all patterns \ provided are searched. Empty pattern lines will match all input \ - lines, and the newline is not counted as part of the pattern."); - doc!(h, "files-with-matches", - "Only show the path of each file with at least one match."); - doc!(h, "files-without-match", - "Only show the path of each file that contains zero matches."); - doc!(h, "with-filename", - "Show file name for each match.", - "Prefix each match with the file name that contains it. This is \ - the default when more than one file is searched."); - doc!(h, "no-filename", - "Never show the file name for a match.", - "Never show the file name for a match. This is the default when \ - one file is searched."); - doc!(h, "heading", - "Show matches grouped by each file.", - "This shows the file name above clusters of matches from each \ + lines, and the newline is not counted as part of the pattern." + ); + doc!( + h, + "files-with-matches", + "Only show the path of each file with at least one match." + ); + doc!( + h, + "files-without-match", + "Only show the path of each file that contains zero matches." + ); + doc!( + h, + "with-filename", + "Show file name for each match.", + "Prefix each match with the file name that contains it. This is \ + the default when more than one file is searched." + ); + doc!( + h, + "no-filename", + "Never show the file name for a match.", + "Never show the file name for a match. This is the default when \ + one file is searched." + ); + doc!( + h, + "heading", + "Show matches grouped by each file.", + "This shows the file name above clusters of matches from each \ file instead of showing the file name for every match. This is \ - the default mode at a tty."); - doc!(h, "no-heading", - "Don't group matches by each file.", - "Don't group matches by each file. If -H/--with-filename is \ + the default mode at a tty." + ); + doc!( + h, + "no-heading", + "Don't group matches by each file.", + "Don't group matches by each file. If -H/--with-filename is \ enabled, then file names will be shown for every line matched. \ - This is the default mode when not at a tty."); - doc!(h, "hidden", - "Search hidden files and directories.", - "Search hidden files and directories. By default, hidden files \ - and directories are skipped."); - doc!(h, "ignore-file", - "Specify additional ignore files.", - "Specify additional ignore files for filtering file paths. \ + This is the default mode when not at a tty." + ); + doc!( + h, + "hidden", + "Search hidden files and directories.", + "Search hidden files and directories. By default, hidden files \ + and directories are skipped." + ); + doc!( + h, + "ignore-file", + "Specify additional ignore files.", + "Specify additional ignore files for filtering file paths. \ Ignore files should be in the gitignore format and are matched \ relative to the current working directory. These ignore files \ have lower precedence than all other ignore files. When \ specifying multiple ignore files, earlier files have lower \ - precedence than later files."); - doc!(h, "follow", - "Follow symbolic links."); - doc!(h, "max-count", - "Limit the number of matches.", - "Limit the number of matching lines per file searched to NUM."); - doc!(h, "maxdepth", - "Descend at most NUM directories.", - "Limit the depth of directory traversal to NUM levels beyond \ + precedence than later files." + ); + doc!(h, "follow", "Follow symbolic links."); + doc!( + h, + "max-count", + "Limit the number of matches.", + "Limit the number of matching lines per file searched to NUM." + ); + doc!( + h, + "maxdepth", + "Descend at most NUM directories.", + "Limit the depth of directory traversal to NUM levels beyond \ the paths given. A value of zero only searches the \ starting-points themselves.\n\nFor example, \ 'rg --maxdepth 0 dir/' is a no-op because dir/ will not be \ descended into. 'rg --maxdepth 1 dir/' will search only the \ - direct children of dir/."); - doc!(h, "mmap", - "Searching using memory maps when possible.", - "Search using memory maps when possible. This is enabled by \ + direct children of dir/." + ); + doc!( + h, + "mmap", + "Searching using memory maps when possible.", + "Search using memory maps when possible. This is enabled by \ default when ripgrep thinks it will be faster. Note that memory \ map searching doesn't currently support all options, so if an \ incompatible option (e.g., --context) is given with --mmap, \ - then memory maps will not be used."); - doc!(h, "no-messages", - "Suppress all error messages.", - "Suppress all error messages. This is equivalent to redirecting \ - stderr to /dev/null."); - doc!(h, "no-mmap", - "Never use memory maps.", - "Never use memory maps, even when they might be faster."); - doc!(h, "no-ignore", - "Don't respect ignore files.", - "Don't respect ignore files (.gitignore, .ignore, etc.). This \ - implies --no-ignore-parent and --no-ignore-vcs."); - doc!(h, "no-ignore-parent", - "Don't respect ignore files in parent directories.", - "Don't respect ignore files (.gitignore, .ignore, etc.) in \ - parent directories."); - doc!(h, "no-ignore-vcs", - "Don't respect VCS ignore files", - "Don't respect version control ignore files (.gitignore, etc.). \ + then memory maps will not be used." + ); + doc!( + h, + "no-messages", + "Suppress all error messages.", + "Suppress all error messages. This is equivalent to redirecting \ + stderr to /dev/null." + ); + doc!( + h, + "no-mmap", + "Never use memory maps.", + "Never use memory maps, even when they might be faster." + ); + doc!( + h, + "no-ignore", + "Don't respect ignore files.", + "Don't respect ignore files (.gitignore, .ignore, etc.). This \ + implies --no-ignore-parent and --no-ignore-vcs." + ); + doc!( + h, + "no-ignore-parent", + "Don't respect ignore files in parent directories.", + "Don't respect ignore files (.gitignore, .ignore, etc.) in \ + parent directories." + ); + doc!( + h, + "no-ignore-vcs", + "Don't respect VCS ignore files", + "Don't respect version control ignore files (.gitignore, etc.). \ This implies --no-ignore-parent. Note that .ignore files will \ - continue to be respected."); - doc!(h, "null", - "Print NUL byte after file names", - "Whenever a file name is printed, follow it with a NUL byte. \ + continue to be respected." + ); + doc!( + h, + "null", + "Print NUL byte after file names", + "Whenever a file name is printed, follow it with a NUL byte. \ This includes printing file names before matches, and when \ printing a list of matching files such as with --count, \ --files-with-matches and --files. This option is useful for use \ - with xargs."); - doc!(h, "path-separator", - "Path separator to use when printing file paths.", - "The path separator to use when printing file paths. This \ + with xargs." + ); + doc!( + h, + "path-separator", + "Path separator to use when printing file paths.", + "The path separator to use when printing file paths. This \ defaults to your platform's path separator, which is / on Unix \ and \\ on Windows. This flag is intended for overriding the \ default when the environment demands it (e.g., cygwin). A path \ - separator is limited to a single byte."); - doc!(h, "pretty", - "Alias for --color always --heading -n."); - doc!(h, "replace", - "Replace matches with string given.", - "Replace every match with the string given when printing \ + separator is limited to a single byte." + ); + doc!(h, "pretty", "Alias for --color always --heading -n."); + doc!( + h, + "replace", + "Replace matches with string given.", + "Replace every match with the string given when printing \ results. Neither this flag nor any other flag will modify your \ files.\n\nCapture group indices (e.g., $5) and names \ (e.g., $foo) are supported in the replacement string.\n\n\ Note that the replacement by default replaces each match, and \ NOT the entire line. To replace the entire line, you should \ - match the entire line."); - doc!(h, "case-sensitive", - "Search case sensitively.", - "Search case sensitively. This overrides -i/--ignore-case and \ - -S/--smart-case."); - doc!(h, "smart-case", - "Smart case search.", - "Searches case insensitively if the pattern is all lowercase. \ + match the entire line." + ); + doc!( + h, + "case-sensitive", + "Search case sensitively.", + "Search case sensitively. This overrides -i/--ignore-case and \ + -S/--smart-case." + ); + doc!( + h, + "smart-case", + "Smart case search.", + "Searches case insensitively if the pattern is all lowercase. \ Search case sensitively otherwise. This is overridden by \ - either -s/--case-sensitive or -i/--ignore-case."); - doc!(h, "sort-files", - "Sort results by file path. Implies --threads=1.", - "Sort results by file path. Note that this currently \ - disables all parallelism and runs search in a single thread."); - doc!(h, "threads", - "The approximate number of threads to use.", - "The approximate number of threads to use. A value of 0 (which \ + either -s/--case-sensitive or -i/--ignore-case." + ); + doc!( + h, + "sort-files", + "Sort results by file path. Implies --threads=1.", + "Sort results by file path. Note that this currently \ + disables all parallelism and runs search in a single thread." + ); + doc!( + h, + "threads", + "The approximate number of threads to use.", + "The approximate number of threads to use. A value of 0 (which \ is the default) causes ripgrep to choose the thread count \ - using heuristics."); - doc!(h, "vimgrep", - "Show results in vim compatible format.", - "Show results with every match on its own line, including \ + using heuristics." + ); + doc!( + h, + "vimgrep", + "Show results in vim compatible format.", + "Show results with every match on its own line, including \ line numbers and column numbers. With this option, a line with \ - more than one match will be printed more than once."); - - doc!(h, "type-add", - "Add a new glob for a file type.", - "Add a new glob for a particular file type. Only one glob can be \ + more than one match will be printed more than once." + ); + + doc!( + h, + "type-add", + "Add a new glob for a file type.", + "Add a new glob for a particular file type. Only one glob can be \ added at a time. Multiple --type-add flags can be provided. \ Unless --type-clear is used, globs are added to any existing \ globs defined inside of ripgrep.\n\nNote that this MUST be \ @@ -760,18 +940,24 @@ lazy_static! { using the --type-add flag again:\n\n\ --type-add 'src:include:cpp,py,md' --type-add 'src:*.foo'\n\n\ Note that type names must consist only of Unicode letters or \ - numbers. Punctuation characters are not allowed."); - doc!(h, "type-clear", - "Clear globs for given file type.", - "Clear the file type globs previously defined for TYPE. This \ + numbers. Punctuation characters are not allowed." + ); + doc!( + h, + "type-clear", + "Clear globs for given file type.", + "Clear the file type globs previously defined for TYPE. This \ only clears the default type definitions that are found inside \ of ripgrep.\n\nNote that this MUST be passed to every \ - invocation of ripgrep. Type settings are NOT persisted."); + invocation of ripgrep. Type settings are NOT persisted." + ); h }; } fn validate_number(s: String) -> Result<(), String> { - s.parse::().map(|_| ()).map_err(|err| err.to_string()) + s.parse::() + .map(|_| ()) + .map_err(|err| err.to_string()) } diff --git a/benches/06_rustup.rs b/benches/06_rustup.rs index f9ba477182c..2853152d8e8 100644 --- a/benches/06_rustup.rs +++ b/benches/06_rustup.rs @@ -7,15 +7,19 @@ extern crate clap; extern crate test; -use clap::{App, AppSettings, Arg, Shell, SubCommand, ArgGroup}; +use clap::{App, AppSettings, Arg, ArgGroup, Shell, SubCommand}; use test::Bencher; #[bench] -fn build_app(b: &mut Bencher) { b.iter(|| build_cli()); } +fn build_app(b: &mut Bencher) { + b.iter(|| build_cli()); +} #[bench] -fn parse_clean(b: &mut Bencher) { b.iter(|| build_cli().get_matches_from(vec![""])); } +fn parse_clean(b: &mut Bencher) { + b.iter(|| build_cli().get_matches_from(vec![""])); +} #[bench] fn parse_subcommands(b: &mut Bencher) { @@ -30,220 +34,318 @@ pub fn build_cli() -> App<'static, 'static> { .setting(AppSettings::VersionlessSubcommands) .setting(AppSettings::DeriveDisplayOrder) // .setting(AppSettings::SubcommandRequiredElseHelp) - .arg(Arg::with_name("verbose") - .help("Enable verbose output") - .short("v") - .long("verbose")) - .subcommand(SubCommand::with_name("show") - .about("Show the active and installed toolchains") - .after_help(SHOW_HELP)) - .subcommand(SubCommand::with_name("install") - .about("Update Rust toolchains") - .after_help(TOOLCHAIN_INSTALL_HELP) - .setting(AppSettings::Hidden) // synonym for 'toolchain install' - .arg(Arg::with_name("toolchain") - .required(true))) - .subcommand(SubCommand::with_name("update") - .about("Update Rust toolchains") - .after_help(UPDATE_HELP) - .arg(Arg::with_name("toolchain").required(false)) - .arg(Arg::with_name("no-self-update") - .help("Don't perform self update when running the `rustup` command") - .long("no-self-update") - .takes_value(false) - .hidden(true))) - .subcommand(SubCommand::with_name("default") - .about("Set the default toolchain") - .after_help(DEFAULT_HELP) - .arg(Arg::with_name("toolchain").required(true))) - .subcommand(SubCommand::with_name("toolchain") - .about("Modify or query the installed toolchains") - .after_help(TOOLCHAIN_HELP) - .setting(AppSettings::VersionlessSubcommands) - .setting(AppSettings::DeriveDisplayOrder) - // .setting(AppSettings::SubcommandRequiredElseHelp) - .subcommand(SubCommand::with_name("list").about("List installed toolchains")) - .subcommand(SubCommand::with_name("install") - .about("Install or update a given toolchain") - .arg(Arg::with_name("toolchain").required(true))) - .subcommand(SubCommand::with_name("uninstall") - .about("Uninstall a toolchain") - .arg(Arg::with_name("toolchain").required(true))) - .subcommand(SubCommand::with_name("link") - .about("Create a custom toolchain by symlinking to a directory") + .arg( + Arg::with_name("verbose") + .help("Enable verbose output") + .short("v") + .long("verbose"), + ) + .subcommand( + SubCommand::with_name("show") + .about("Show the active and installed toolchains") + .after_help(SHOW_HELP), + ) + .subcommand( + SubCommand::with_name("install") + .about("Update Rust toolchains") + .after_help(TOOLCHAIN_INSTALL_HELP) + .setting(AppSettings::Hidden) // synonym for 'toolchain install' + .arg(Arg::with_name("toolchain").required(true)), + ) + .subcommand( + SubCommand::with_name("update") + .about("Update Rust toolchains") + .after_help(UPDATE_HELP) + .arg(Arg::with_name("toolchain").required(false)) + .arg( + Arg::with_name("no-self-update") + .help("Don't perform self update when running the `rustup` command") + .long("no-self-update") + .takes_value(false) + .hidden(true), + ), + ) + .subcommand( + SubCommand::with_name("default") + .about("Set the default toolchain") + .after_help(DEFAULT_HELP) + .arg(Arg::with_name("toolchain").required(true)), + ) + .subcommand( + SubCommand::with_name("toolchain") + .about("Modify or query the installed toolchains") + .after_help(TOOLCHAIN_HELP) + .setting(AppSettings::VersionlessSubcommands) + .setting(AppSettings::DeriveDisplayOrder) + // .setting(AppSettings::SubcommandRequiredElseHelp) + .subcommand(SubCommand::with_name("list").about("List installed toolchains")) + .subcommand( + SubCommand::with_name("install") + .about("Install or update a given toolchain") + .arg(Arg::with_name("toolchain").required(true)), + ) + .subcommand( + SubCommand::with_name("uninstall") + .about("Uninstall a toolchain") + .arg(Arg::with_name("toolchain").required(true)), + ) + .subcommand( + SubCommand::with_name("link") + .about("Create a custom toolchain by symlinking to a directory") + .arg(Arg::with_name("toolchain").required(true)) + .arg(Arg::with_name("path").required(true)), + ) + .subcommand( + SubCommand::with_name("update") + .setting(AppSettings::Hidden) // synonym for 'install' + .arg(Arg::with_name("toolchain").required(true)), + ) + .subcommand( + SubCommand::with_name("add") + .setting(AppSettings::Hidden) // synonym for 'install' + .arg(Arg::with_name("toolchain").required(true)), + ) + .subcommand( + SubCommand::with_name("remove") + .setting(AppSettings::Hidden) // synonym for 'uninstall' + .arg(Arg::with_name("toolchain").required(true)), + ), + ) + .subcommand( + SubCommand::with_name("target") + .about("Modify a toolchain's supported targets") + .setting(AppSettings::VersionlessSubcommands) + .setting(AppSettings::DeriveDisplayOrder) + // .setting(AppSettings::SubcommandRequiredElseHelp) + .subcommand( + SubCommand::with_name("list") + .about("List installed and available targets") + .arg( + Arg::with_name("toolchain") + .long("toolchain") + .takes_value(true), + ), + ) + .subcommand( + SubCommand::with_name("add") + .about("Add a target to a Rust toolchain") + .arg(Arg::with_name("target").required(true)) + .arg( + Arg::with_name("toolchain") + .long("toolchain") + .takes_value(true), + ), + ) + .subcommand( + SubCommand::with_name("remove") + .about("Remove a target from a Rust toolchain") + .arg(Arg::with_name("target").required(true)) + .arg( + Arg::with_name("toolchain") + .long("toolchain") + .takes_value(true), + ), + ) + .subcommand( + SubCommand::with_name("install") + .setting(AppSettings::Hidden) // synonym for 'add' + .arg(Arg::with_name("target").required(true)) + .arg( + Arg::with_name("toolchain") + .long("toolchain") + .takes_value(true), + ), + ) + .subcommand( + SubCommand::with_name("uninstall") + .setting(AppSettings::Hidden) // synonym for 'remove' + .arg(Arg::with_name("target").required(true)) + .arg( + Arg::with_name("toolchain") + .long("toolchain") + .takes_value(true), + ), + ), + ) + .subcommand( + SubCommand::with_name("component") + .about("Modify a toolchain's installed components") + .setting(AppSettings::VersionlessSubcommands) + .setting(AppSettings::DeriveDisplayOrder) + // .setting(AppSettings::SubcommandRequiredElseHelp) + .subcommand( + SubCommand::with_name("list") + .about("List installed and available components") + .arg( + Arg::with_name("toolchain") + .long("toolchain") + .takes_value(true), + ), + ) + .subcommand( + SubCommand::with_name("add") + .about("Add a component to a Rust toolchain") + .arg(Arg::with_name("component").required(true)) + .arg( + Arg::with_name("toolchain") + .long("toolchain") + .takes_value(true), + ) + .arg(Arg::with_name("target").long("target").takes_value(true)), + ) + .subcommand( + SubCommand::with_name("remove") + .about("Remove a component from a Rust toolchain") + .arg(Arg::with_name("component").required(true)) + .arg( + Arg::with_name("toolchain") + .long("toolchain") + .takes_value(true), + ) + .arg(Arg::with_name("target").long("target").takes_value(true)), + ), + ) + .subcommand( + SubCommand::with_name("override") + .about("Modify directory toolchain overrides") + .after_help(OVERRIDE_HELP) + .setting(AppSettings::VersionlessSubcommands) + .setting(AppSettings::DeriveDisplayOrder) + // .setting(AppSettings::SubcommandRequiredElseHelp) + .subcommand( + SubCommand::with_name("list").about("List directory toolchain overrides"), + ) + .subcommand( + SubCommand::with_name("set") + .about("Set the override toolchain for a directory") + .arg(Arg::with_name("toolchain").required(true)), + ) + .subcommand( + SubCommand::with_name("unset") + .about("Remove the override toolchain for a directory") + .after_help(OVERRIDE_UNSET_HELP) + .arg( + Arg::with_name("path") + .long("path") + .takes_value(true) + .help("Path to the directory"), + ) + .arg( + Arg::with_name("nonexistent") + .long("nonexistent") + .takes_value(false) + .help("Remove override toolchain for all nonexistent directories"), + ), + ) + .subcommand( + SubCommand::with_name("add") + .setting(AppSettings::Hidden) // synonym for 'set' + .arg(Arg::with_name("toolchain").required(true)), + ) + .subcommand( + SubCommand::with_name("remove") + .setting(AppSettings::Hidden) // synonym for 'unset' + .about("Remove the override toolchain for a directory") + .arg(Arg::with_name("path").long("path").takes_value(true)) + .arg( + Arg::with_name("nonexistent") + .long("nonexistent") + .takes_value(false) + .help("Remove override toolchain for all nonexistent directories"), + ), + ), + ) + .subcommand( + SubCommand::with_name("run") + .about("Run a command with an environment configured for a given toolchain") + .after_help(RUN_HELP) + .setting(AppSettings::TrailingVarArg) .arg(Arg::with_name("toolchain").required(true)) - .arg(Arg::with_name("path").required(true))) - .subcommand(SubCommand::with_name("update") - .setting(AppSettings::Hidden) // synonym for 'install' - .arg(Arg::with_name("toolchain") - .required(true))) - .subcommand(SubCommand::with_name("add") - .setting(AppSettings::Hidden) // synonym for 'install' - .arg(Arg::with_name("toolchain") - .required(true))) - .subcommand(SubCommand::with_name("remove") - .setting(AppSettings::Hidden) // synonym for 'uninstall' - .arg(Arg::with_name("toolchain") - .required(true)))) - .subcommand(SubCommand::with_name("target") - .about("Modify a toolchain's supported targets") - .setting(AppSettings::VersionlessSubcommands) - .setting(AppSettings::DeriveDisplayOrder) - // .setting(AppSettings::SubcommandRequiredElseHelp) - .subcommand(SubCommand::with_name("list") - .about("List installed and available targets") - .arg(Arg::with_name("toolchain") - .long("toolchain") - .takes_value(true))) - .subcommand(SubCommand::with_name("add") - .about("Add a target to a Rust toolchain") - .arg(Arg::with_name("target").required(true)) - .arg(Arg::with_name("toolchain") - .long("toolchain") - .takes_value(true))) - .subcommand(SubCommand::with_name("remove") - .about("Remove a target from a Rust toolchain") - .arg(Arg::with_name("target").required(true)) - .arg(Arg::with_name("toolchain") - .long("toolchain") - .takes_value(true))) - .subcommand(SubCommand::with_name("install") - .setting(AppSettings::Hidden) // synonym for 'add' - .arg(Arg::with_name("target") - .required(true)) - .arg(Arg::with_name("toolchain") - .long("toolchain") - .takes_value(true))) - .subcommand(SubCommand::with_name("uninstall") - .setting(AppSettings::Hidden) // synonym for 'remove' - .arg(Arg::with_name("target") - .required(true)) - .arg(Arg::with_name("toolchain") - .long("toolchain") - .takes_value(true)))) - .subcommand(SubCommand::with_name("component") - .about("Modify a toolchain's installed components") - .setting(AppSettings::VersionlessSubcommands) - .setting(AppSettings::DeriveDisplayOrder) - // .setting(AppSettings::SubcommandRequiredElseHelp) - .subcommand(SubCommand::with_name("list") - .about("List installed and available components") - .arg(Arg::with_name("toolchain") - .long("toolchain") - .takes_value(true))) - .subcommand(SubCommand::with_name("add") - .about("Add a component to a Rust toolchain") - .arg(Arg::with_name("component").required(true)) - .arg(Arg::with_name("toolchain") - .long("toolchain") - .takes_value(true)) - .arg(Arg::with_name("target") - .long("target") - .takes_value(true))) - .subcommand(SubCommand::with_name("remove") - .about("Remove a component from a Rust toolchain") - .arg(Arg::with_name("component").required(true)) - .arg(Arg::with_name("toolchain") - .long("toolchain") - .takes_value(true)) - .arg(Arg::with_name("target") - .long("target") - .takes_value(true)))) - .subcommand(SubCommand::with_name("override") - .about("Modify directory toolchain overrides") - .after_help(OVERRIDE_HELP) - .setting(AppSettings::VersionlessSubcommands) - .setting(AppSettings::DeriveDisplayOrder) - // .setting(AppSettings::SubcommandRequiredElseHelp) - .subcommand(SubCommand::with_name("list").about("List directory toolchain overrides")) - .subcommand(SubCommand::with_name("set") - .about("Set the override toolchain for a directory") - .arg(Arg::with_name("toolchain").required(true))) - .subcommand(SubCommand::with_name("unset") - .about("Remove the override toolchain for a directory") - .after_help(OVERRIDE_UNSET_HELP) - .arg(Arg::with_name("path") - .long("path") - .takes_value(true) - .help("Path to the directory")) - .arg(Arg::with_name("nonexistent") - .long("nonexistent") - .takes_value(false) - .help("Remove override toolchain for all nonexistent directories"))) - .subcommand(SubCommand::with_name("add") - .setting(AppSettings::Hidden) // synonym for 'set' - .arg(Arg::with_name("toolchain") - .required(true))) - .subcommand(SubCommand::with_name("remove") - .setting(AppSettings::Hidden) // synonym for 'unset' - .about("Remove the override toolchain for a directory") - .arg(Arg::with_name("path") - .long("path") - .takes_value(true)) - .arg(Arg::with_name("nonexistent") - .long("nonexistent") - .takes_value(false) - .help("Remove override toolchain for all nonexistent directories")))) - .subcommand(SubCommand::with_name("run") - .about("Run a command with an environment configured for a given toolchain") - .after_help(RUN_HELP) - .setting(AppSettings::TrailingVarArg) - .arg(Arg::with_name("toolchain").required(true)) - .arg(Arg::with_name("command") - .required(true) - .multiple(true) - .use_delimiter(false))) - .subcommand(SubCommand::with_name("which") - .about("Display which binary will be run for a given command") - .arg(Arg::with_name("command").required(true))) - .subcommand(SubCommand::with_name("doc") - .about("Open the documentation for the current toolchain") - .after_help(DOC_HELP) - .arg(Arg::with_name("book") - .long("book") - .help("The Rust Programming Language book")) - .arg(Arg::with_name("std") - .long("std") - .help("Standard library API documentation")) - .group(ArgGroup::with_name("page").args(&["book", "std"]))) - .subcommand(SubCommand::with_name("man") - .about("View the man page for a given command") - .arg(Arg::with_name("command").required(true)) - .arg(Arg::with_name("toolchain") - .long("toolchain") - .takes_value(true))) - .subcommand(SubCommand::with_name("self") - .about("Modify the rustup installation") - .setting(AppSettings::VersionlessSubcommands) - .setting(AppSettings::DeriveDisplayOrder) - // .setting(AppSettings::SubcommandRequiredElseHelp) - .subcommand(SubCommand::with_name("update") - .about("Download and install updates to rustup")) - .subcommand(SubCommand::with_name("uninstall") - .about("Uninstall rustup.") - .arg(Arg::with_name("no-prompt").short("y"))) - .subcommand(SubCommand::with_name("upgrade-data") - .about("Upgrade the internal data format."))) - .subcommand(SubCommand::with_name("telemetry") - .about("rustup telemetry commands") - .setting(AppSettings::Hidden) - .setting(AppSettings::VersionlessSubcommands) - .setting(AppSettings::DeriveDisplayOrder) - // .setting(AppSettings::SubcommandRequiredElseHelp) - .subcommand(SubCommand::with_name("enable").about("Enable rustup telemetry")) - .subcommand(SubCommand::with_name("disable").about("Disable rustup telemetry")) - .subcommand(SubCommand::with_name("analyze").about("Analyze stored telemetry"))) - .subcommand(SubCommand::with_name("set") - .about("Alter rustup settings") - // .setting(AppSettings::SubcommandRequiredElseHelp) - .subcommand(SubCommand::with_name("default-host") - .about("The triple used to identify toolchains when not specified") - .arg(Arg::with_name("host_triple").required(true)))) - .subcommand(SubCommand::with_name("completions") - .about("Generate completion scripts for your shell") - .after_help(COMPLETIONS_HELP) - .setting(AppSettings::ArgRequiredElseHelp) - .arg(Arg::with_name("shell").possible_values(&Shell::variants()))) + .arg( + Arg::with_name("command") + .required(true) + .multiple(true) + .use_delimiter(false), + ), + ) + .subcommand( + SubCommand::with_name("which") + .about("Display which binary will be run for a given command") + .arg(Arg::with_name("command").required(true)), + ) + .subcommand( + SubCommand::with_name("doc") + .about("Open the documentation for the current toolchain") + .after_help(DOC_HELP) + .arg( + Arg::with_name("book") + .long("book") + .help("The Rust Programming Language book"), + ) + .arg( + Arg::with_name("std") + .long("std") + .help("Standard library API documentation"), + ) + .group(ArgGroup::with_name("page").args(&["book", "std"])), + ) + .subcommand( + SubCommand::with_name("man") + .about("View the man page for a given command") + .arg(Arg::with_name("command").required(true)) + .arg( + Arg::with_name("toolchain") + .long("toolchain") + .takes_value(true), + ), + ) + .subcommand( + SubCommand::with_name("self") + .about("Modify the rustup installation") + .setting(AppSettings::VersionlessSubcommands) + .setting(AppSettings::DeriveDisplayOrder) + // .setting(AppSettings::SubcommandRequiredElseHelp) + .subcommand( + SubCommand::with_name("update").about("Download and install updates to rustup"), + ) + .subcommand( + SubCommand::with_name("uninstall") + .about("Uninstall rustup.") + .arg(Arg::with_name("no-prompt").short("y")), + ) + .subcommand( + SubCommand::with_name("upgrade-data") + .about("Upgrade the internal data format."), + ), + ) + .subcommand( + SubCommand::with_name("telemetry") + .about("rustup telemetry commands") + .setting(AppSettings::Hidden) + .setting(AppSettings::VersionlessSubcommands) + .setting(AppSettings::DeriveDisplayOrder) + // .setting(AppSettings::SubcommandRequiredElseHelp) + .subcommand(SubCommand::with_name("enable").about("Enable rustup telemetry")) + .subcommand(SubCommand::with_name("disable").about("Disable rustup telemetry")) + .subcommand(SubCommand::with_name("analyze").about("Analyze stored telemetry")), + ) + .subcommand( + SubCommand::with_name("set") + .about("Alter rustup settings") + // .setting(AppSettings::SubcommandRequiredElseHelp) + .subcommand( + SubCommand::with_name("default-host") + .about("The triple used to identify toolchains when not specified") + .arg(Arg::with_name("host_triple").required(true)), + ), + ) + .subcommand( + SubCommand::with_name("completions") + .about("Generate completion scripts for your shell") + .after_help(COMPLETIONS_HELP) + .setting(AppSettings::ArgRequiredElseHelp) + .arg(Arg::with_name("shell").possible_values(&Shell::variants())), + ) } static RUSTUP_HELP: &'static str = r" diff --git a/examples/01a_quick_example.rs b/examples/01a_quick_example.rs index c7fa20f9048..0a81da78373 100644 --- a/examples/01a_quick_example.rs +++ b/examples/01a_quick_example.rs @@ -3,7 +3,6 @@ extern crate clap; use clap::{App, SubCommand}; fn main() { - // This example shows how to create an application with several arguments using usage strings, which can be // far less verbose that shown in 01b_QuickExample.rs, but is more readable. The downside is you cannot set // the more advanced configuration options using this method (well...actually you can, you'll see ;) ) @@ -33,16 +32,20 @@ fn main() { // - A subcommand "help" (automatically generated by clap because we specified a subcommand of our own) // + Used by "$ myapp help" (same functionality as "-h" or "--help") let matches = App::new("MyApp") - .version("1.0") - .author("Kevin K. ") - .about("Does awesome things") - .args_from_usage("-c, --config=[FILE] 'Sets a custom config file' + .version("1.0") + .author("Kevin K. ") + .about("Does awesome things") + .args_from_usage( + "-c, --config=[FILE] 'Sets a custom config file' 'Sets an optional output file' - -d... 'Turn debugging information on'") - .subcommand(SubCommand::with_name("test") - .about("does testing things") - .arg_from_usage("-l, --list 'lists test values'")) - .get_matches(); + -d... 'Turn debugging information on'", + ) + .subcommand( + SubCommand::with_name("test") + .about("does testing things") + .arg_from_usage("-l, --list 'lists test values'"), + ) + .get_matches(); // You can check the value provided by positional arguments, or option arguments if let Some(o) = matches.value_of("output") { @@ -60,7 +63,7 @@ fn main() { 1 => println!("Debug mode is kind of on"), 2 => println!("Debug mode is on"), 3 | _ => 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 @@ -74,6 +77,5 @@ fn main() { } } - // Continued program logic goes here... } diff --git a/examples/01b_quick_example.rs b/examples/01b_quick_example.rs index 7f455a82657..f117babac62 100644 --- a/examples/01b_quick_example.rs +++ b/examples/01b_quick_example.rs @@ -3,7 +3,6 @@ extern crate clap; use clap::{App, Arg, SubCommand}; fn main() { - // This method shows the traditional, and slightly more configurable way to set up arguments. This method is // more verbose, but allows setting more configuration options, and even supports easier dynamic generation. // @@ -35,28 +34,34 @@ fn main() { // - A subcommand "help" (automatically generated by clap because we specified a subcommand of our own) // + Used by "$ myapp help" (same functionality as "-h" or "--help") let matches = App::new("MyApp") - .version("1.0") - .author("Kevin K. ") - .about("Does awesome things") - .arg(Arg::with_name("config") - .short("c") - .long("config") - .value_name("FILE") - .help("Sets a custom config file") - .takes_value(true)) - .arg(Arg::with_name("output") - .help("Sets an optional output file") - .index(1)) - .arg(Arg::with_name("debug") - .short("d") - .multiple(true) - .help("Turn debugging information on")) - .subcommand(SubCommand::with_name("test") - .about("does testing things") - .arg(Arg::with_name("list") - .short("l") - .help("lists test values"))) - .get_matches(); + .version("1.0") + .author("Kevin K. ") + .about("Does awesome things") + .arg( + Arg::with_name("config") + .short("c") + .long("config") + .value_name("FILE") + .help("Sets a custom config file") + .takes_value(true), + ) + .arg( + Arg::with_name("output") + .help("Sets an optional output file") + .index(1), + ) + .arg( + Arg::with_name("debug") + .short("d") + .multiple(true) + .help("Turn debugging information on"), + ) + .subcommand( + SubCommand::with_name("test") + .about("does testing things") + .arg(Arg::with_name("list").short("l").help("lists test values")), + ) + .get_matches(); // You can check the value provided by positional arguments, or option arguments if let Some(o) = matches.value_of("output") { @@ -74,7 +79,7 @@ fn main() { 1 => println!("Debug mode is kind of on"), 2 => println!("Debug mode is on"), 3 | _ => 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 @@ -88,6 +93,5 @@ fn main() { } } - // Continued program logic goes here... } diff --git a/examples/01c_quick_example.rs b/examples/01c_quick_example.rs index 071bdc0a10b..2197a6429ca 100644 --- a/examples/01c_quick_example.rs +++ b/examples/01c_quick_example.rs @@ -42,7 +42,8 @@ fn main() { (author: "Someone E. ") (@arg verbose: -v --verbose "Print test information verbosely") ) - ).get_matches(); + ) + .get_matches(); // Calling .unwrap() is safe here because "INPUT" is required (if "INPUT" wasn't // required we could have used an 'if let' to conditionally get the value) diff --git a/examples/03_args.rs b/examples/03_args.rs index c62d57637d5..5f3956a72ae 100644 --- a/examples/03_args.rs +++ b/examples/03_args.rs @@ -26,46 +26,53 @@ fn main() { // safely override "-V" and "-h" to your own arguments, and "--help" and "--version" will still // be automatically generated for you. let matches = App::new("MyApp") - // All application settings go here... - - // A simple "Flag" argument example (i.e. "-d") using the builder pattern - .arg(Arg::with_name("debug") - .help("turn on debugging information") - .short("d")) - - // Two arguments, one "Option" argument (i.e. one that takes a value) such - // as "-c some", and one positional argument (i.e. "myapp some_file") - .args(&[ - Arg::with_name("config") - .help("sets the config file to use") - .takes_value(true) - .short("c") - .long("config"), - Arg::with_name("input") - .help("the input file to use") - .index(1) - .required(true) - ]) - - // *Note* the following two examples are convenience methods, if you wish - // to still get the full configurability of Arg::with_name() and the readability - // of arg_from_usage(), you can instantiate a new Arg with Arg::from_usage() and - // still be able to set all the additional properties, just like Arg::with_name() - // - // - // One "Flag" using a usage string - .arg_from_usage("--license 'display the license file'") - - // Two args, one "Positional", and one "Option" using a usage string - .args_from_usage("[output] 'Supply an output file to use' - -i, --int=[IFACE] 'Set an interface to use'") - .get_matches(); + // All application settings go here... + // A simple "Flag" argument example (i.e. "-d") using the builder pattern + .arg( + Arg::with_name("debug") + .help("turn on debugging information") + .short("d"), + ) + // Two arguments, one "Option" argument (i.e. one that takes a value) such + // as "-c some", and one positional argument (i.e. "myapp some_file") + .args(&[ + Arg::with_name("config") + .help("sets the config file to use") + .takes_value(true) + .short("c") + .long("config"), + Arg::with_name("input") + .help("the input file to use") + .index(1) + .required(true), + ]) + // *Note* the following two examples are convenience methods, if you wish + // to still get the full configurability of Arg::with_name() and the readability + // of arg_from_usage(), you can instantiate a new Arg with Arg::from_usage() and + // still be able to set all the additional properties, just like Arg::with_name() + // + // + // One "Flag" using a usage string + .arg_from_usage("--license 'display the license file'") + // Two args, one "Positional", and one "Option" using a usage string + .args_from_usage( + "[output] 'Supply an output file to use' + -i, --int=[IFACE] 'Set an interface to use'", + ) + .get_matches(); // Here are some examples of using the arguments defined above. Keep in mind that this is only // an example, and may be somewhat contrived // // First we check if debugging should be on or not - println!("Debugging mode is: {}", if matches.is_present("debug") { "ON" } else { "OFF" }); + println!( + "Debugging mode is: {}", + if matches.is_present("debug") { + "ON" + } else { + "OFF" + } + ); // Next we print the config file we're using, if any was defined with either -c or // --config diff --git a/examples/04_using_matches.rs b/examples/04_using_matches.rs index a0a986f9830..f118acc6b9f 100644 --- a/examples/04_using_matches.rs +++ b/examples/04_using_matches.rs @@ -3,7 +3,6 @@ extern crate clap; use clap::{App, Arg}; fn main() { - // Once all App settings (including all arguments) have been set, you call get_matches() which // parses the string provided by the user, and returns all the valid matches to the ones you // specified. @@ -18,22 +17,28 @@ fn main() { // argument which is the input file we want to work with, this will be the only required // argument. let matches = App::new("MyApp") - .about("Parses an input file to do awesome things") - .version("1.0") - .author("Kevin K. ") - .arg(Arg::with_name("debug") - .help("turn on debugging information") - .short("d") - .long("debug")) - .arg(Arg::with_name("config") - .help("sets the config file to use") - .short("c") - .long("config")) - .arg(Arg::with_name("input") - .help("the input file to use") - .index(1) - .required(true)) - .get_matches(); + .about("Parses an input file to do awesome things") + .version("1.0") + .author("Kevin K. ") + .arg( + Arg::with_name("debug") + .help("turn on debugging information") + .short("d") + .long("debug"), + ) + .arg( + Arg::with_name("config") + .help("sets the config file to use") + .short("c") + .long("config"), + ) + .arg( + Arg::with_name("input") + .help("the input file to use") + .index(1) + .required(true), + ) + .get_matches(); // We can find out whether or not debugging was turned on if matches.is_present("debug") { @@ -48,7 +53,10 @@ fn main() { // Because "input" is required we can safely call unwrap() because had the user NOT // specified a value, clap would have explained the error the user, and exited. - println!("Doing real work with file: {}", matches.value_of("input").unwrap() ); + println!( + "Doing real work with file: {}", + matches.value_of("input").unwrap() + ); // Continued program logic goes here... } diff --git a/examples/05_flag_args.rs b/examples/05_flag_args.rs index a6b89456971..9900b3839a0 100644 --- a/examples/05_flag_args.rs +++ b/examples/05_flag_args.rs @@ -3,38 +3,37 @@ extern crate clap; use clap::{App, Arg}; fn main() { - // Of the three argument types, flags are the most simple. Flags are simple switches which can // be either "on" or "off" // // clap also supports multiple occurrences of flags, the common example is "verbosity" where a // user could want a little information with "-v" or tons of information with "-v -v" or "-vv" let matches = App::new("MyApp") - // Regular App configuration goes here... - - // We'll add a flag that represents an awesome meter... - // - // I'll explain each possible setting that "flags" accept. Keep in mind - // that you DO NOT need to set each of these for every flag, only the ones - // you want for your individual case. - .arg(Arg::with_name("awesome") - .help("turns up the awesome") // Displayed when showing help info - .short("a") // Trigger this arg with "-a" - .long("awesome") // Trigger this arg with "--awesome" - .multiple(true) // This flag should allow multiple - // occurrences such as "-aaa" or "-a -a" - .requires("config") // Says, "If the user uses -a, they MUST - // also use this other 'config' arg too" - // Can also specify a list using - // requires_all(Vec<&str>) - .conflicts_with("output") // Opposite of requires(), says "if the - // user uses -a, they CANNOT use 'output'" - // also has a conflicts_with_all(Vec<&str>) - ) - // NOTE: In order to compile this example, comment out requires() and - // conflicts_with() because we have not defined an "output" or "config" - // argument. - .get_matches(); + // Regular App configuration goes here... + // We'll add a flag that represents an awesome meter... + // + // I'll explain each possible setting that "flags" accept. Keep in mind + // that you DO NOT need to set each of these for every flag, only the ones + // you want for your individual case. + .arg( + Arg::with_name("awesome") + .help("turns up the awesome") // Displayed when showing help info + .short("a") // Trigger this arg with "-a" + .long("awesome") // Trigger this arg with "--awesome" + .multiple(true) // This flag should allow multiple + // occurrences such as "-aaa" or "-a -a" + .requires("config") // Says, "If the user uses -a, they MUST + // also use this other 'config' arg too" + // Can also specify a list using + // requires_all(Vec<&str>) + .conflicts_with("output"), // Opposite of requires(), says "if the + // user uses -a, they CANNOT use 'output'" + // also has a conflicts_with_all(Vec<&str>) + ) + // NOTE: In order to compile this example, comment out requires() and + // conflicts_with() because we have not defined an "output" or "config" + // argument. + .get_matches(); // We can find out whether or not awesome was used if matches.is_present("awesome") { diff --git a/examples/06_positional_args.rs b/examples/06_positional_args.rs index 1f29612e970..9d2596da79e 100644 --- a/examples/06_positional_args.rs +++ b/examples/06_positional_args.rs @@ -3,44 +3,44 @@ extern crate clap; use clap::{App, Arg}; fn main() { - // Positional arguments are those values after the program name which are not preceded by any // identifier (such as "myapp some_file"). Positionals support many of the same options as // flags, as well as a few additional ones. let matches = App::new("MyApp") - // Regular App configuration goes here... - - // We'll add two positional arguments, a input file, and a config file. - // - // I'll explain each possible setting that "positionals" accept. Keep in - // mind that you DO NOT need to set each of these for every flag, only the - // ones that apply to your individual case. - .arg(Arg::with_name("input") - .help("the input file to use") // Displayed when showing help info - .index(1) // Set the order in which the user must - // specify this argument (Starts at 1) - .requires("config") // Says, "If the user uses "input", they MUST - // also use this other 'config' arg too" - // Can also specify a list using - // requires_all(Vec<&str>) - .conflicts_with("output") // Opposite of requires(), says "if the - // user uses -a, they CANNOT use 'output'" - // also has a conflicts_with_all(Vec<&str>) - .required(true) // By default this argument MUST be present - // NOTE: mutual exclusions take precedence over - // required arguments - ) - .arg(Arg::with_name("config") - .help("the config file to use") - .index(2)) // Note, we do not need to specify required(true) - // if we don't want to, because "input" already - // requires "config" - // Note, we also do not need to specify requires("input") - // because requires lists are automatically two-way - - // NOTE: In order to compile this example, comment out conflicts_with() - // because we have not defined an "output" argument. - .get_matches(); + // Regular App configuration goes here... + // We'll add two positional arguments, a input file, and a config file. + // + // I'll explain each possible setting that "positionals" accept. Keep in + // mind that you DO NOT need to set each of these for every flag, only the + // ones that apply to your individual case. + .arg( + Arg::with_name("input") + .help("the input file to use") // Displayed when showing help info + .index(1) // Set the order in which the user must + // specify this argument (Starts at 1) + .requires("config") // Says, "If the user uses "input", they MUST + // also use this other 'config' arg too" + // Can also specify a list using + // requires_all(Vec<&str>) + .conflicts_with("output") // Opposite of requires(), says "if the + // user uses -a, they CANNOT use 'output'" + // also has a conflicts_with_all(Vec<&str>) + .required(true), // By default this argument MUST be present + // NOTE: mutual exclusions take precedence over + // required arguments + ) + .arg( + Arg::with_name("config") + .help("the config file to use") + .index(2), + ) // Note, we do not need to specify required(true) + // if we don't want to, because "input" already + // requires "config" + // Note, we also do not need to specify requires("input") + // because requires lists are automatically two-way + // NOTE: In order to compile this example, comment out conflicts_with() + // because we have not defined an "output" argument. + .get_matches(); // We can find out whether or not "input" or "config" were used if matches.is_present("input") { @@ -50,7 +50,11 @@ fn main() { // We can also get the values for those arguments if let Some(in_file) = matches.value_of("input") { // It's safe to call unwrap() because of the required options we set above - println!("Doing work with {} and {}", in_file, matches.value_of("config").unwrap()); + println!( + "Doing work with {} and {}", + in_file, + matches.value_of("config").unwrap() + ); } // Continued program logic goes here... } diff --git a/examples/07_option_args.rs b/examples/07_option_args.rs index 85ff0e53d30..e0e46119fb5 100644 --- a/examples/07_option_args.rs +++ b/examples/07_option_args.rs @@ -3,42 +3,41 @@ extern crate clap; use clap::{App, Arg}; fn main() { - // Option arguments are those that take an additional value, such as "-c value". In clap they // support three types of specification, those with short() as "-o some", or those with long() // as "--option value" or "--option=value" // // Options also support a multiple setting, which is discussed in the example below. let matches = App::new("MyApp") - // Regular App configuration goes here... - - // Assume we have an application that accepts an input file via the "-i file" - // or the "--input file" (as well as "--input=file"). - // Below every setting supported by option arguments is discussed. - // NOTE: You DO NOT need to specify each setting, only those which apply - // to your particular case. - .arg(Arg::with_name("input") - .help("the input file to use") // Displayed when showing help info - .takes_value(true) // MUST be set to true in order to be an "option" argument - .short("i") // This argument is triggered with "-i" - .long("input") // This argument is triggered with "--input" - .multiple(true) // Set to true if you wish to allow multiple occurrences - // such as "-i file -i other_file -i third_file" - .required(true) // By default this argument MUST be present - // NOTE: mutual exclusions take precedence over - // required arguments - .requires("config") // Says, "If the user uses "input", they MUST - // also use this other 'config' arg too" - // Can also specify a list using - // requires_all(Vec<&str>) - .conflicts_with("output") // Opposite of requires(), says "if the - // user uses -a, they CANNOT use 'output'" - // also has a conflicts_with_all(Vec<&str>) - ) - // NOTE: In order to compile this example, comment out conflicts_with() - // and requires() because we have not defined an "output" or "config" - // argument. - .get_matches(); + // Regular App configuration goes here... + // Assume we have an application that accepts an input file via the "-i file" + // or the "--input file" (as well as "--input=file"). + // Below every setting supported by option arguments is discussed. + // NOTE: You DO NOT need to specify each setting, only those which apply + // to your particular case. + .arg( + Arg::with_name("input") + .help("the input file to use") // Displayed when showing help info + .takes_value(true) // MUST be set to true in order to be an "option" argument + .short("i") // This argument is triggered with "-i" + .long("input") // This argument is triggered with "--input" + .multiple(true) // Set to true if you wish to allow multiple occurrences + // such as "-i file -i other_file -i third_file" + .required(true) // By default this argument MUST be present + // NOTE: mutual exclusions take precedence over + // required arguments + .requires("config") // Says, "If the user uses "input", they MUST + // also use this other 'config' arg too" + // Can also specify a list using + // requires_all(Vec<&str>) + .conflicts_with("output"), // Opposite of requires(), says "if the + // user uses -a, they CANNOT use 'output'" + // also has a conflicts_with_all(Vec<&str>) + ) + // NOTE: In order to compile this example, comment out conflicts_with() + // and requires() because we have not defined an "output" or "config" + // argument. + .get_matches(); // We can find out whether or not "input" was used if matches.is_present("input") { @@ -65,7 +64,10 @@ fn main() { // NOTE: Just like with flags, if we did not specify the multiple() setting this will only // return 1 no matter how many times the argument was used (unless it wasn't used at all, in // in which case 0 is returned) - println!("The \"input\" argument was used {} times", matches.occurrences_of("input")); + println!( + "The \"input\" argument was used {} times", + matches.occurrences_of("input") + ); // Continued program logic goes here... } diff --git a/examples/08_subcommands.rs b/examples/08_subcommands.rs index 73bd09830a2..cad260bc0a1 100644 --- a/examples/08_subcommands.rs +++ b/examples/08_subcommands.rs @@ -3,7 +3,6 @@ extern crate clap; use clap::{App, Arg, SubCommand}; fn main() { - // SubCommands function exactly like sub-Apps, because that's exactly what they are. Each // instance of a SubCommand can have it's own version, author(s), Args, and even it's own // subcommands. @@ -19,21 +18,24 @@ fn main() { // Just like arg() and args(), subcommands can be specified one at a time via subcommand() or // multiple ones at once with a Vec provided to subcommands(). let matches = App::new("MyApp") - // Normal App and Arg configuration goes here... - - // In the following example assume we wanted an application which - // supported an "add" subcommand, this "add" subcommand also took - // one positional argument of a file to add: - .subcommand(SubCommand::with_name("add") // The name we call argument with - .about("Adds files to myapp") // The message displayed in "myapp -h" - // or "myapp help" - .version("0.1") // Subcommands can have independent version - .author("Kevin K.") // And authors - .arg(Arg::with_name("input") // And their own arguments - .help("the file to add") - .index(1) - .required(true))) - .get_matches(); + // Normal App and Arg configuration goes here... + // In the following example assume we wanted an application which + // supported an "add" subcommand, this "add" subcommand also took + // one positional argument of a file to add: + .subcommand( + SubCommand::with_name("add") // The name we call argument with + .about("Adds files to myapp") // The message displayed in "myapp -h" + // or "myapp help" + .version("0.1") // Subcommands can have independent version + .author("Kevin K.") // And authors + .arg( + Arg::with_name("input") // And their own arguments + .help("the file to add") + .index(1) + .required(true), + ), + ) + .get_matches(); // You can check if a subcommand was used like normal if matches.is_present("add") { @@ -49,8 +51,8 @@ fn main() { // You can also match on a subcommand's name match matches.subcommand_name() { Some("add") => println!("'myapp add' was used"), - None => println!("No subcommand was used"), - _ => println!("Some other subcommand was used"), + None => println!("No subcommand was used"), + _ => println!("Some other subcommand was used"), } // Continued program logic goes here... diff --git a/examples/09_auto_version.rs b/examples/09_auto_version.rs index dfd221f082b..ea6d75f964f 100644 --- a/examples/09_auto_version.rs +++ b/examples/09_auto_version.rs @@ -20,9 +20,9 @@ fn main() { // Thanks to https://github.com/jhelwig for pointing this out App::new("myapp") .about("does awesome things") - // use crate_version! to pull the version number - .version(crate_version!()) - .get_matches(); + // use crate_version! to pull the version number + .version(crate_version!()) + .get_matches(); // running this app with the -V or --version will display whatever version is in your // Cargo.toml, the default being: myapp 0.0.1 diff --git a/examples/10_default_values.rs b/examples/10_default_values.rs index ca509817b35..2049f6029b3 100644 --- a/examples/10_default_values.rs +++ b/examples/10_default_values.rs @@ -9,24 +9,28 @@ fn main() { // I'll demo both here. // // First, we'll use clap's Arg::default_value with an "INPUT" file. - let matches = App::new("myapp").about("does awesome things") - .arg(Arg::with_name("INPUT") - .help("The input file to use") // Note, we don't need to specify - // anything like, "Defaults to..." - // because clap will automatically - // generate that for us, and place - // it in the help text - .default_value("input.txt") - .index(1)) - - // Next we'll use the Option::unwrap_or method on this "CONFIG" option - .arg(Arg::with_name("CONFIG") - // Note that we have to manually include some verbiage to the user - // telling them what the default will be. - .help("The config file to use (default is \"config.json\")") - .short("c") - .takes_value(true)) - .get_matches(); + let matches = App::new("myapp") + .about("does awesome things") + .arg( + Arg::with_name("INPUT") + .help("The input file to use") // Note, we don't need to specify + // anything like, "Defaults to..." + // because clap will automatically + // generate that for us, and place + // it in the help text + .default_value("input.txt") + .index(1), + ) + // Next we'll use the Option::unwrap_or method on this "CONFIG" option + .arg( + Arg::with_name("CONFIG") + // Note that we have to manually include some verbiage to the user + // telling them what the default will be. + .help("The config file to use (default is \"config.json\")") + .short("c") + .takes_value(true), + ) + .get_matches(); // It's safe to call unwrap because the value with either be what the user input at runtime // or "input.txt" diff --git a/examples/11_only_specific_values.rs b/examples/11_only_specific_values.rs index 3445218fbec..73c6cee3e42 100644 --- a/examples/11_only_specific_values.rs +++ b/examples/11_only_specific_values.rs @@ -12,22 +12,25 @@ fn main() { // // For this example, assume you want one positional argument of either "fast" or "slow" // i.e. the only possible ways to run the program are "myprog fast" or "myprog slow" - let matches = App::new("myapp").about("does awesome things") - .arg(Arg::with_name("MODE") - .help("What mode to run the program in") - .index(1) - .possible_values(&["fast", "slow"]) - .required(true)) - .get_matches(); + let matches = App::new("myapp") + .about("does awesome things") + .arg( + Arg::with_name("MODE") + .help("What mode to run the program in") + .index(1) + .possible_values(&["fast", "slow"]) + .required(true), + ) + .get_matches(); // Note, it's safe to call unwrap() because the arg is required match matches.value_of("MODE").unwrap() { "fast" => { // Do fast things... - }, + } "slow" => { // Do slow things... - }, - _ => unreachable!() + } + _ => unreachable!(), } } diff --git a/examples/12_typed_values.rs b/examples/12_typed_values.rs index 3d03e4fd4c5..4bc22ba1b7e 100644 --- a/examples/12_typed_values.rs +++ b/examples/12_typed_values.rs @@ -26,12 +26,13 @@ fn main() { // **NOTE:** to use the macros, you must include #[macro_use] just above the 'extern crate clap;' // declaration in your crate root. let matches = App::new("myapp") - // Create two arguments, a required positional which accepts multiple values - // and an optional '-l value' - .args_from_usage( - "... 'A sequence of whole positive numbers, i.e. 20 25 30' - -l [len] 'A length to use, defaults to 10 when omitted'") - .get_matches(); + // Create two arguments, a required positional which accepts multiple values + // and an optional '-l value' + .args_from_usage( + "... 'A sequence of whole positive numbers, i.e. 20 25 30' + -l [len] 'A length to use, defaults to 10 when omitted'", + ) + .get_matches(); // Here we get a value of type u32 from our optional -l argument. // If the value provided to len fails to parse, we default to 10 diff --git a/examples/13a_enum_values_automatic.rs b/examples/13a_enum_values_automatic.rs index 1abe5cb9abc..73b9cca0d8b 100644 --- a/examples/13a_enum_values_automatic.rs +++ b/examples/13a_enum_values_automatic.rs @@ -18,7 +18,7 @@ use clap::{App, Arg}; // Using arg_enum! is more like traditional enum declarations // // **NOTE:** Only bare variants are supported -arg_enum!{ +arg_enum! { #[derive(Debug)] pub enum Oof { Rab, @@ -27,7 +27,7 @@ arg_enum!{ } } -arg_enum!{ +arg_enum! { #[derive(Debug)] enum Foo { Bar, @@ -40,27 +40,27 @@ fn main() { // Create the application like normal let enum_vals = ["fast", "slow"]; let m = App::new("myapp") - // Use a single positional argument that is required - .arg(Arg::from_usage(" 'The Foo to use'") - .possible_values(&Foo::variants())) - .arg(Arg::from_usage(" 'The speed to use'") - // You can define a list of possible values if you want the values to be - // displayed in the help information. Whether you use possible_values() or - // not, the valid values will ALWAYS be displayed on a failed parse. - .possible_values(&enum_vals)) - // For the second positional, lets not use possible_values() just to show the difference - .arg_from_usage(" 'The Oof to use'") - .get_matches(); + // Use a single positional argument that is required + .arg(Arg::from_usage(" 'The Foo to use'").possible_values(&Foo::variants())) + .arg( + Arg::from_usage(" 'The speed to use'") + // You can define a list of possible values if you want the values to be + // displayed in the help information. Whether you use possible_values() or + // not, the valid values will ALWAYS be displayed on a failed parse. + .possible_values(&enum_vals), + ) + // For the second positional, lets not use possible_values() just to show the difference + .arg_from_usage(" 'The Oof to use'") + .get_matches(); let t = value_t!(m.value_of("foo"), Foo).unwrap_or_else(|e| e.exit()); let t2 = value_t!(m.value_of("oof"), Oof).unwrap_or_else(|e| e.exit()); - // Now we can use our enum like normal. match t { Foo::Bar => println!("Found a Bar"), Foo::Baz => println!("Found a Baz"), - Foo::Qux => println!("Found a Qux") + Foo::Qux => println!("Found a Qux"), } // Since our Oof derives Debug, we can do this: diff --git a/examples/13b_enum_values_manual.rs b/examples/13b_enum_values_manual.rs index 81ffe5ebdcd..d53c681e070 100644 --- a/examples/13b_enum_values_manual.rs +++ b/examples/13b_enum_values_manual.rs @@ -15,7 +15,7 @@ enum Vals { Foo, Bar, Baz, - Qux + Qux, } // Implement the trait @@ -28,7 +28,7 @@ impl FromStr for Vals { "Bar" => Ok(Vals::Bar), "Baz" => Ok(Vals::Baz), "Qux" => Ok(Vals::Qux), - _ => Err("no match") + _ => Err("no match"), } } } @@ -36,11 +36,13 @@ impl FromStr for Vals { fn main() { // Create the application like normal let m = App::new("myapp") - // Use a single positional argument that is required - .arg(Arg::from_usage(" 'The type to use'") - // Define the list of possible values - .possible_values(&["Foo", "Bar", "Baz", "Qux"])) - .get_matches(); + // Use a single positional argument that is required + .arg( + Arg::from_usage(" 'The type to use'") + // Define the list of possible values + .possible_values(&["Foo", "Bar", "Baz", "Qux"]), + ) + .get_matches(); let t = value_t!(m, "type", Vals).unwrap_or_else(|e| e.exit()); @@ -49,6 +51,6 @@ fn main() { Vals::Foo => println!("Found a Foo"), Vals::Bar => println!("Found a Bar"), Vals::Baz => println!("Found a Baz"), - Vals::Qux => println!("Found a Qux") + Vals::Qux => println!("Found a Qux"), } } diff --git a/examples/14_groups.rs b/examples/14_groups.rs index e160464c6c4..86ade6dc118 100644 --- a/examples/14_groups.rs +++ b/examples/14_groups.rs @@ -20,7 +20,6 @@ /// of the three numbers. So you create three flags `--major`, `--minor`, and `--patch`. All of /// these arguments shouldn't be used at one time but you want to specify that *at least one* of /// them is used. For this, you can create a group. - extern crate clap; use clap::{App, Arg, ArgGroup}; @@ -28,28 +27,32 @@ use clap::{App, Arg, ArgGroup}; fn main() { // Create application like normal let matches = App::new("myapp") - // Add the version arguments - .args_from_usage("--set-ver [ver] 'set version manually' + // Add the version arguments + .args_from_usage( + "--set-ver [ver] 'set version manually' --major 'auto inc major' --minor 'auto inc minor' - --patch 'auto inc patch'") - // Create a group, make it required, and add the above arguments - .group(ArgGroup::with_name("vers") - .required(true) - .args(&["ver", "major", "minor", "patch"])) - // Arguments can also be added to a group individually, these two arguments - // are part of the "input" group which is not required - .arg(Arg::from_usage("[INPUT_FILE] 'some regular input'") - .group("input")) - .arg(Arg::from_usage("--spec-in [SPEC_IN] 'some special input argument'") - .group("input")) - // Now let's assume we have a -c [config] argument which requires one of - // (but **not** both) the "input" arguments - .arg(Arg::with_name("config") - .short("c") - .takes_value(true) - .requires("input")) - .get_matches(); + --patch 'auto inc patch'", + ) + // Create a group, make it required, and add the above arguments + .group( + ArgGroup::with_name("vers") + .required(true) + .args(&["ver", "major", "minor", "patch"]), + ) + // Arguments can also be added to a group individually, these two arguments + // are part of the "input" group which is not required + .arg(Arg::from_usage("[INPUT_FILE] 'some regular input'").group("input")) + .arg(Arg::from_usage("--spec-in [SPEC_IN] 'some special input argument'").group("input")) + // Now let's assume we have a -c [config] argument which requires one of + // (but **not** both) the "input" arguments + .arg( + Arg::with_name("config") + .short("c") + .takes_value(true) + .requires("input"), + ) + .get_matches(); // Let's assume the old version 1.2.3 let mut major = 1; @@ -61,14 +64,16 @@ fn main() { format!("{}", ver) } else { // Increment the one requested (in a real program, we'd reset the lower numbers) - let (maj, min, pat) = (matches.is_present("major"), - matches.is_present("minor"), - matches.is_present("patch")); + let (maj, min, pat) = ( + matches.is_present("major"), + matches.is_present("minor"), + matches.is_present("patch"), + ); match (maj, min, pat) { (true, _, _) => major += 1, (_, true, _) => minor += 1, (_, _, true) => patch += 1, - _ => unreachable!(), + _ => unreachable!(), }; format!("{}.{}.{}", major, minor, patch) }; @@ -77,11 +82,13 @@ fn main() { // Check for usage of -c if matches.is_present("config") { - let input = matches.value_of("INPUT_FILE").unwrap_or(matches.value_of("SPEC_IN").unwrap()); - println!("Doing work using input {} and config {}", - input, - matches.value_of("config").unwrap()); + let input = matches + .value_of("INPUT_FILE") + .unwrap_or(matches.value_of("SPEC_IN").unwrap()); + println!( + "Doing work using input {} and config {}", + input, + matches.value_of("config").unwrap() + ); } - - } diff --git a/examples/15_custom_validator.rs b/examples/15_custom_validator.rs index a5c0d42f5ec..d470b168462 100644 --- a/examples/15_custom_validator.rs +++ b/examples/15_custom_validator.rs @@ -8,14 +8,16 @@ fn main() { // displayed to the user. let matches = App::new("myapp") - // Application logic goes here... - .arg(Arg::with_name("input") - .help("the input file to use") - .index(1) - .required(true) - // You can pass in a closure, or a function - .validator(is_png)) - .get_matches(); + // Application logic goes here... + .arg( + Arg::with_name("input") + .help("the input file to use") + .index(1) + .required(true) + // You can pass in a closure, or a function + .validator(is_png), + ) + .get_matches(); // Here we can call .unwrap() because the argument is required. println!("The .PNG file is: {}", matches.value_of("input").unwrap()); diff --git a/examples/16_app_settings.rs b/examples/16_app_settings.rs index ab1d1850b9c..6da311a5dca 100644 --- a/examples/16_app_settings.rs +++ b/examples/16_app_settings.rs @@ -12,20 +12,16 @@ fn main() { // information. let matches = App::new("myapp") - .setting(AppSettings::SubcommandsNegateReqs) - // Negates requirement of parent command. - - .arg_from_usage(" 'input file to use'") - // Required positional argument called input. This - // will be only required if subcommand is not present. - - .subcommand(SubCommand::with_name("test") - .about("does some testing")) - // if program is invoked with subcommand, you do not - // need to specify the argument anymore due to - // the AppSettings::SubcommandsNegateReqs setting. - - .get_matches(); + .setting(AppSettings::SubcommandsNegateReqs) + // Negates requirement of parent command. + .arg_from_usage(" 'input file to use'") + // Required positional argument called input. This + // will be only required if subcommand is not present. + .subcommand(SubCommand::with_name("test").about("does some testing")) + // if program is invoked with subcommand, you do not + // need to specify the argument anymore due to + // the AppSettings::SubcommandsNegateReqs setting. + .get_matches(); // Calling unwrap() on "input" would not be advised here, because although it's required, // if the user uses a subcommand, those requirements are no longer required. Hence, we should @@ -36,6 +32,6 @@ fn main() { match matches.subcommand() { ("test", _) => println!("The 'test' subcommand was used"), - _ => unreachable!() + _ => unreachable!(), } } diff --git a/examples/17_yaml.rs b/examples/17_yaml.rs index 3353d73a92b..c5b3ad756da 100644 --- a/examples/17_yaml.rs +++ b/examples/17_yaml.rs @@ -11,7 +11,6 @@ // [dependencies] // clap = { features = ["yaml"] } - // Using yaml requires calling a clap macro `load_yaml!()` so we must use the '#[macro_use]' // directive #[macro_use] @@ -38,7 +37,7 @@ fn main() { match mode { "vi" => println!("You are using vi"), "emacs" => println!("You are using emacs..."), - _ => unreachable!() + _ => unreachable!(), } } else { println!("--mode wasn't used..."); diff --git a/examples/18_builder_macro.rs b/examples/18_builder_macro.rs index 6bdce47d330..09bd149f350 100644 --- a/examples/18_builder_macro.rs +++ b/examples/18_builder_macro.rs @@ -5,7 +5,6 @@ extern crate clap; // $crate:: internally fn main() { - // Validation example testing that a file exists let file_exists = |path| { if std::fs::metadata(path).is_ok() { diff --git a/examples/19_auto_authors.rs b/examples/19_auto_authors.rs index afbb9853b94..cfb540e8688 100644 --- a/examples/19_auto_authors.rs +++ b/examples/19_auto_authors.rs @@ -6,9 +6,9 @@ use clap::App; fn main() { App::new("myapp") .about("does awesome things") - // use crate_authors! to pull the author(s) names from the Cargo.toml - .author(crate_authors!()) - .get_matches(); + // use crate_authors! to pull the author(s) names from the Cargo.toml + .author(crate_authors!()) + .get_matches(); // running this app with -h will display whatever author(s) are in your // Cargo.toml diff --git a/examples/20_subcommands.rs b/examples/20_subcommands.rs index f80f46d7135..8e5dde289ed 100644 --- a/examples/20_subcommands.rs +++ b/examples/20_subcommands.rs @@ -41,40 +41,50 @@ extern crate clap; -use clap::{App, Arg, SubCommand, AppSettings}; +use clap::{App, AppSettings, Arg, SubCommand}; fn main() { - let matches = App::new("git") .about("A fictional versioning CLI") .version("1.0") .author("Me") - .subcommand(SubCommand::with_name("clone") - .about("clones repos") - .arg(Arg::with_name("repo") - .help("The repo to clone") - .required(true))) - .subcommand(SubCommand::with_name("push") - .about("pushes things") - .setting(AppSettings::SubcommandRequiredElseHelp) - .subcommand(SubCommand::with_name("remote") // Subcommands can have their own subcommands, - // which in turn have their own subcommands - .about("pushes remote things") - .arg(Arg::with_name("repo") - .required(true) - .help("The remote repo to push things to"))) - .subcommand(SubCommand::with_name("local") - .about("pushes local things"))) - .subcommand(SubCommand::with_name("add") - .about("adds things") - .author("Someone Else") // Subcommands can list different authors - .version("v2.0 (I'm versioned differently") // or different version from their parents - .setting(AppSettings::ArgRequiredElseHelp) // They can even have different settings - .arg(Arg::with_name("stuff") - .long("stuff") - .help("Stuff to add") - .takes_value(true) - .multiple(true))) + .subcommand( + SubCommand::with_name("clone").about("clones repos").arg( + Arg::with_name("repo") + .help("The repo to clone") + .required(true), + ), + ) + .subcommand( + SubCommand::with_name("push") + .about("pushes things") + .setting(AppSettings::SubcommandRequiredElseHelp) + .subcommand( + SubCommand::with_name("remote") // Subcommands can have their own subcommands, + // which in turn have their own subcommands + .about("pushes remote things") + .arg( + Arg::with_name("repo") + .required(true) + .help("The remote repo to push things to"), + ), + ) + .subcommand(SubCommand::with_name("local").about("pushes local things")), + ) + .subcommand( + SubCommand::with_name("add") + .about("adds things") + .author("Someone Else") // Subcommands can list different authors + .version("v2.0 (I'm versioned differently") // or different version from their parents + .setting(AppSettings::ArgRequiredElseHelp) // They can even have different settings + .arg( + Arg::with_name("stuff") + .long("stuff") + .help("Stuff to add") + .takes_value(true) + .multiple(true), + ), + ) .get_matches(); // At this point, the matches we have point to git. Keep this in mind... @@ -101,8 +111,8 @@ fn main() { Some("clone") => println!("'git clone' was used"), Some("push") => println!("'git push' was used"), Some("add") => println!("'git add' was used"), - None => println!("No subcommand was used"), - _ => unreachable!(), // Assuming you've listed all direct children above, this is unreachable + None => println!("No subcommand was used"), + _ => unreachable!(), // Assuming you've listed all direct children above, this is unreachable } // You could get the independent subcommand matches, although this is less common @@ -114,29 +124,36 @@ fn main() { // The most common way to handle subcommands is via a combined approach using // `ArgMatches::subcommand` which returns a tuple of both the name and matches match matches.subcommand() { - ("clone", Some(clone_matches)) =>{ + ("clone", Some(clone_matches)) => { // Now we have a reference to clone's matches println!("Cloning {}", clone_matches.value_of("repo").unwrap()); - }, - ("push", Some(push_matches)) =>{ + } + ("push", Some(push_matches)) => { // Now we have a reference to push's matches match push_matches.subcommand() { - ("remote", Some(remote_matches)) =>{ + ("remote", Some(remote_matches)) => { // Now we have a reference to remote's matches println!("Pushing to {}", remote_matches.value_of("repo").unwrap()); - }, - ("local", Some(_)) =>{ + } + ("local", Some(_)) => { println!("'git push local' was used"); - }, - _ => unreachable!(), + } + _ => unreachable!(), } - }, - ("add", Some(add_matches)) =>{ + } + ("add", Some(add_matches)) => { // Now we have a reference to add's matches - println!("Adding {}", add_matches.values_of("stuff").unwrap().collect::>().join(", ")); - }, - ("", None) => println!("No subcommand was used"), // If no subcommand was used it'll match the tuple ("", None) - _ => unreachable!(), // If all subcommands are defined above, anything else is unreachable!() + println!( + "Adding {}", + add_matches + .values_of("stuff") + .unwrap() + .collect::>() + .join(", ") + ); + } + ("", None) => println!("No subcommand was used"), // If no subcommand was used it'll match the tuple ("", None) + _ => unreachable!(), // If all subcommands are defined above, anything else is unreachable!() } // Continued program logic goes here... diff --git a/examples/21_aliases.rs b/examples/21_aliases.rs index 3be04458b50..6bc8ebe16f0 100644 --- a/examples/21_aliases.rs +++ b/examples/21_aliases.rs @@ -3,19 +3,21 @@ extern crate clap; use clap::{App, Arg, SubCommand}; fn main() { - let matches = App::new("MyApp") - .subcommand(SubCommand::with_name("ls") - .aliases(&["list", "dir"]) - .about("Adds files to myapp") - .version("0.1") - .author("Kevin K.") - .arg(Arg::with_name("input") - .help("the file to add") - .index(1) - .required(true)) - ) - .get_matches(); + .subcommand( + SubCommand::with_name("ls") + .aliases(&["list", "dir"]) + .about("Adds files to myapp") + .version("0.1") + .author("Kevin K.") + .arg( + Arg::with_name("input") + .help("the file to add") + .index(1) + .required(true), + ), + ) + .get_matches(); // You can check if a subcommand was used like normal if matches.is_present("add") { @@ -31,8 +33,8 @@ fn main() { // You can also match on a subcommand's name match matches.subcommand_name() { Some("add") => println!("'myapp add' was used"), - None => println!("No subcommand was used"), - _ => println!("Some other subcommand was used"), + None => println!("No subcommand was used"), + _ => println!("Some other subcommand was used"), } // Continued program logic goes here... diff --git a/examples/22_stop_parsing_with_--.rs b/examples/22_stop_parsing_with_--.rs index a5ba5b38ff9..acb86a93584 100644 --- a/examples/22_stop_parsing_with_--.rs +++ b/examples/22_stop_parsing_with_--.rs @@ -4,22 +4,20 @@ use clap::{App, Arg}; /// myprog -f -p=bob -- sloppy slop slop fn main() { - let matches = App::new("myprog") - .arg(Arg::with_name("eff") - .short("f")) - .arg(Arg::with_name("pea") - .short("p") - .takes_value(true)) - .arg(Arg::with_name("slop") - .multiple(true) - .last(true)) + .arg(Arg::with_name("eff").short("f")) + .arg(Arg::with_name("pea").short("p").takes_value(true)) + .arg(Arg::with_name("slop").multiple(true).last(true)) .get_matches(); - println!("-f used: {:?}", matches.is_present("eff")); println!("-p's value: {:?}", matches.value_of("pea")); - println!("'slops' values: {:?}", matches.values_of("slop").map(|vals| vals.collect::>())); + println!( + "'slops' values: {:?}", + matches + .values_of("slop") + .map(|vals| vals.collect::>()) + ); // Continued program logic goes here... } diff --git a/rustfmt.toml b/rustfmt.toml deleted file mode 100644 index 0136d86e313..00000000000 --- a/rustfmt.toml +++ /dev/null @@ -1,4 +0,0 @@ -format_strings = false -chain_overflow_last = false -same_line_if_else = true -fn_single_line = true diff --git a/src/app/help.rs b/src/app/help.rs index 34f97ac322e..4751fe7d86c 100644 --- a/src/app/help.rs +++ b/src/app/help.rs @@ -37,11 +37,7 @@ const TAB: &'static str = " "; // These are just convenient traits to make the code easier to read. trait ArgWithDisplay<'b, 'c>: AnyArg<'b, 'c> + Display {} -impl<'b, 'c, T> ArgWithDisplay<'b, 'c> for T -where - T: AnyArg<'b, 'c> + Display, -{ -} +impl<'b, 'c, T> ArgWithDisplay<'b, 'c> for T where T: AnyArg<'b, 'c> + Display {} trait ArgWithOrder<'b, 'c>: ArgWithDisplay<'b, 'c> + DispOrder { fn as_base(&self) -> &ArgWithDisplay<'b, 'c>; @@ -117,11 +113,13 @@ impl<'a> Help<'a> { next_line_help: next_line_help, hide_pv: hide_pv, term_w: match term_w { - Some(width) => if width == 0 { - usize::MAX - } else { - width - }, + Some(width) => { + if width == 0 { + usize::MAX + } else { + width + } + } None => cmp::min( term_size::dimensions().map_or(120, |(w, _)| w), match max_w { @@ -184,7 +182,8 @@ impl<'a> Help<'a> { parser.meta.term_w, parser.meta.max_w, use_long, - ).write_help(parser) + ) + .write_help(parser) } /// Writes the parser help to the wrapped stream. @@ -369,7 +368,8 @@ impl<'a> Help<'a> { let h_w = str_width(h) + str_width(&*spec_vals); let nlh = self.next_line_help || arg.is_set(ArgSettings::NextLineHelp); let taken = self.longest + 12; - self.force_next_line = !nlh && self.term_w >= taken + self.force_next_line = !nlh + && self.term_w >= taken && (taken as f32 / self.term_w as f32) > 0.40 && h_w > (self.term_w - taken); @@ -458,7 +458,9 @@ impl<'a> Help<'a> { arg.help().unwrap_or_else(|| arg.long_help().unwrap_or("")) }; let mut help = String::from(h) + spec_vals; - let nlh = self.next_line_help || arg.is_set(ArgSettings::NextLineHelp) || (self.use_long && arg.name() != ""); + let nlh = self.next_line_help + || arg.is_set(ArgSettings::NextLineHelp) + || (self.use_long && arg.name() != ""); debugln!("Help::help: Next Line...{:?}", nlh); let spcs = if nlh || self.force_next_line { @@ -596,7 +598,8 @@ impl<'a> Help<'a> { let pos = parser .positionals() .filter(|arg| !arg.is_set(ArgSettings::Hidden)) - .count() > 0; + .count() + > 0; let opts = parser.has_opts(); let subcmds = parser.has_visible_subcommands(); diff --git a/src/app/meta.rs b/src/app/meta.rs index c7f128fe537..8916101015b 100644 --- a/src/app/meta.rs +++ b/src/app/meta.rs @@ -22,7 +22,9 @@ pub struct AppMeta<'b> { } impl<'b> AppMeta<'b> { - pub fn new() -> Self { Default::default() } + pub fn new() -> Self { + Default::default() + } pub fn with_name(s: String) -> Self { AppMeta { name: s, diff --git a/src/app/mod.rs b/src/app/mod.rs index 3a1a3831e39..604b8befebf 100644 --- a/src/app/mod.rs +++ b/src/app/mod.rs @@ -1,9 +1,9 @@ -mod settings; -pub mod parser; -mod meta; mod help; -mod validator; +mod meta; +pub mod parser; +mod settings; mod usage; +mod validator; // Std use std::env; @@ -20,12 +20,12 @@ use std::result::Result as StdResult; use yaml_rust::Yaml; // Internal +pub use self::settings::AppSettings; use app::help::Help; use app::parser::Parser; use args::{AnyArg, Arg, ArgGroup, ArgMatcher, ArgMatches, ArgSettings}; -use errors::Result as ClapResult; -pub use self::settings::AppSettings; use completions::Shell; +use errors::Result as ClapResult; use map::{self, VecMap}; /// Used to create a representation of a command line program and all possible command line @@ -61,10 +61,10 @@ pub struct App<'a, 'b> where 'a: 'b, { - #[doc(hidden)] pub p: Parser<'a, 'b>, + #[doc(hidden)] + pub p: Parser<'a, 'b>, } - impl<'a, 'b> App<'a, 'b> { /// Creates a new instance of an application requiring a name. The name may be, but doesn't /// have to be same as the binary. The name will be displayed to the user when they request to @@ -84,10 +84,14 @@ impl<'a, 'b> App<'a, 'b> { } /// Get the name of the app - pub fn get_name(&self) -> &str { &self.p.meta.name } + pub fn get_name(&self) -> &str { + &self.p.meta.name + } /// Get the name of the binary - pub fn get_bin_name(&self) -> Option<&str> { self.p.meta.bin_name.as_ref().map(|s| s.as_str()) } + pub fn get_bin_name(&self) -> Option<&str> { + self.p.meta.bin_name.as_ref().map(|s| s.as_str()) + } /// Creates a new instance of an application requiring a name, but uses the [`crate_authors!`] /// and [`crate_version!`] macros to fill in the [`App::author`] and [`App::version`] fields. @@ -103,7 +107,10 @@ impl<'a, 'b> App<'a, 'b> { /// [`crate_version!`]: ./macro.crate_version!.html /// [`App::author`]: ./struct.App.html#method.author /// [`App::version`]: ./struct.App.html#method.author - #[deprecated(since="2.14.1", note="Can never work; use explicit App::author() and App::version() calls instead")] + #[deprecated( + since = "2.14.1", + note = "Can never work; use explicit App::author() and App::version() calls instead" + )] pub fn with_defaults>(n: S) -> Self { let mut a = App { p: Parser::with_name(n.into()), @@ -153,7 +160,9 @@ impl<'a, 'b> App<'a, 'b> { /// [`examples/17_yaml.yml`]: https://github.com/clap-rs/clap/blob/master/examples/17_yaml.yml /// [`panic!`]: https://doc.rust-lang.org/std/macro.panic!.html #[cfg(feature = "yaml")] - pub fn from_yaml(yaml: &'a Yaml) -> App<'a, 'a> { App::from(yaml) } + pub fn from_yaml(yaml: &'a Yaml) -> App<'a, 'a> { + App::from(yaml) + } /// Sets a string of author(s) that will be displayed to the user when they /// request the help information with `--help` or `-h`. @@ -1391,7 +1400,6 @@ impl<'a, 'b> App<'a, 'b> { self.p.gen_completions(for_shell, out_dir.into()); } - /// Generate a completions file for a specified shell at runtime. Until `cargo install` can /// install extra files like a completion script, this may be used e.g. in a command that /// outputs the contents of the completion script, to be redirected into a file by the user. @@ -1448,7 +1456,9 @@ impl<'a, 'b> App<'a, 'b> { /// .get_matches(); /// ``` /// [`env::args_os`]: https://doc.rust-lang.org/std/env/fn.args_os.html - pub fn get_matches(self) -> ArgMatches<'a> { self.get_matches_from(&mut env::args_os()) } + pub fn get_matches(self) -> ArgMatches<'a> { + self.get_matches_from(&mut env::args_os()) + } /// Starts the parsing process. This method will return a [`clap::Result`] type instead of exiting /// the process on failed parse. By default this method gets matches from [`env::args_os`] @@ -1658,7 +1668,10 @@ impl<'a> From<&'a Yaml> for App<'a, 'a> { if let Some(v) = $y[stringify!($i)].as_str() { $a = $a.$i(v); } else if $y[stringify!($i)] != Yaml::BadValue { - panic!("Failed to convert YAML value {:?} to a string", $y[stringify!($i)]); + panic!( + "Failed to convert YAML value {:?} to a string", + $y[stringify!($i)] + ); } }; } @@ -1736,25 +1749,27 @@ impl<'a> From<&'a Yaml> for App<'a, 'a> { macro_rules! vec_or_str { ($a:ident, $y:ident, $as_vec:ident, $as_single:ident) => {{ - let maybe_vec = $y[stringify!($as_vec)].as_vec(); - if let Some(vec) = maybe_vec { - for ys in vec { - if let Some(s) = ys.as_str() { - $a = $a.$as_single(s); - } else { - panic!("Failed to convert YAML value {:?} to a string", ys); - } - } - } else { - if let Some(s) = $y[stringify!($as_vec)].as_str() { + let maybe_vec = $y[stringify!($as_vec)].as_vec(); + if let Some(vec) = maybe_vec { + for ys in vec { + if let Some(s) = ys.as_str() { $a = $a.$as_single(s); - } else if $y[stringify!($as_vec)] != Yaml::BadValue { - panic!("Failed to convert YAML value {:?} to either a vec or string", $y[stringify!($as_vec)]); + } else { + panic!("Failed to convert YAML value {:?} to a string", ys); } } - $a + } else { + if let Some(s) = $y[stringify!($as_vec)].as_str() { + $a = $a.$as_single(s); + } else if $y[stringify!($as_vec)] != Yaml::BadValue { + panic!( + "Failed to convert YAML value {:?} to either a vec or string", + $y[stringify!($as_vec)] + ); + } } - }; + $a + }}; } a = vec_or_str!(a, yaml, aliases, alias); @@ -1781,42 +1796,90 @@ impl<'a> From<&'a Yaml> for App<'a, 'a> { } impl<'a, 'b> Clone for App<'a, 'b> { - fn clone(&self) -> Self { App { p: self.p.clone() } } + fn clone(&self) -> Self { + App { p: self.p.clone() } + } } impl<'n, 'e> AnyArg<'n, 'e> for App<'n, 'e> { fn name(&self) -> &'n str { "" } - fn overrides(&self) -> Option<&[&'e str]> { None } - fn requires(&self) -> Option<&[(Option<&'e str>, &'n str)]> { None } - fn blacklist(&self) -> Option<&[&'e str]> { None } - fn required_unless(&self) -> Option<&[&'e str]> { None } - fn val_names(&self) -> Option<&VecMap<&'e str>> { None } - fn is_set(&self, _: ArgSettings) -> bool { false } - fn val_terminator(&self) -> Option<&'e str> { None } + fn overrides(&self) -> Option<&[&'e str]> { + None + } + fn requires(&self) -> Option<&[(Option<&'e str>, &'n str)]> { + None + } + fn blacklist(&self) -> Option<&[&'e str]> { + None + } + fn required_unless(&self) -> Option<&[&'e str]> { + None + } + fn val_names(&self) -> Option<&VecMap<&'e str>> { + None + } + fn is_set(&self, _: ArgSettings) -> bool { + false + } + fn val_terminator(&self) -> Option<&'e str> { + None + } fn set(&mut self, _: ArgSettings) { unreachable!("App struct does not support AnyArg::set, this is a bug!") } - fn has_switch(&self) -> bool { false } - fn max_vals(&self) -> Option { None } - fn num_vals(&self) -> Option { None } - fn possible_vals(&self) -> Option<&[&'e str]> { None } - fn validator(&self) -> Option<&Rc StdResult<(), String>>> { None } - fn validator_os(&self) -> Option<&Rc StdResult<(), OsString>>> { None } - fn min_vals(&self) -> Option { None } - fn short(&self) -> Option { None } - fn long(&self) -> Option<&'e str> { None } - fn val_delim(&self) -> Option { None } - fn takes_value(&self) -> bool { true } - fn help(&self) -> Option<&'e str> { self.p.meta.about } - fn long_help(&self) -> Option<&'e str> { self.p.meta.long_about } - fn default_val(&self) -> Option<&'e OsStr> { None } + fn has_switch(&self) -> bool { + false + } + fn max_vals(&self) -> Option { + None + } + fn num_vals(&self) -> Option { + None + } + fn possible_vals(&self) -> Option<&[&'e str]> { + None + } + fn validator(&self) -> Option<&Rc StdResult<(), String>>> { + None + } + fn validator_os(&self) -> Option<&Rc StdResult<(), OsString>>> { + None + } + fn min_vals(&self) -> Option { + None + } + fn short(&self) -> Option { + None + } + fn long(&self) -> Option<&'e str> { + None + } + fn val_delim(&self) -> Option { + None + } + fn takes_value(&self) -> bool { + true + } + fn help(&self) -> Option<&'e str> { + self.p.meta.about + } + fn long_help(&self) -> Option<&'e str> { + self.p.meta.long_about + } + fn default_val(&self) -> Option<&'e OsStr> { + None + } fn default_vals_ifs(&self) -> Option, &'e OsStr)>> { None } - fn env<'s>(&'s self) -> Option<(&'n OsStr, Option<&'s OsString>)> { None } - fn longest_filter(&self) -> bool { true } + fn env<'s>(&'s self) -> Option<(&'n OsStr, Option<&'s OsString>)> { + None + } + fn longest_filter(&self) -> bool { + true + } fn aliases(&self) -> Option> { if let Some(ref aliases) = self.p.meta.aliases { let vis_aliases: Vec<_> = aliases @@ -1835,5 +1898,7 @@ impl<'n, 'e> AnyArg<'n, 'e> for App<'n, 'e> { } impl<'n, 'e> fmt::Display for App<'n, 'e> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.p.meta.name) } + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}", self.p.meta.name) + } } diff --git a/src/app/parser.rs b/src/app/parser.rs index decfde4f8d2..c05602e83d2 100644 --- a/src/app/parser.rs +++ b/src/app/parser.rs @@ -1,38 +1,43 @@ // Std +#[cfg(all(feature = "debug", any(target_os = "windows", target_arch = "wasm32")))] +use osstringext::OsStrExt3; +use std::cell::Cell; use std::ffi::{OsStr, OsString}; use std::fmt::Display; use std::fs::File; use std::io::{self, BufWriter, Write}; -#[cfg(all(feature = "debug", not(any(target_os = "windows", target_arch = "wasm32"))))] +use std::iter::Peekable; +#[cfg(all( + feature = "debug", + not(any(target_os = "windows", target_arch = "wasm32")) +))] use std::os::unix::ffi::OsStrExt; -#[cfg(all(feature = "debug", any(target_os = "windows", target_arch = "wasm32")))] -use osstringext::OsStrExt3; use std::path::PathBuf; use std::slice::Iter; -use std::iter::Peekable; -use std::cell::Cell; // Internal -use INTERNAL_ERROR_MSG; -use INVALID_UTF8; -use SubCommand; -use app::App; use app::help::Help; use app::meta::AppMeta; use app::settings::AppFlags; -use args::{AnyArg, Arg, ArgGroup, ArgMatcher, Base, FlagBuilder, OptBuilder, PosBuilder, Switched}; +use app::settings::AppSettings as AS; +use app::usage; +use app::validator::Validator; +use app::App; use args::settings::ArgSettings; +use args::{ + AnyArg, Arg, ArgGroup, ArgMatcher, Base, FlagBuilder, OptBuilder, PosBuilder, Switched, +}; use completions::ComplGen; -use errors::{Error, ErrorKind}; +use completions::Shell; use errors::Result as ClapResult; +use errors::{Error, ErrorKind}; use fmt::ColorWhen; +use map::{self, VecMap}; use osstringext::OsStrExt2; -use completions::Shell; use suggestions; -use app::settings::AppSettings as AS; -use app::validator::Validator; -use app::usage; -use map::{self, VecMap}; +use SubCommand; +use INTERNAL_ERROR_MSG; +use INVALID_UTF8; #[derive(Debug, PartialEq, Copy, Clone)] #[doc(hidden)] @@ -87,7 +92,8 @@ where } pub fn help_short(&mut self, s: &str) { - let c = s.trim_left_matches(|c| c == '-') + let c = s + .trim_left_matches(|c| c == '-') .chars() .nth(0) .unwrap_or('h'); @@ -95,7 +101,8 @@ where } pub fn version_short(&mut self, s: &str) { - let c = s.trim_left_matches(|c| c == '-') + let c = s + .trim_left_matches(|c| c == '-') .chars() .nth(0) .unwrap_or('V'); @@ -209,7 +216,8 @@ where ); if a.b.is_set(ArgSettings::Last) { assert!( - !self.positionals + !self + .positionals .values() .any(|p| p.b.is_set(ArgSettings::Last)), "Only one positional argument may have last(true) set. Found two." @@ -354,7 +362,8 @@ where // } } if self.groups.iter().any(|g| g.name == group.name) { - let grp = self.groups + let grp = self + .groups .iter_mut() .find(|g| g.name == group.name) .expect(INTERNAL_ERROR_MSG); @@ -420,21 +429,24 @@ where pub fn derive_display_order(&mut self) { if self.is_set(AS::DeriveDisplayOrder) { let unified = self.is_set(AS::UnifiedHelpMessage); - for (i, o) in self.opts + for (i, o) in self + .opts .iter_mut() .enumerate() .filter(|&(_, ref o)| o.s.disp_ord == 999) { o.s.disp_ord = if unified { o.s.unified_ord } else { i }; } - for (i, f) in self.flags + for (i, f) in self + .flags .iter_mut() .enumerate() .filter(|&(_, ref f)| f.s.disp_ord == 999) { f.s.disp_ord = if unified { f.s.unified_ord } else { i }; } - for (i, sc) in &mut self.subcommands + for (i, sc) in &mut self + .subcommands .iter_mut() .enumerate() .filter(|&(_, ref sc)| sc.p.meta.disp_ord == 999) @@ -447,7 +459,9 @@ where } } - pub fn required(&self) -> Iter<&str> { self.required.iter() } + pub fn required(&self) -> Iter<&str> { + self.required.iter() + } #[cfg_attr(feature = "lints", allow(needless_borrow))] #[inline] @@ -456,16 +470,24 @@ where } #[inline] - pub fn has_opts(&self) -> bool { !self.opts.is_empty() } + pub fn has_opts(&self) -> bool { + !self.opts.is_empty() + } #[inline] - pub fn has_flags(&self) -> bool { !self.flags.is_empty() } + pub fn has_flags(&self) -> bool { + !self.flags.is_empty() + } #[inline] - pub fn has_positionals(&self) -> bool { !self.positionals.is_empty() } + pub fn has_positionals(&self) -> bool { + !self.positionals.is_empty() + } #[inline] - pub fn has_subcommands(&self) -> bool { !self.subcommands.is_empty() } + pub fn has_subcommands(&self) -> bool { + !self.subcommands.is_empty() + } #[inline] pub fn has_visible_opts(&self) -> bool { @@ -496,20 +518,27 @@ where #[inline] pub fn has_visible_subcommands(&self) -> bool { self.has_subcommands() - && self.subcommands + && self + .subcommands .iter() .filter(|sc| sc.p.meta.name != "help") .any(|sc| !sc.p.is_set(AS::Hidden)) } #[inline] - pub fn is_set(&self, s: AS) -> bool { self.settings.is_set(s) } + pub fn is_set(&self, s: AS) -> bool { + self.settings.is_set(s) + } #[inline] - pub fn set(&mut self, s: AS) { self.settings.set(s) } + pub fn set(&mut self, s: AS) { + self.settings.set(s) + } #[inline] - pub fn unset(&mut self, s: AS) { self.settings.unset(s) } + pub fn unset(&mut self, s: AS) { + self.settings.unset(s) + } #[cfg_attr(feature = "lints", allow(block_in_if_condition_stmt))] pub fn verify_positionals(&self) -> bool { @@ -556,12 +585,14 @@ where argument may be set to .multiple(true)" ); - let count = self.positionals + let count = self + .positionals .values() .filter(|p| p.b.settings.is_set(ArgSettings::Multiple) && p.v.num_vals.is_none()) .count(); let ok = count <= 1 - || (last.is_set(ArgSettings::Last) && last.is_set(ArgSettings::Multiple) + || (last.is_set(ArgSettings::Last) + && last.is_set(ArgSettings::Multiple) && second_to_last.is_set(ArgSettings::Multiple) && count == 2); assert!( @@ -628,10 +659,12 @@ where } } } - if self.positionals + if self + .positionals .values() .any(|p| p.b.is_set(ArgSettings::Last) && p.b.is_set(ArgSettings::Required)) - && self.has_subcommands() && !self.is_set(AS::SubcommandsNegateReqs) + && self.has_subcommands() + && !self.is_set(AS::SubcommandsNegateReqs) { panic!( "Having a required positional argument with .last(true) set *and* child \ @@ -657,10 +690,10 @@ where // Checks if the arg matches a subcommand name, or any of it's aliases (if defined) fn possible_subcommand(&self, arg_os: &OsStr) -> (bool, Option<&str>) { - #[cfg(not(any(target_os = "windows", target_arch = "wasm32")))] - use std::os::unix::ffi::OsStrExt; #[cfg(any(target_os = "windows", target_arch = "wasm32"))] use osstringext::OsStrExt3; + #[cfg(not(any(target_os = "windows", target_arch = "wasm32")))] + use std::os::unix::ffi::OsStrExt; debugln!("Parser::possible_subcommand: arg={:?}", arg_os); fn starts(h: &str, n: &OsStr) -> bool { let n_bytes = n.as_bytes(); @@ -677,7 +710,8 @@ where return (true, Some(&sc.p.meta.name)); } } else { - let v = self.subcommands + let v = self + .subcommands .iter() .filter(|s| { starts(&s.p.meta.name[..], &*arg_os) @@ -689,7 +723,8 @@ where .unwrap() .iter() .filter(|&&(a, _)| starts(a, &*arg_os)) - .count() == 1) + .count() + == 1) }) .map(|sc| &sc.p.meta.name) .collect::>(); @@ -715,7 +750,8 @@ where debugln!("Parser::parse_help_subcommand;"); let cmds: Vec = it.map(|c| c.into()).collect(); let mut help_help = false; - let mut bin_name = self.meta + let mut bin_name = self + .meta .bin_name .as_ref() .unwrap_or(&self.meta.name) @@ -727,7 +763,8 @@ where // cmd help help help_help = true; } - if let Some(c) = sc.subcommands + if let Some(c) = sc + .subcommands .iter() .find(|s| &*s.p.meta.name == cmd) .map(|sc| &sc.p) @@ -736,7 +773,8 @@ where if i == cmds.len() - 1 { break; } - } else if let Some(c) = sc.subcommands + } else if let Some(c) = sc + .subcommands .iter() .find(|s| { if let Some(ref als) = s.p.meta.aliases { @@ -796,14 +834,16 @@ where }; let arg_allows_tac = match needs_val_of { ParseResult::Opt(name) => { - let o = self.opts + let o = self + .opts .iter() .find(|o| o.b.name == name) .expect(INTERNAL_ERROR_MSG); (o.is_set(ArgSettings::AllowLeadingHyphen) || app_wide_settings) } ParseResult::Pos(name) => { - let p = self.positionals + let p = self + .positionals .values() .find(|p| p.b.name == name) .expect(INTERNAL_ERROR_MSG); @@ -854,11 +894,11 @@ where debug_assert!(self.app_debug_asserts()); if self.positionals.values().any(|a| { a.b.is_set(ArgSettings::Multiple) && (a.index as usize != self.positionals.len()) - }) - && self.positionals - .values() - .last() - .map_or(false, |p| !p.is_set(ArgSettings::Last)) + }) && self + .positionals + .values() + .last() + .map_or(false, |p| !p.is_set(ArgSettings::Last)) { self.settings.set(AS::LowIndexMultiplePositional); } @@ -883,7 +923,9 @@ where self.unset(AS::ValidNegNumFound); // Is this a new argument, or values from a previous option? let starts_new_arg = self.is_new_arg(&arg_os, needs_val_of); - if !self.is_set(AS::TrailingValues) && arg_os.starts_with(b"--") && arg_os.len() == 2 + if !self.is_set(AS::TrailingValues) + && arg_os.starts_with(b"--") + && arg_os.len() == 2 && starts_new_arg { debugln!("Parser::get_matches_with: setting TrailingVals=true"); @@ -972,7 +1014,8 @@ where } else { if let ParseResult::Opt(name) = needs_val_of { // Check to see if parsing a value from a previous arg - let arg = self.opts + let arg = self + .opts .iter() .find(|o| o.b.name == name) .expect(INTERNAL_ERROR_MSG); @@ -985,7 +1028,8 @@ where } if !(self.is_set(AS::ArgsNegateSubcommands) && self.is_set(AS::ValidArgFound)) - && !self.is_set(AS::InferSubcommands) && !self.is_set(AS::AllowExternalSubcommands) + && !self.is_set(AS::InferSubcommands) + && !self.is_set(AS::AllowExternalSubcommands) { if let Some(cdate) = suggestions::did_you_mean(&*arg_os.to_string_lossy(), sc_names!(self)) @@ -1026,7 +1070,8 @@ where ParseResult::ValuesDone }; let sc_match = { self.possible_subcommand(&n).0 }; - if self.is_new_arg(&n, needs_val_of) || sc_match + if self.is_new_arg(&n, needs_val_of) + || sc_match || suggestions::did_you_mean(&n.to_string_lossy(), sc_names!(self)) .is_some() { @@ -1075,7 +1120,8 @@ where let _ = self.add_val_to_arg(p, &arg_os, matcher)?; matcher.inc_occurrence_of(p.b.name); - let _ = self.groups_for_arg(p.b.name) + let _ = self + .groups_for_arg(p.b.name) .and_then(|vec| Some(matcher.inc_occurrences_of(&*vec))); self.settings.set(AS::ValidArgFound); @@ -1300,7 +1346,8 @@ where } } mid_string.push_str(" "); - if let Some(ref mut sc) = self.subcommands + if let Some(ref mut sc) = self + .subcommands .iter_mut() .find(|s| s.p.meta.name == sc_name) { @@ -1371,7 +1418,8 @@ where let mut g_vec = vec![]; let mut args = vec![]; - for n in &self.groups + for n in &self + .groups .iter() .find(|g| g.name == group) .expect(INTERNAL_ERROR_MSG) @@ -1399,7 +1447,8 @@ where let mut g_vec = vec![]; let mut args = vec![]; - for n in &self.groups + for n in &self + .groups .iter() .find(|g| g.name == group) .expect(INTERNAL_ERROR_MSG) @@ -1458,7 +1507,8 @@ where }; self.flags.push(arg); } - if !self.subcommands.is_empty() && !self.is_set(AS::DisableHelpSubcommand) + if !self.subcommands.is_empty() + && !self.is_set(AS::DisableHelpSubcommand) && self.is_set(AS::NeedsSubcommandHelp) { debugln!("Parser::create_help_and_version: Building help"); @@ -1513,25 +1563,26 @@ where } fn use_long_help(&self) -> bool { - // In this case, both must be checked. This allows the retention of + // In this case, both must be checked. This allows the retention of // original formatting, but also ensures that the actual -h or --help // specified by the user is sent through. If HiddenShortHelp is not included, // then items specified with hidden_short_help will also be hidden. - let should_long = |v: &Base| { - v.long_help.is_some() || - v.is_set(ArgSettings::HiddenLongHelp) || - v.is_set(ArgSettings::HiddenShortHelp) + let should_long = |v: &Base| { + v.long_help.is_some() + || v.is_set(ArgSettings::HiddenLongHelp) + || v.is_set(ArgSettings::HiddenShortHelp) }; - self.meta.long_about.is_some() + self.meta.long_about.is_some() || self.flags.iter().any(|f| should_long(&f.b)) || self.opts.iter().any(|o| should_long(&o.b)) || self.positionals.values().any(|p| should_long(&p.b)) - || self.subcommands + || self + .subcommands .iter() .any(|s| s.p.meta.long_about.is_some()) } - + fn _help(&self, mut use_long: bool) -> Error { debugln!("Parser::_help: use_long={:?}", use_long); use_long = use_long && self.use_long_help(); @@ -1627,12 +1678,12 @@ where debugln!("Parser::parse_long_arg: Didn't match anything"); let args_rest: Vec<_> = it.map(|x| x.clone().into()).collect(); - let args_rest2: Vec<_> = args_rest.iter().map(|x| x.to_str().expect(INVALID_UTF8)).collect(); - self.did_you_mean_error( - arg.to_str().expect(INVALID_UTF8), - matcher, - &args_rest2[..] - ).map(|_| ParseResult::NotFound) + let args_rest2: Vec<_> = args_rest + .iter() + .map(|x| x.to_str().expect(INVALID_UTF8)) + .collect(); + self.did_you_mean_error(arg.to_str().expect(INVALID_UTF8), matcher, &args_rest2[..]) + .map(|_| ParseResult::NotFound) } #[cfg_attr(feature = "lints", allow(len_zero))] @@ -1889,9 +1940,15 @@ where Ok(ParseResult::Flag) } - fn did_you_mean_error(&self, arg: &str, matcher: &mut ArgMatcher<'a>, args_rest: &[&str]) -> ClapResult<()> { + fn did_you_mean_error( + &self, + arg: &str, + matcher: &mut ArgMatcher<'a>, + args_rest: &[&str], + ) -> ClapResult<()> { // Didn't match a flag or option - let suffix = suggestions::did_you_mean_flag_suffix(arg, &args_rest, longs!(self), &self.subcommands); + let suffix = + suggestions::did_you_mean_flag_suffix(arg, &args_rest, longs!(self), &self.subcommands); // Add the arg to the matches to build a proper usage string if let Some(name) = suffix.1 { @@ -2040,7 +2097,12 @@ where macro_rules! add_val { ($_self:ident, $a:ident, $m:ident) => { if let Some(ref val) = $a.v.env { - if $m.get($a.b.name).map(|ma| ma.vals.len()).map(|len| len == 0).unwrap_or(false) { + if $m + .get($a.b.name) + .map(|ma| ma.vals.len()) + .map(|len| len == 0) + .unwrap_or(false) + { if let Some(ref val) = val.1 { $_self.add_val_to_arg($a, OsStr::new(val), $m)?; @@ -2070,13 +2132,21 @@ where Ok(()) } - pub fn flags(&self) -> Iter> { self.flags.iter() } + pub fn flags(&self) -> Iter> { + self.flags.iter() + } - pub fn opts(&self) -> Iter> { self.opts.iter() } + pub fn opts(&self) -> Iter> { + self.opts.iter() + } - pub fn positionals(&self) -> map::Values> { self.positionals.values() } + pub fn positionals(&self) -> map::Values> { + self.positionals.values() + } - pub fn subcommands(&self) -> Iter { self.subcommands.iter() } + pub fn subcommands(&self) -> Iter { + self.subcommands.iter() + } // Should we color the output? None=determined by output location, true=yes, false=no #[doc(hidden)] @@ -2160,8 +2230,12 @@ where } #[inline] - fn contains_long(&self, l: &str) -> bool { longs!(self).any(|al| al == &l) } + fn contains_long(&self, l: &str) -> bool { + longs!(self).any(|al| al == &l) + } #[inline] - fn contains_short(&self, s: char) -> bool { shorts!(self).any(|arg_s| arg_s == &s) } + fn contains_short(&self, s: char) -> bool { + shorts!(self).any(|arg_s| arg_s == &s) + } } diff --git a/src/app/settings.rs b/src/app/settings.rs index ec0399722bd..e387d9e9013 100644 --- a/src/app/settings.rs +++ b/src/app/settings.rs @@ -1,8 +1,8 @@ // Std #[allow(deprecated, unused_imports)] use std::ascii::AsciiExt; -use std::str::FromStr; use std::ops::BitOr; +use std::str::FromStr; bitflags! { struct Flags: u64 { @@ -57,22 +57,31 @@ pub struct AppFlags(Flags); impl BitOr for AppFlags { type Output = Self; - fn bitor(self, rhs: Self) -> Self { AppFlags(self.0 | rhs.0) } + fn bitor(self, rhs: Self) -> Self { + AppFlags(self.0 | rhs.0) + } } impl Default for AppFlags { fn default() -> Self { AppFlags( - Flags::NEEDS_LONG_VERSION | Flags::NEEDS_LONG_HELP | Flags::NEEDS_SC_HELP - | Flags::UTF8_NONE | Flags::COLOR_AUTO, + Flags::NEEDS_LONG_VERSION + | Flags::NEEDS_LONG_HELP + | Flags::NEEDS_SC_HELP + | Flags::UTF8_NONE + | Flags::COLOR_AUTO, ) } } #[allow(deprecated)] impl AppFlags { - pub fn new() -> Self { AppFlags::default() } - pub fn zeroed() -> Self { AppFlags(Flags::empty()) } + pub fn new() -> Self { + AppFlags::default() + } + pub fn zeroed() -> Self { + AppFlags(Flags::empty()) + } impl_settings! { AppSettings, ArgRequiredElseHelp => Flags::A_REQUIRED_ELSE_HELP, @@ -960,23 +969,32 @@ pub enum AppSettings { /// [`SubCommand`]: ./struct.SubCommand.html WaitOnError, - #[doc(hidden)] NeedsLongVersion, + #[doc(hidden)] + NeedsLongVersion, - #[doc(hidden)] NeedsLongHelp, + #[doc(hidden)] + NeedsLongHelp, - #[doc(hidden)] NeedsSubcommandHelp, + #[doc(hidden)] + NeedsSubcommandHelp, - #[doc(hidden)] LowIndexMultiplePositional, + #[doc(hidden)] + LowIndexMultiplePositional, - #[doc(hidden)] TrailingValues, + #[doc(hidden)] + TrailingValues, - #[doc(hidden)] ValidNegNumFound, + #[doc(hidden)] + ValidNegNumFound, - #[doc(hidden)] Propagated, + #[doc(hidden)] + Propagated, - #[doc(hidden)] ValidArgFound, + #[doc(hidden)] + ValidArgFound, - #[doc(hidden)] ContainsLast, + #[doc(hidden)] + ContainsLast, } impl FromStr for AppSettings { diff --git a/src/app/usage.rs b/src/app/usage.rs index 609058843c8..e8105c6e712 100644 --- a/src/app/usage.rs +++ b/src/app/usage.rs @@ -2,11 +2,11 @@ use std::collections::{BTreeMap, VecDeque}; // Internal -use INTERNAL_ERROR_MSG; -use args::{AnyArg, ArgMatcher, PosBuilder}; -use args::settings::ArgSettings; -use app::settings::AppSettings as AS; use app::parser::Parser; +use app::settings::AppSettings as AS; +use args::settings::ArgSettings; +use args::{AnyArg, ArgMatcher, PosBuilder}; +use INTERNAL_ERROR_MSG; // Creates a usage string for display. This happens just after all arguments were parsed, but before // any subcommands have been parsed (so as to give subcommands their own usage recursively) @@ -59,7 +59,8 @@ pub fn create_usage_no_title(p: &Parser, used: &[&str]) -> String { // Creates a usage string for display in help messages (i.e. not for errors) pub fn create_help_usage(p: &Parser, incl_reqs: bool) -> String { let mut usage = String::with_capacity(75); - let name = p.meta + let name = p + .meta .usage .as_ref() .unwrap_or_else(|| p.meta.bin_name.as_ref().unwrap_or(&p.meta.name)); @@ -81,9 +82,11 @@ pub fn create_help_usage(p: &Parser, incl_reqs: bool) -> String { } else if flags { usage.push_str(" [OPTIONS]"); } - if !p.is_set(AS::UnifiedHelpMessage) && p.opts.iter().any(|o| { - !o.is_set(ArgSettings::Required) && !o.is_set(ArgSettings::Hidden) - }) { + if !p.is_set(AS::UnifiedHelpMessage) + && p.opts + .iter() + .any(|o| !o.is_set(ArgSettings::Required) && !o.is_set(ArgSettings::Hidden)) + { usage.push_str(" [OPTIONS]"); } @@ -112,7 +115,8 @@ pub fn create_help_usage(p: &Parser, incl_reqs: bool) -> String { usage.push_str(" [ARGS]"); } if has_last && incl_reqs { - let pos = p.positionals + let pos = p + .positionals .values() .find(|p| p.b.is_set(ArgSettings::Last)) .expect(INTERNAL_ERROR_MSG); @@ -191,7 +195,8 @@ fn create_smart_usage(p: &Parser, used: &[&str]) -> String { fn get_args_tag(p: &Parser, incl_reqs: bool) -> Option { debugln!("usage::get_args_tag;"); let mut count = 0; - 'outer: for pos in p.positionals + 'outer: for pos in p + .positionals .values() .filter(|pos| !pos.is_set(ArgSettings::Required)) .filter(|pos| !pos.is_set(ArgSettings::Hidden)) @@ -217,10 +222,12 @@ fn get_args_tag(p: &Parser, incl_reqs: bool) -> Option { debugln!("usage::get_args_tag:iter: More than one, returning [ARGS]"); return None; // [ARGS] } else if count == 1 && incl_reqs { - let pos = p.positionals + let pos = p + .positionals .values() .find(|pos| { - !pos.is_set(ArgSettings::Required) && !pos.is_set(ArgSettings::Hidden) + !pos.is_set(ArgSettings::Required) + && !pos.is_set(ArgSettings::Hidden) && !pos.is_set(ArgSettings::Last) }) .expect(INTERNAL_ERROR_MSG); @@ -241,15 +248,14 @@ fn get_args_tag(p: &Parser, incl_reqs: bool) -> Option { .filter(|pos| !pos.is_set(ArgSettings::Required)) .filter(|pos| !pos.is_set(ArgSettings::Hidden)) .filter(|pos| !pos.is_set(ArgSettings::Last)) - .map(|pos| { - format!(" [{}]{}", pos.name_no_brackets(), pos.multiple_str()) - }) + .map(|pos| format!(" [{}]{}", pos.name_no_brackets(), pos.multiple_str())) .collect::>() .join(""), ); } else if !incl_reqs { debugln!("usage::get_args_tag:iter: incl_reqs=false, building secondary usage string"); - let highest_req_pos = p.positionals + let highest_req_pos = p + .positionals .iter() .filter_map(|(idx, pos)| { if pos.b.is_set(ArgSettings::Required) && !pos.b.is_set(ArgSettings::Last) { @@ -273,9 +279,7 @@ fn get_args_tag(p: &Parser, incl_reqs: bool) -> Option { .filter(|pos| !pos.is_set(ArgSettings::Required)) .filter(|pos| !pos.is_set(ArgSettings::Hidden)) .filter(|pos| !pos.is_set(ArgSettings::Last)) - .map(|pos| { - format!(" [{}]{}", pos.name_no_brackets(), pos.multiple_str()) - }) + .map(|pos| format!(" [{}]{}", pos.name_no_brackets(), pos.multiple_str())) .collect::>() .join(""), ); @@ -332,28 +336,40 @@ pub fn get_required_usage_from<'a, 'b>( let mut new_reqs: Vec<&str> = vec![]; macro_rules! get_requires { (@group $a: ident, $v:ident, $p:ident) => {{ - if let Some(rl) = p.groups.iter() - .filter(|g| g.requires.is_some()) - .find(|g| &g.name == $a) - .map(|g| g.requires.as_ref().unwrap()) { + if let Some(rl) = p + .groups + .iter() + .filter(|g| g.requires.is_some()) + .find(|g| &g.name == $a) + .map(|g| g.requires.as_ref().unwrap()) + { for r in rl { if !$p.contains(&r) { - debugln!("usage::get_required_usage_from:iter:{}: adding group req={:?}", - $a, r); + debugln!( + "usage::get_required_usage_from:iter:{}: adding group req={:?}", + $a, + r + ); $v.push(r); } } } }}; ($a:ident, $what:ident, $how:ident, $v:ident, $p:ident) => {{ - if let Some(rl) = p.$what.$how() - .filter(|a| a.b.requires.is_some()) - .find(|arg| &arg.b.name == $a) - .map(|a| a.b.requires.as_ref().unwrap()) { + if let Some(rl) = p + .$what + .$how() + .filter(|a| a.b.requires.is_some()) + .find(|arg| &arg.b.name == $a) + .map(|a| a.b.requires.as_ref().unwrap()) + { for &(_, r) in rl.iter() { if !$p.contains(&r) { - debugln!("usage::get_required_usage_from:iter:{}: adding arg req={:?}", - $a, r); + debugln!( + "usage::get_required_usage_from:iter:{}: adding arg req={:?}", + $a, + r + ); $v.push(r); } } @@ -406,7 +422,8 @@ pub fn get_required_usage_from<'a, 'b>( desc_reqs ); let mut ret_val = VecDeque::new(); - let args_in_groups = p.groups + let args_in_groups = p + .groups .iter() .filter(|gn| desc_reqs.contains(&gn.name)) .flat_map(|g| p.arg_names_in_group(g.name)) @@ -447,9 +464,8 @@ pub fn get_required_usage_from<'a, 'b>( .filter(|name| !p.positionals.values().any(|p| &&p.b.name == name)) .filter(|name| !p.groups.iter().any(|g| &&g.name == name)) .filter(|name| !args_in_groups.contains(name)) - .filter(|name| { - !(matcher.is_some() && matcher.as_ref().unwrap().contains(name)) - }) { + .filter(|name| !(matcher.is_some() && matcher.as_ref().unwrap().contains(name))) + { debugln!("usage::get_required_usage_from:iter:{}:", a); let arg = find_by_name!(p, *a, flags, iter) .map(|f| f.to_string()) diff --git a/src/app/validator.rs b/src/app/validator.rs index 181b831d0b3..862f0bbde4e 100644 --- a/src/app/validator.rs +++ b/src/app/validator.rs @@ -1,19 +1,19 @@ // std -use std::fmt::Display; #[allow(deprecated, unused_imports)] use std::ascii::AsciiExt; +use std::fmt::Display; // Internal -use INTERNAL_ERROR_MSG; -use INVALID_UTF8; -use args::{AnyArg, ArgMatcher, MatchedArg}; +use app::parser::{ParseResult, Parser}; +use app::settings::AppSettings as AS; +use app::usage; use args::settings::ArgSettings; -use errors::{Error, ErrorKind}; +use args::{AnyArg, ArgMatcher, MatchedArg}; use errors::Result as ClapResult; -use app::settings::AppSettings as AS; -use app::parser::{ParseResult, Parser}; +use errors::{Error, ErrorKind}; use fmt::{Colorizer, ColorizerOption}; -use app::usage; +use INTERNAL_ERROR_MSG; +use INVALID_UTF8; pub struct Validator<'a, 'b, 'z>(&'z mut Parser<'a, 'b>) where @@ -21,7 +21,9 @@ where 'b: 'z; impl<'a, 'b, 'z> Validator<'a, 'b, 'z> { - pub fn new(p: &'z mut Parser<'a, 'b>) -> Self { Validator(p) } + pub fn new(p: &'z mut Parser<'a, 'b>) -> Self { + Validator(p) + } pub fn validate( &mut self, @@ -37,11 +39,11 @@ impl<'a, 'b, 'z> Validator<'a, 'b, 'z> { debugln!("Validator::validate: needs_val_of={:?}", a); let o = { self.0 - .opts - .iter() - .find(|o| o.b.name == a) - .expect(INTERNAL_ERROR_MSG) - .clone() + .opts + .iter() + .find(|o| o.b.name == a) + .expect(INTERNAL_ERROR_MSG) + .clone() }; self.validate_required(matcher)?; reqs_validated = true; @@ -59,7 +61,8 @@ impl<'a, 'b, 'z> Validator<'a, 'b, 'z> { } } - if matcher.is_empty() && matcher.subcommand_name().is_none() + if matcher.is_empty() + && matcher.subcommand_name().is_none() && self.0.is_set(AS::ArgRequiredElseHelp) { let mut out = vec![]; @@ -119,7 +122,8 @@ impl<'a, 'b, 'z> Validator<'a, 'b, 'z> { )); } } - if !arg.is_set(ArgSettings::EmptyValues) && val.is_empty() + if !arg.is_set(ArgSettings::EmptyValues) + && val.is_empty() && matcher.contains(&*arg.name()) { debugln!("Validator::validate_arg_values: illegal empty val found"); @@ -158,15 +162,15 @@ impl<'a, 'b, 'z> Validator<'a, 'b, 'z> { fn build_err(&self, name: &str, matcher: &ArgMatcher) -> ClapResult<()> { debugln!("build_err!: name={}", name); let mut c_with = find_from!(self.0, &name, blacklist, matcher); - c_with = c_with.or( - self.0.find_any_arg(name).map_or(None, |aa| aa.blacklist()) - .map_or(None, - |bl| bl.iter().find(|arg| matcher.contains(arg))) + c_with = c_with.or(self + .0 + .find_any_arg(name) + .map_or(None, |aa| aa.blacklist()) + .map_or(None, |bl| bl.iter().find(|arg| matcher.contains(arg))) .map_or(None, |an| self.0.find_any_arg(an)) - .map_or(None, |aa| Some(format!("{}", aa))) - ); + .map_or(None, |aa| Some(format!("{}", aa)))); debugln!("build_err!: '{:?}' conflicts with '{}'", c_with, &name); -// matcher.remove(&name); + // matcher.remove(&name); let usg = usage::create_error_usage(self.0, matcher, None); if let Some(f) = find_by_name!(self.0, name, flags, iter) { debugln!("build_err!: It was a flag..."); @@ -179,8 +183,8 @@ impl<'a, 'b, 'z> Validator<'a, 'b, 'z> { Some(p) => { debugln!("build_err!: It was a positional..."); Err(Error::argument_conflict(p, c_with, &*usg, self.0.color())) - }, - None => panic!(INTERNAL_ERROR_MSG) + } + None => panic!(INTERNAL_ERROR_MSG), } } } @@ -219,7 +223,11 @@ impl<'a, 'b, 'z> Validator<'a, 'b, 'z> { debugln!("Validator::validate_blacklist:iter:{}:group;", name); let args = self.0.arg_names_in_group(name); for arg in &args { - debugln!("Validator::validate_blacklist:iter:{}:group:iter:{};", name, arg); + debugln!( + "Validator::validate_blacklist:iter:{}:group:iter:{};", + name, + arg + ); if let Some(bl) = find_any_by_name!(self.0, *arg).unwrap().blacklist() { for conf in bl { if matcher.get(conf).is_some() { @@ -293,7 +301,8 @@ impl<'a, 'b, 'z> Validator<'a, 'b, 'z> { self.validate_arg_values(pos, ma, matcher)?; self.validate_arg_requires(pos, ma, matcher)?; } else { - let grp = self.0 + let grp = self + .0 .groups .iter() .find(|g| &g.name == name) @@ -475,7 +484,7 @@ impl<'a, 'b, 'z> Validator<'a, 'b, 'z> { } if should_err { for r in &to_rem { - 'inner: for i in (0 .. self.0.required.len()).rev() { + 'inner: for i in (0..self.0.required.len()).rev() { if &self.0.required[i] == r { self.0.required.swap_remove(i); break 'inner; @@ -501,7 +510,8 @@ impl<'a, 'b, 'z> Validator<'a, 'b, 'z> { a.blacklist().map(|bl| { bl.iter().any(|conf| { matcher.contains(conf) - || self.0 + || self + .0 .groups .iter() .find(|g| &g.name == conf) @@ -518,7 +528,7 @@ impl<'a, 'b, 'z> Validator<'a, 'b, 'z> { ru.iter().$how(|n| { $m.contains(n) || { if let Some(grp) = $_self.groups.iter().find(|g| &g.name == n) { - grp.args.iter().any(|arg| $m.contains(arg)) + grp.args.iter().any(|arg| $m.contains(arg)) } else { false } diff --git a/src/args/any_arg.rs b/src/args/any_arg.rs index eee52283328..46aa763b0a6 100644 --- a/src/args/any_arg.rs +++ b/src/args/any_arg.rs @@ -1,7 +1,7 @@ // Std -use std::rc::Rc; -use std::fmt as std_fmt; use std::ffi::{OsStr, OsString}; +use std::fmt as std_fmt; +use std::rc::Rc; // Internal use args::settings::ArgSettings; @@ -43,32 +43,89 @@ pub trait DispOrder { fn disp_ord(&self) -> usize; } -impl<'n, 'e, 'z, T: ?Sized> AnyArg<'n, 'e> for &'z T where T: AnyArg<'n, 'e> + 'z { - fn name(&self) -> &'n str { (*self).name() } - fn overrides(&self) -> Option<&[&'e str]> { (*self).overrides() } - fn aliases(&self) -> Option> { (*self).aliases() } - fn requires(&self) -> Option<&[(Option<&'e str>, &'n str)]> { (*self).requires() } - fn blacklist(&self) -> Option<&[&'e str]> { (*self).blacklist() } - fn required_unless(&self) -> Option<&[&'e str]> { (*self).required_unless() } - fn is_set(&self, a: ArgSettings) -> bool { (*self).is_set(a) } - fn set(&mut self, _: ArgSettings) { panic!(INTERNAL_ERROR_MSG) } - fn has_switch(&self) -> bool { (*self).has_switch() } - fn max_vals(&self) -> Option { (*self).max_vals() } - fn min_vals(&self) -> Option { (*self).min_vals() } - fn num_vals(&self) -> Option { (*self).num_vals() } - fn possible_vals(&self) -> Option<&[&'e str]> { (*self).possible_vals() } - fn validator(&self) -> Option<&Rc Result<(), String>>> { (*self).validator() } - fn validator_os(&self) -> Option<&Rc Result<(), OsString>>> { (*self).validator_os() } - fn short(&self) -> Option { (*self).short() } - fn long(&self) -> Option<&'e str> { (*self).long() } - fn val_delim(&self) -> Option { (*self).val_delim() } - fn takes_value(&self) -> bool { (*self).takes_value() } - fn val_names(&self) -> Option<&VecMap<&'e str>> { (*self).val_names() } - fn help(&self) -> Option<&'e str> { (*self).help() } - fn long_help(&self) -> Option<&'e str> { (*self).long_help() } - fn default_val(&self) -> Option<&'e OsStr> { (*self).default_val() } - fn default_vals_ifs(&self) -> Option, &'e OsStr)>> { (*self).default_vals_ifs() } - fn env<'s>(&'s self) -> Option<(&'n OsStr, Option<&'s OsString>)> { (*self).env() } - fn longest_filter(&self) -> bool { (*self).longest_filter() } - fn val_terminator(&self) -> Option<&'e str> { (*self).val_terminator() } +impl<'n, 'e, 'z, T: ?Sized> AnyArg<'n, 'e> for &'z T +where + T: AnyArg<'n, 'e> + 'z, +{ + fn name(&self) -> &'n str { + (*self).name() + } + fn overrides(&self) -> Option<&[&'e str]> { + (*self).overrides() + } + fn aliases(&self) -> Option> { + (*self).aliases() + } + fn requires(&self) -> Option<&[(Option<&'e str>, &'n str)]> { + (*self).requires() + } + fn blacklist(&self) -> Option<&[&'e str]> { + (*self).blacklist() + } + fn required_unless(&self) -> Option<&[&'e str]> { + (*self).required_unless() + } + fn is_set(&self, a: ArgSettings) -> bool { + (*self).is_set(a) + } + fn set(&mut self, _: ArgSettings) { + panic!(INTERNAL_ERROR_MSG) + } + fn has_switch(&self) -> bool { + (*self).has_switch() + } + fn max_vals(&self) -> Option { + (*self).max_vals() + } + fn min_vals(&self) -> Option { + (*self).min_vals() + } + fn num_vals(&self) -> Option { + (*self).num_vals() + } + fn possible_vals(&self) -> Option<&[&'e str]> { + (*self).possible_vals() + } + fn validator(&self) -> Option<&Rc Result<(), String>>> { + (*self).validator() + } + fn validator_os(&self) -> Option<&Rc Result<(), OsString>>> { + (*self).validator_os() + } + fn short(&self) -> Option { + (*self).short() + } + fn long(&self) -> Option<&'e str> { + (*self).long() + } + fn val_delim(&self) -> Option { + (*self).val_delim() + } + fn takes_value(&self) -> bool { + (*self).takes_value() + } + fn val_names(&self) -> Option<&VecMap<&'e str>> { + (*self).val_names() + } + fn help(&self) -> Option<&'e str> { + (*self).help() + } + fn long_help(&self) -> Option<&'e str> { + (*self).long_help() + } + fn default_val(&self) -> Option<&'e OsStr> { + (*self).default_val() + } + fn default_vals_ifs(&self) -> Option, &'e OsStr)>> { + (*self).default_vals_ifs() + } + fn env<'s>(&'s self) -> Option<(&'n OsStr, Option<&'s OsString>)> { + (*self).env() + } + fn longest_filter(&self) -> bool { + (*self).longest_filter() + } + fn val_terminator(&self) -> Option<&'e str> { + (*self).val_terminator() + } } diff --git a/src/args/arg.rs b/src/args/arg.rs index 50a30abb7ac..ce578e0a451 100644 --- a/src/args/arg.rs +++ b/src/args/arg.rs @@ -1,20 +1,20 @@ +#[cfg(any(target_os = "windows", target_arch = "wasm32"))] +use osstringext::OsStrExt3; #[cfg(feature = "yaml")] use std::collections::BTreeMap; -use std::rc::Rc; +use std::env; use std::ffi::{OsStr, OsString}; -#[cfg(any(target_os = "windows", target_arch = "wasm32"))] -use osstringext::OsStrExt3; #[cfg(not(any(target_os = "windows", target_arch = "wasm32")))] use std::os::unix::ffi::OsStrExt; -use std::env; +use std::rc::Rc; +use map::VecMap; #[cfg(feature = "yaml")] use yaml_rust::Yaml; -use map::VecMap; -use usage_parser::UsageParser; -use args::settings::ArgSettings; use args::arg_builder::{Base, Switched, Valued}; +use args::settings::ArgSettings; +use usage_parser::UsageParser; /// The abstract representation of a command line argument. Used to set all the options and /// relationships that define a valid argument for the program. @@ -44,11 +44,16 @@ pub struct Arg<'a, 'b> where 'a: 'b, { - #[doc(hidden)] pub b: Base<'a, 'b>, - #[doc(hidden)] pub s: Switched<'b>, - #[doc(hidden)] pub v: Valued<'a, 'b>, - #[doc(hidden)] pub index: Option, - #[doc(hidden)] pub r_ifs: Option>, + #[doc(hidden)] + pub b: Base<'a, 'b>, + #[doc(hidden)] + pub s: Switched<'b>, + #[doc(hidden)] + pub v: Valued<'a, 'b>, + #[doc(hidden)] + pub index: Option, + #[doc(hidden)] + pub r_ifs: Option>, } impl<'a, 'b> Arg<'a, 'b> { diff --git a/src/args/arg_builder/base.rs b/src/args/arg_builder/base.rs index fef9d8ab979..cc8de7288a9 100644 --- a/src/args/arg_builder/base.rs +++ b/src/args/arg_builder/base.rs @@ -24,15 +24,25 @@ impl<'n, 'e> Base<'n, 'e> { } } - pub fn set(&mut self, s: ArgSettings) { self.settings.set(s); } - pub fn unset(&mut self, s: ArgSettings) { self.settings.unset(s); } - pub fn is_set(&self, s: ArgSettings) -> bool { self.settings.is_set(s) } + pub fn set(&mut self, s: ArgSettings) { + self.settings.set(s); + } + pub fn unset(&mut self, s: ArgSettings) { + self.settings.unset(s); + } + pub fn is_set(&self, s: ArgSettings) -> bool { + self.settings.is_set(s) + } } impl<'n, 'e, 'z> From<&'z Arg<'n, 'e>> for Base<'n, 'e> { - fn from(a: &'z Arg<'n, 'e>) -> Self { a.b.clone() } + fn from(a: &'z Arg<'n, 'e>) -> Self { + a.b.clone() + } } impl<'n, 'e> PartialEq for Base<'n, 'e> { - fn eq(&self, other: &Base<'n, 'e>) -> bool { self.name == other.name } + fn eq(&self, other: &Base<'n, 'e>) -> bool { + self.name == other.name + } } diff --git a/src/args/arg_builder/flag.rs b/src/args/arg_builder/flag.rs index 641e7777e00..4b92231248e 100644 --- a/src/args/arg_builder/flag.rs +++ b/src/args/arg_builder/flag.rs @@ -1,15 +1,15 @@ // Std use std::convert::From; +use std::ffi::{OsStr, OsString}; use std::fmt::{Display, Formatter, Result}; +use std::mem; use std::rc::Rc; use std::result::Result as StdResult; -use std::ffi::{OsStr, OsString}; -use std::mem; // Internal -use Arg; use args::{AnyArg, ArgSettings, Base, DispOrder, Switched}; use map::{self, VecMap}; +use Arg; #[derive(Default, Clone, Debug)] #[doc(hidden)] @@ -61,36 +61,84 @@ impl<'n, 'e> Display for FlagBuilder<'n, 'e> { } impl<'n, 'e> AnyArg<'n, 'e> for FlagBuilder<'n, 'e> { - fn name(&self) -> &'n str { self.b.name } - fn overrides(&self) -> Option<&[&'e str]> { self.b.overrides.as_ref().map(|o| &o[..]) } + fn name(&self) -> &'n str { + self.b.name + } + fn overrides(&self) -> Option<&[&'e str]> { + self.b.overrides.as_ref().map(|o| &o[..]) + } fn requires(&self) -> Option<&[(Option<&'e str>, &'n str)]> { self.b.requires.as_ref().map(|o| &o[..]) } - fn blacklist(&self) -> Option<&[&'e str]> { self.b.blacklist.as_ref().map(|o| &o[..]) } - fn required_unless(&self) -> Option<&[&'e str]> { self.b.r_unless.as_ref().map(|o| &o[..]) } - fn is_set(&self, s: ArgSettings) -> bool { self.b.settings.is_set(s) } - fn has_switch(&self) -> bool { true } - fn takes_value(&self) -> bool { false } - fn set(&mut self, s: ArgSettings) { self.b.settings.set(s) } - fn max_vals(&self) -> Option { None } - fn val_names(&self) -> Option<&VecMap<&'e str>> { None } - fn num_vals(&self) -> Option { None } - fn possible_vals(&self) -> Option<&[&'e str]> { None } - fn validator(&self) -> Option<&Rc StdResult<(), String>>> { None } - fn validator_os(&self) -> Option<&Rc StdResult<(), OsString>>> { None } - fn min_vals(&self) -> Option { None } - fn short(&self) -> Option { self.s.short } - fn long(&self) -> Option<&'e str> { self.s.long } - fn val_delim(&self) -> Option { None } - fn help(&self) -> Option<&'e str> { self.b.help } - fn long_help(&self) -> Option<&'e str> { self.b.long_help } - fn val_terminator(&self) -> Option<&'e str> { None } - fn default_val(&self) -> Option<&'e OsStr> { None } + fn blacklist(&self) -> Option<&[&'e str]> { + self.b.blacklist.as_ref().map(|o| &o[..]) + } + fn required_unless(&self) -> Option<&[&'e str]> { + self.b.r_unless.as_ref().map(|o| &o[..]) + } + fn is_set(&self, s: ArgSettings) -> bool { + self.b.settings.is_set(s) + } + fn has_switch(&self) -> bool { + true + } + fn takes_value(&self) -> bool { + false + } + fn set(&mut self, s: ArgSettings) { + self.b.settings.set(s) + } + fn max_vals(&self) -> Option { + None + } + fn val_names(&self) -> Option<&VecMap<&'e str>> { + None + } + fn num_vals(&self) -> Option { + None + } + fn possible_vals(&self) -> Option<&[&'e str]> { + None + } + fn validator(&self) -> Option<&Rc StdResult<(), String>>> { + None + } + fn validator_os(&self) -> Option<&Rc StdResult<(), OsString>>> { + None + } + fn min_vals(&self) -> Option { + None + } + fn short(&self) -> Option { + self.s.short + } + fn long(&self) -> Option<&'e str> { + self.s.long + } + fn val_delim(&self) -> Option { + None + } + fn help(&self) -> Option<&'e str> { + self.b.help + } + fn long_help(&self) -> Option<&'e str> { + self.b.long_help + } + fn val_terminator(&self) -> Option<&'e str> { + None + } + fn default_val(&self) -> Option<&'e OsStr> { + None + } fn default_vals_ifs(&self) -> Option, &'e OsStr)>> { None } - fn env<'s>(&'s self) -> Option<(&'n OsStr, Option<&'s OsString>)> { None } - fn longest_filter(&self) -> bool { self.s.long.is_some() } + fn env<'s>(&'s self) -> Option<(&'n OsStr, Option<&'s OsString>)> { + None + } + fn longest_filter(&self) -> bool { + self.s.long.is_some() + } fn aliases(&self) -> Option> { if let Some(ref aliases) = self.s.aliases { let vis_aliases: Vec<_> = aliases @@ -109,17 +157,21 @@ impl<'n, 'e> AnyArg<'n, 'e> for FlagBuilder<'n, 'e> { } impl<'n, 'e> DispOrder for FlagBuilder<'n, 'e> { - fn disp_ord(&self) -> usize { self.s.disp_ord } + fn disp_ord(&self) -> usize { + self.s.disp_ord + } } impl<'n, 'e> PartialEq for FlagBuilder<'n, 'e> { - fn eq(&self, other: &FlagBuilder<'n, 'e>) -> bool { self.b == other.b } + fn eq(&self, other: &FlagBuilder<'n, 'e>) -> bool { + self.b == other.b + } } #[cfg(test)] mod test { - use args::settings::ArgSettings; use super::FlagBuilder; + use args::settings::ArgSettings; #[test] fn flagbuilder_display() { diff --git a/src/args/arg_builder/mod.rs b/src/args/arg_builder/mod.rs index d1a7a660866..2d7920819a5 100644 --- a/src/args/arg_builder/mod.rs +++ b/src/args/arg_builder/mod.rs @@ -1,13 +1,13 @@ +pub use self::base::Base; pub use self::flag::FlagBuilder; pub use self::option::OptBuilder; pub use self::positional::PosBuilder; -pub use self::base::Base; pub use self::switched::Switched; pub use self::valued::Valued; +mod base; mod flag; -mod positional; mod option; -mod base; -mod valued; +mod positional; mod switched; +mod valued; diff --git a/src/args/arg_builder/option.rs b/src/args/arg_builder/option.rs index 4bb147a7d2d..45d41fa027d 100644 --- a/src/args/arg_builder/option.rs +++ b/src/args/arg_builder/option.rs @@ -1,9 +1,9 @@ // Std +use std::ffi::{OsStr, OsString}; use std::fmt::{Display, Formatter, Result}; +use std::mem; use std::rc::Rc; use std::result::Result as StdResult; -use std::ffi::{OsStr, OsString}; -use std::mem; // Internal use args::{AnyArg, Arg, ArgSettings, Base, DispOrder, Switched, Valued}; @@ -114,35 +114,75 @@ impl<'n, 'e> Display for OptBuilder<'n, 'e> { } impl<'n, 'e> AnyArg<'n, 'e> for OptBuilder<'n, 'e> { - fn name(&self) -> &'n str { self.b.name } - fn overrides(&self) -> Option<&[&'e str]> { self.b.overrides.as_ref().map(|o| &o[..]) } + fn name(&self) -> &'n str { + self.b.name + } + fn overrides(&self) -> Option<&[&'e str]> { + self.b.overrides.as_ref().map(|o| &o[..]) + } fn requires(&self) -> Option<&[(Option<&'e str>, &'n str)]> { self.b.requires.as_ref().map(|o| &o[..]) } - fn blacklist(&self) -> Option<&[&'e str]> { self.b.blacklist.as_ref().map(|o| &o[..]) } - fn required_unless(&self) -> Option<&[&'e str]> { self.b.r_unless.as_ref().map(|o| &o[..]) } - fn val_names(&self) -> Option<&VecMap<&'e str>> { self.v.val_names.as_ref() } - fn is_set(&self, s: ArgSettings) -> bool { self.b.settings.is_set(s) } - fn has_switch(&self) -> bool { true } - fn set(&mut self, s: ArgSettings) { self.b.settings.set(s) } - fn max_vals(&self) -> Option { self.v.max_vals } - fn val_terminator(&self) -> Option<&'e str> { self.v.terminator } - fn num_vals(&self) -> Option { self.v.num_vals } - fn possible_vals(&self) -> Option<&[&'e str]> { self.v.possible_vals.as_ref().map(|o| &o[..]) } + fn blacklist(&self) -> Option<&[&'e str]> { + self.b.blacklist.as_ref().map(|o| &o[..]) + } + fn required_unless(&self) -> Option<&[&'e str]> { + self.b.r_unless.as_ref().map(|o| &o[..]) + } + fn val_names(&self) -> Option<&VecMap<&'e str>> { + self.v.val_names.as_ref() + } + fn is_set(&self, s: ArgSettings) -> bool { + self.b.settings.is_set(s) + } + fn has_switch(&self) -> bool { + true + } + fn set(&mut self, s: ArgSettings) { + self.b.settings.set(s) + } + fn max_vals(&self) -> Option { + self.v.max_vals + } + fn val_terminator(&self) -> Option<&'e str> { + self.v.terminator + } + fn num_vals(&self) -> Option { + self.v.num_vals + } + fn possible_vals(&self) -> Option<&[&'e str]> { + self.v.possible_vals.as_ref().map(|o| &o[..]) + } fn validator(&self) -> Option<&Rc StdResult<(), String>>> { self.v.validator.as_ref() } fn validator_os(&self) -> Option<&Rc StdResult<(), OsString>>> { self.v.validator_os.as_ref() } - fn min_vals(&self) -> Option { self.v.min_vals } - fn short(&self) -> Option { self.s.short } - fn long(&self) -> Option<&'e str> { self.s.long } - fn val_delim(&self) -> Option { self.v.val_delim } - fn takes_value(&self) -> bool { true } - fn help(&self) -> Option<&'e str> { self.b.help } - fn long_help(&self) -> Option<&'e str> { self.b.long_help } - fn default_val(&self) -> Option<&'e OsStr> { self.v.default_val } + fn min_vals(&self) -> Option { + self.v.min_vals + } + fn short(&self) -> Option { + self.s.short + } + fn long(&self) -> Option<&'e str> { + self.s.long + } + fn val_delim(&self) -> Option { + self.v.val_delim + } + fn takes_value(&self) -> bool { + true + } + fn help(&self) -> Option<&'e str> { + self.b.help + } + fn long_help(&self) -> Option<&'e str> { + self.b.long_help + } + fn default_val(&self) -> Option<&'e OsStr> { + self.v.default_val + } fn default_vals_ifs(&self) -> Option, &'e OsStr)>> { self.v.default_vals_ifs.as_ref().map(|vm| vm.values()) } @@ -152,7 +192,9 @@ impl<'n, 'e> AnyArg<'n, 'e> for OptBuilder<'n, 'e> { .as_ref() .map(|&(key, ref value)| (key, value.as_ref())) } - fn longest_filter(&self) -> bool { true } + fn longest_filter(&self) -> bool { + true + } fn aliases(&self) -> Option> { if let Some(ref aliases) = self.s.aliases { let vis_aliases: Vec<_> = aliases @@ -171,17 +213,21 @@ impl<'n, 'e> AnyArg<'n, 'e> for OptBuilder<'n, 'e> { } impl<'n, 'e> DispOrder for OptBuilder<'n, 'e> { - fn disp_ord(&self) -> usize { self.s.disp_ord } + fn disp_ord(&self) -> usize { + self.s.disp_ord + } } impl<'n, 'e> PartialEq for OptBuilder<'n, 'e> { - fn eq(&self, other: &OptBuilder<'n, 'e>) -> bool { self.b == other.b } + fn eq(&self, other: &OptBuilder<'n, 'e>) -> bool { + self.b == other.b + } } #[cfg(test)] mod test { - use args::settings::ArgSettings; use super::OptBuilder; + use args::settings::ArgSettings; use map::VecMap; #[test] diff --git a/src/args/arg_builder/positional.rs b/src/args/arg_builder/positional.rs index 43fdca4c580..6d8c1fe024e 100644 --- a/src/args/arg_builder/positional.rs +++ b/src/args/arg_builder/positional.rs @@ -1,16 +1,16 @@ // Std use std::borrow::Cow; +use std::ffi::{OsStr, OsString}; use std::fmt::{Display, Formatter, Result}; +use std::mem; use std::rc::Rc; use std::result::Result as StdResult; -use std::ffi::{OsStr, OsString}; -use std::mem; // Internal -use Arg; use args::{AnyArg, ArgSettings, Base, DispOrder, Valued}; -use INTERNAL_ERROR_MSG; use map::{self, VecMap}; +use Arg; +use INTERNAL_ERROR_MSG; #[allow(missing_debug_implementations)] #[doc(hidden)] @@ -39,7 +39,8 @@ impl<'n, 'e> PosBuilder<'n, 'e> { v: Valued::from(a), index: idx, }; - if a.v.max_vals.is_some() || a.v.min_vals.is_some() + if a.v.max_vals.is_some() + || a.v.min_vals.is_some() || (a.v.num_vals.is_some() && a.v.num_vals.unwrap() > 1) { pb.b.settings.set(ArgSettings::Multiple); @@ -48,7 +49,8 @@ impl<'n, 'e> PosBuilder<'n, 'e> { } pub fn from_arg(mut a: Arg<'n, 'e>, idx: u64) -> Self { - if a.v.max_vals.is_some() || a.v.min_vals.is_some() + if a.v.max_vals.is_some() + || a.v.min_vals.is_some() || (a.v.num_vals.is_some() && a.v.num_vals.unwrap() > 1) { a.b.settings.set(ArgSettings::Multiple); @@ -61,7 +63,8 @@ impl<'n, 'e> PosBuilder<'n, 'e> { } pub fn multiple_str(&self) -> &str { - let mult_vals = self.v + let mult_vals = self + .v .val_names .as_ref() .map_or(true, |names| names.len() < 2); @@ -132,60 +135,108 @@ impl<'n, 'e> Display for PosBuilder<'n, 'e> { } impl<'n, 'e> AnyArg<'n, 'e> for PosBuilder<'n, 'e> { - fn name(&self) -> &'n str { self.b.name } - fn overrides(&self) -> Option<&[&'e str]> { self.b.overrides.as_ref().map(|o| &o[..]) } + fn name(&self) -> &'n str { + self.b.name + } + fn overrides(&self) -> Option<&[&'e str]> { + self.b.overrides.as_ref().map(|o| &o[..]) + } fn requires(&self) -> Option<&[(Option<&'e str>, &'n str)]> { self.b.requires.as_ref().map(|o| &o[..]) } - fn blacklist(&self) -> Option<&[&'e str]> { self.b.blacklist.as_ref().map(|o| &o[..]) } - fn required_unless(&self) -> Option<&[&'e str]> { self.b.r_unless.as_ref().map(|o| &o[..]) } - fn val_names(&self) -> Option<&VecMap<&'e str>> { self.v.val_names.as_ref() } - fn is_set(&self, s: ArgSettings) -> bool { self.b.settings.is_set(s) } - fn set(&mut self, s: ArgSettings) { self.b.settings.set(s) } - fn has_switch(&self) -> bool { false } - fn max_vals(&self) -> Option { self.v.max_vals } - fn val_terminator(&self) -> Option<&'e str> { self.v.terminator } - fn num_vals(&self) -> Option { self.v.num_vals } - fn possible_vals(&self) -> Option<&[&'e str]> { self.v.possible_vals.as_ref().map(|o| &o[..]) } + fn blacklist(&self) -> Option<&[&'e str]> { + self.b.blacklist.as_ref().map(|o| &o[..]) + } + fn required_unless(&self) -> Option<&[&'e str]> { + self.b.r_unless.as_ref().map(|o| &o[..]) + } + fn val_names(&self) -> Option<&VecMap<&'e str>> { + self.v.val_names.as_ref() + } + fn is_set(&self, s: ArgSettings) -> bool { + self.b.settings.is_set(s) + } + fn set(&mut self, s: ArgSettings) { + self.b.settings.set(s) + } + fn has_switch(&self) -> bool { + false + } + fn max_vals(&self) -> Option { + self.v.max_vals + } + fn val_terminator(&self) -> Option<&'e str> { + self.v.terminator + } + fn num_vals(&self) -> Option { + self.v.num_vals + } + fn possible_vals(&self) -> Option<&[&'e str]> { + self.v.possible_vals.as_ref().map(|o| &o[..]) + } fn validator(&self) -> Option<&Rc StdResult<(), String>>> { self.v.validator.as_ref() } fn validator_os(&self) -> Option<&Rc StdResult<(), OsString>>> { self.v.validator_os.as_ref() } - fn min_vals(&self) -> Option { self.v.min_vals } - fn short(&self) -> Option { None } - fn long(&self) -> Option<&'e str> { None } - fn val_delim(&self) -> Option { self.v.val_delim } - fn takes_value(&self) -> bool { true } - fn help(&self) -> Option<&'e str> { self.b.help } - fn long_help(&self) -> Option<&'e str> { self.b.long_help } + fn min_vals(&self) -> Option { + self.v.min_vals + } + fn short(&self) -> Option { + None + } + fn long(&self) -> Option<&'e str> { + None + } + fn val_delim(&self) -> Option { + self.v.val_delim + } + fn takes_value(&self) -> bool { + true + } + fn help(&self) -> Option<&'e str> { + self.b.help + } + fn long_help(&self) -> Option<&'e str> { + self.b.long_help + } fn default_vals_ifs(&self) -> Option, &'e OsStr)>> { self.v.default_vals_ifs.as_ref().map(|vm| vm.values()) } - fn default_val(&self) -> Option<&'e OsStr> { self.v.default_val } + fn default_val(&self) -> Option<&'e OsStr> { + self.v.default_val + } fn env<'s>(&'s self) -> Option<(&'n OsStr, Option<&'s OsString>)> { self.v .env .as_ref() .map(|&(key, ref value)| (key, value.as_ref())) } - fn longest_filter(&self) -> bool { true } - fn aliases(&self) -> Option> { None } + fn longest_filter(&self) -> bool { + true + } + fn aliases(&self) -> Option> { + None + } } impl<'n, 'e> DispOrder for PosBuilder<'n, 'e> { - fn disp_ord(&self) -> usize { self.index as usize } + fn disp_ord(&self) -> usize { + self.index as usize + } } impl<'n, 'e> PartialEq for PosBuilder<'n, 'e> { - fn eq(&self, other: &PosBuilder<'n, 'e>) -> bool { self.b == other.b } + fn eq(&self, other: &PosBuilder<'n, 'e>) -> bool { + self.b == other.b + } } #[cfg(test)] mod test { - use args::settings::ArgSettings; use super::PosBuilder; + use args::settings::ArgSettings; use map::VecMap; #[test] diff --git a/src/args/arg_builder/switched.rs b/src/args/arg_builder/switched.rs index 224b2f2b24b..777ff1d590b 100644 --- a/src/args/arg_builder/switched.rs +++ b/src/args/arg_builder/switched.rs @@ -22,7 +22,9 @@ impl<'e> Default for Switched<'e> { } impl<'n, 'e, 'z> From<&'z Arg<'n, 'e>> for Switched<'e> { - fn from(a: &'z Arg<'n, 'e>) -> Self { a.s.clone() } + fn from(a: &'z Arg<'n, 'e>) -> Self { + a.s.clone() + } } impl<'e> Clone for Switched<'e> { diff --git a/src/args/arg_builder/valued.rs b/src/args/arg_builder/valued.rs index d70854dc89a..82e148754b2 100644 --- a/src/args/arg_builder/valued.rs +++ b/src/args/arg_builder/valued.rs @@ -1,5 +1,5 @@ -use std::rc::Rc; use std::ffi::{OsStr, OsString}; +use std::rc::Rc; use map::VecMap; diff --git a/src/args/arg_matcher.rs b/src/args/arg_matcher.rs index e1d8067e69a..1a0a149c4d0 100644 --- a/src/args/arg_matcher.rs +++ b/src/args/arg_matcher.rs @@ -2,27 +2,40 @@ use std::collections::hash_map::{Entry, Iter}; use std::collections::HashMap; use std::ffi::OsStr; -use std::ops::Deref; use std::mem; +use std::ops::Deref; // Internal -use args::{ArgMatches, MatchedArg, SubCommand}; -use args::AnyArg; use args::settings::ArgSettings; +use args::AnyArg; +use args::{ArgMatches, MatchedArg, SubCommand}; #[doc(hidden)] #[allow(missing_debug_implementations)] pub struct ArgMatcher<'a>(pub ArgMatches<'a>); impl<'a> Default for ArgMatcher<'a> { - fn default() -> Self { ArgMatcher(ArgMatches::default()) } + fn default() -> Self { + ArgMatcher(ArgMatches::default()) + } } impl<'a> ArgMatcher<'a> { - pub fn new() -> Self { ArgMatcher::default() } + pub fn new() -> Self { + ArgMatcher::default() + } - pub fn process_arg_overrides<'b>(&mut self, a: Option<&AnyArg<'a, 'b>>, overrides: &mut Vec<(&'b str, &'a str)>, required: &mut Vec<&'a str>, check_all: bool) { - debugln!("ArgMatcher::process_arg_overrides:{:?};", a.map_or(None, |a| Some(a.name()))); + pub fn process_arg_overrides<'b>( + &mut self, + a: Option<&AnyArg<'a, 'b>>, + overrides: &mut Vec<(&'b str, &'a str)>, + required: &mut Vec<&'a str>, + check_all: bool, + ) { + debugln!( + "ArgMatcher::process_arg_overrides:{:?};", + a.map_or(None, |a| Some(a.name())) + ); if let Some(aa) = a { let mut self_done = false; if let Some(a_overrides) = aa.overrides() { @@ -32,11 +45,17 @@ impl<'a> ArgMatcher<'a> { self_done = true; self.handle_self_overrides(a); } else if self.is_present(overr) { - debugln!("ArgMatcher::process_arg_overrides:iter:{}: removing from matches;", overr); + debugln!( + "ArgMatcher::process_arg_overrides:iter:{}: removing from matches;", + overr + ); self.remove(overr); - for i in (0 .. required.len()).rev() { + for i in (0..required.len()).rev() { if &required[i] == overr { - debugln!("ArgMatcher::process_arg_overrides:iter:{}: removing required;", overr); + debugln!( + "ArgMatcher::process_arg_overrides:iter:{}: removing required;", + overr + ); required.swap_remove(i); break; } @@ -54,7 +73,10 @@ impl<'a> ArgMatcher<'a> { } pub fn handle_self_overrides<'b>(&mut self, a: Option<&AnyArg<'a, 'b>>) { - debugln!("ArgMatcher::handle_self_overrides:{:?};", a.map_or(None, |a| Some(a.name()))); + debugln!( + "ArgMatcher::handle_self_overrides:{:?};", + a.map_or(None, |a| Some(a.name())) + ); if let Some(aa) = a { if !aa.has_switch() || aa.is_set(ArgSettings::Multiple) { // positional args can't override self or else we would never advance to the next @@ -81,7 +103,10 @@ impl<'a> ArgMatcher<'a> { } pub fn propagate_globals(&mut self, global_arg_vec: &[&'a str]) { - debugln!( "ArgMatcher::get_global_values: global_arg_vec={:?}", global_arg_vec ); + debugln!( + "ArgMatcher::get_global_values: global_arg_vec={:?}", + global_arg_vec + ); let mut vals_map = HashMap::new(); self.fill_in_global_values(global_arg_vec, &mut vals_map); } @@ -122,11 +147,17 @@ impl<'a> ArgMatcher<'a> { } } - pub fn get_mut(&mut self, arg: &str) -> Option<&mut MatchedArg> { self.0.args.get_mut(arg) } + pub fn get_mut(&mut self, arg: &str) -> Option<&mut MatchedArg> { + self.0.args.get_mut(arg) + } - pub fn get(&self, arg: &str) -> Option<&MatchedArg> { self.0.args.get(arg) } + pub fn get(&self, arg: &str) -> Option<&MatchedArg> { + self.0.args.get(arg) + } - pub fn remove(&mut self, arg: &str) { self.0.args.remove(arg); } + pub fn remove(&mut self, arg: &str) { + self.0.args.remove(arg); + } pub fn remove_all(&mut self, args: &[&str]) { for &arg in args { @@ -134,23 +165,41 @@ impl<'a> ArgMatcher<'a> { } } - pub fn insert(&mut self, name: &'a str) { self.0.args.insert(name, MatchedArg::new()); } + pub fn insert(&mut self, name: &'a str) { + self.0.args.insert(name, MatchedArg::new()); + } - pub fn contains(&self, arg: &str) -> bool { self.0.args.contains_key(arg) } + pub fn contains(&self, arg: &str) -> bool { + self.0.args.contains_key(arg) + } - pub fn is_empty(&self) -> bool { self.0.args.is_empty() } + pub fn is_empty(&self) -> bool { + self.0.args.is_empty() + } - pub fn usage(&mut self, usage: String) { self.0.usage = Some(usage); } + pub fn usage(&mut self, usage: String) { + self.0.usage = Some(usage); + } - pub fn arg_names(&'a self) -> Vec<&'a str> { self.0.args.keys().map(Deref::deref).collect() } + pub fn arg_names(&'a self) -> Vec<&'a str> { + self.0.args.keys().map(Deref::deref).collect() + } - pub fn entry(&mut self, arg: &'a str) -> Entry<&'a str, MatchedArg> { self.0.args.entry(arg) } + pub fn entry(&mut self, arg: &'a str) -> Entry<&'a str, MatchedArg> { + self.0.args.entry(arg) + } - pub fn subcommand(&mut self, sc: SubCommand<'a>) { self.0.subcommand = Some(Box::new(sc)); } + pub fn subcommand(&mut self, sc: SubCommand<'a>) { + self.0.subcommand = Some(Box::new(sc)); + } - pub fn subcommand_name(&self) -> Option<&str> { self.0.subcommand_name() } + pub fn subcommand_name(&self) -> Option<&str> { + self.0.subcommand_name() + } - pub fn iter(&self) -> Iter<&str, MatchedArg> { self.0.args.iter() } + pub fn iter(&self) -> Iter<&str, MatchedArg> { + self.0.args.iter() + } pub fn inc_occurrence_of(&mut self, arg: &'a str) { debugln!("ArgMatcher::inc_occurrence_of: arg={}", arg); @@ -214,5 +263,7 @@ impl<'a> ArgMatcher<'a> { } impl<'a> Into> for ArgMatcher<'a> { - fn into(self) -> ArgMatches<'a> { self.0 } + fn into(self) -> ArgMatches<'a> { + self.0 + } } diff --git a/src/args/arg_matches.rs b/src/args/arg_matches.rs index 179f6f9f432..f017c4e2f51 100644 --- a/src/args/arg_matches.rs +++ b/src/args/arg_matches.rs @@ -6,9 +6,9 @@ use std::iter::Map; use std::slice::Iter; // Internal -use INVALID_UTF8; use args::MatchedArg; use args::SubCommand; +use INVALID_UTF8; /// Used to get information about the arguments that were supplied to the program at runtime by /// the user. New instances of this struct are obtained by using the [`App::get_matches`] family of @@ -59,9 +59,12 @@ use args::SubCommand; /// [`App::get_matches`]: ./struct.App.html#method.get_matches #[derive(Debug, Clone)] pub struct ArgMatches<'a> { - #[doc(hidden)] pub args: HashMap<&'a str, MatchedArg>, - #[doc(hidden)] pub subcommand: Option>>, - #[doc(hidden)] pub usage: Option, + #[doc(hidden)] + pub args: HashMap<&'a str, MatchedArg>, + #[doc(hidden)] + pub subcommand: Option>>, + #[doc(hidden)] + pub usage: Option, } impl<'a> Default for ArgMatches<'a> { @@ -210,7 +213,9 @@ impl<'a> ArgMatches<'a> { /// [`Iterator`]: https://doc.rust-lang.org/std/iter/trait.Iterator.html pub fn values_of>(&'a self, name: S) -> Option> { if let Some(arg) = self.args.get(name.as_ref()) { - fn to_str_slice(o: &OsString) -> &str { o.to_str().expect(INVALID_UTF8) } + fn to_str_slice(o: &OsString) -> &str { + o.to_str().expect(INVALID_UTF8) + } let to_str_slice: fn(&OsString) -> &str = to_str_slice; // coerce to fn pointer return Some(Values { iter: arg.vals.iter().map(to_str_slice), @@ -287,7 +292,9 @@ impl<'a> ArgMatches<'a> { /// [`OsString`]: https://doc.rust-lang.org/std/ffi/struct.OsString.html /// [`String`]: https://doc.rust-lang.org/std/string/struct.String.html pub fn values_of_os>(&'a self, name: S) -> Option> { - fn to_str_slice(o: &OsString) -> &OsStr { &*o } + fn to_str_slice(o: &OsString) -> &OsStr { + &*o + } let to_str_slice: fn(&'a OsString) -> &'a OsStr = to_str_slice; // coerce to fn pointer if let Some(arg) = self.args.get(name.as_ref()) { return Some(OsValues { @@ -578,7 +585,9 @@ impl<'a> ArgMatches<'a> { /// [delimiter]: ./struct.Arg.html#method.value_delimiter pub fn indices_of>(&'a self, name: S) -> Option> { if let Some(arg) = self.args.get(name.as_ref()) { - fn to_usize(i: &usize) -> usize { *i } + fn to_usize(i: &usize) -> usize { + *i + } let to_usize: fn(&usize) -> usize = to_usize; // coerce to fn pointer return Some(Indices { iter: arg.indices.iter().map(to_usize), @@ -756,10 +765,11 @@ impl<'a> ArgMatches<'a> { /// ``` /// [`Subcommand`]: ./struct.SubCommand.html /// [`App`]: ./struct.App.html - pub fn usage(&self) -> &str { self.usage.as_ref().map_or("", |u| &u[..]) } + pub fn usage(&self) -> &str { + self.usage.as_ref().map_or("", |u| &u[..]) + } } - // The following were taken and adapated from vec_map source // repo: https://github.com/contain-rs/vec-map // commit: be5e1fa3c26e351761b33010ddbdaf5f05dbcc33 @@ -794,12 +804,18 @@ pub struct Values<'a> { impl<'a> Iterator for Values<'a> { type Item = &'a str; - fn next(&mut self) -> Option<&'a str> { self.iter.next() } - fn size_hint(&self) -> (usize, Option) { self.iter.size_hint() } + fn next(&mut self) -> Option<&'a str> { + self.iter.next() + } + fn size_hint(&self) -> (usize, Option) { + self.iter.size_hint() + } } impl<'a> DoubleEndedIterator for Values<'a> { - fn next_back(&mut self) -> Option<&'a str> { self.iter.next_back() } + fn next_back(&mut self) -> Option<&'a str> { + self.iter.next_back() + } } impl<'a> ExactSizeIterator for Values<'a> {} @@ -809,7 +825,9 @@ impl<'a> Default for Values<'a> { fn default() -> Self { static EMPTY: [OsString; 0] = []; // This is never called because the iterator is empty: - fn to_str_slice(_: &OsString) -> &str { unreachable!() }; + fn to_str_slice(_: &OsString) -> &str { + unreachable!() + }; Values { iter: EMPTY[..].iter().map(to_str_slice), } @@ -845,12 +863,18 @@ pub struct OsValues<'a> { impl<'a> Iterator for OsValues<'a> { type Item = &'a OsStr; - fn next(&mut self) -> Option<&'a OsStr> { self.iter.next() } - fn size_hint(&self) -> (usize, Option) { self.iter.size_hint() } + fn next(&mut self) -> Option<&'a OsStr> { + self.iter.next() + } + fn size_hint(&self) -> (usize, Option) { + self.iter.size_hint() + } } impl<'a> DoubleEndedIterator for OsValues<'a> { - fn next_back(&mut self) -> Option<&'a OsStr> { self.iter.next_back() } + fn next_back(&mut self) -> Option<&'a OsStr> { + self.iter.next_back() + } } impl<'a> ExactSizeIterator for OsValues<'a> {} @@ -860,7 +884,9 @@ impl<'a> Default for OsValues<'a> { fn default() -> Self { static EMPTY: [OsString; 0] = []; // This is never called because the iterator is empty: - fn to_str_slice(_: &OsString) -> &OsStr { unreachable!() }; + fn to_str_slice(_: &OsString) -> &OsStr { + unreachable!() + }; OsValues { iter: EMPTY[..].iter().map(to_str_slice), } @@ -889,19 +915,26 @@ impl<'a> Default for OsValues<'a> { /// ``` /// [`ArgMatches::indices_of`]: ./struct.ArgMatches.html#method.indices_of #[derive(Debug, Clone)] -pub struct Indices<'a> { // would rather use '_, but: https://github.com/rust-lang/rust/issues/48469 +pub struct Indices<'a> { + // would rather use '_, but: https://github.com/rust-lang/rust/issues/48469 iter: Map, fn(&'a usize) -> usize>, } impl<'a> Iterator for Indices<'a> { type Item = usize; - fn next(&mut self) -> Option { self.iter.next() } - fn size_hint(&self) -> (usize, Option) { self.iter.size_hint() } + fn next(&mut self) -> Option { + self.iter.next() + } + fn size_hint(&self) -> (usize, Option) { + self.iter.size_hint() + } } impl<'a> DoubleEndedIterator for Indices<'a> { - fn next_back(&mut self) -> Option { self.iter.next_back() } + fn next_back(&mut self) -> Option { + self.iter.next_back() + } } impl<'a> ExactSizeIterator for Indices<'a> {} @@ -911,7 +944,9 @@ impl<'a> Default for Indices<'a> { fn default() -> Self { static EMPTY: [usize; 0] = []; // This is never called because the iterator is empty: - fn to_usize(_: &usize) -> usize { unreachable!() }; + fn to_usize(_: &usize) -> usize { + unreachable!() + }; Indices { iter: EMPTY[..].iter().map(to_usize), } diff --git a/src/args/group.rs b/src/args/group.rs index f8bfb7a0864..8103a9c7897 100644 --- a/src/args/group.rs +++ b/src/args/group.rs @@ -79,12 +79,18 @@ use yaml_rust::Yaml; /// [requirement]: ./struct.Arg.html#method.requires #[derive(Default)] pub struct ArgGroup<'a> { - #[doc(hidden)] pub name: &'a str, - #[doc(hidden)] pub args: Vec<&'a str>, - #[doc(hidden)] pub required: bool, - #[doc(hidden)] pub requires: Option>, - #[doc(hidden)] pub conflicts: Option>, - #[doc(hidden)] pub multiple: bool, + #[doc(hidden)] + pub name: &'a str, + #[doc(hidden)] + pub args: Vec<&'a str>, + #[doc(hidden)] + pub required: bool, + #[doc(hidden)] + pub requires: Option>, + #[doc(hidden)] + pub conflicts: Option>, + #[doc(hidden)] + pub multiple: bool, } impl<'a> ArgGroup<'a> { @@ -123,7 +129,9 @@ impl<'a> ArgGroup<'a> { /// # } /// ``` #[cfg(feature = "yaml")] - pub fn from_yaml(y: &'a Yaml) -> ArgGroup<'a> { ArgGroup::from(y.as_hash().unwrap()) } + pub fn from_yaml(y: &'a Yaml) -> ArgGroup<'a> { + ArgGroup::from(y.as_hash().unwrap()) + } /// Adds an [argument] to this group by name /// @@ -431,11 +439,7 @@ impl<'a> Debug for ArgGroup<'a> { \trequires: {:?},\n\ \tconflicts: {:?},\n\ }}", - self.name, - self.args, - self.required, - self.requires, - self.conflicts + self.name, self.args, self.required, self.requires, self.conflicts ) } } @@ -494,8 +498,7 @@ impl<'a> From<&'a BTreeMap> for ArgGroup<'a> { s => panic!( "Unknown ArgGroup setting '{}' in YAML file for \ ArgGroup '{}'", - s, - a.name + s, a.name ), } } diff --git a/src/args/macros.rs b/src/args/macros.rs index 1de12f4ec20..ac4b1a2d551 100644 --- a/src/args/macros.rs +++ b/src/args/macros.rs @@ -1,72 +1,75 @@ #[cfg(feature = "yaml")] macro_rules! yaml_tuple2 { ($a:ident, $v:ident, $c:ident) => {{ - if let Some(vec) = $v.as_vec() { - for ys in vec { - if let Some(tup) = ys.as_vec() { - debug_assert_eq!(2, tup.len()); - $a = $a.$c(yaml_str!(tup[0]), yaml_str!(tup[1])); - } else { - panic!("Failed to convert YAML value to vec"); - } + if let Some(vec) = $v.as_vec() { + for ys in vec { + if let Some(tup) = ys.as_vec() { + debug_assert_eq!(2, tup.len()); + $a = $a.$c(yaml_str!(tup[0]), yaml_str!(tup[1])); + } else { + panic!("Failed to convert YAML value to vec"); } - } else { - panic!("Failed to convert YAML value to vec"); } - $a + } else { + panic!("Failed to convert YAML value to vec"); } - }; + $a + }}; } #[cfg(feature = "yaml")] macro_rules! yaml_tuple3 { ($a:ident, $v:ident, $c:ident) => {{ - if let Some(vec) = $v.as_vec() { - for ys in vec { - if let Some(tup) = ys.as_vec() { - debug_assert_eq!(3, tup.len()); - $a = $a.$c(yaml_str!(tup[0]), yaml_opt_str!(tup[1]), yaml_str!(tup[2])); - } else { - panic!("Failed to convert YAML value to vec"); - } + if let Some(vec) = $v.as_vec() { + for ys in vec { + if let Some(tup) = ys.as_vec() { + debug_assert_eq!(3, tup.len()); + $a = $a.$c(yaml_str!(tup[0]), yaml_opt_str!(tup[1]), yaml_str!(tup[2])); + } else { + panic!("Failed to convert YAML value to vec"); } - } else { - panic!("Failed to convert YAML value to vec"); } - $a + } else { + panic!("Failed to convert YAML value to vec"); } - }; + $a + }}; } #[cfg(feature = "yaml")] macro_rules! yaml_vec_or_str { ($v:ident, $a:ident, $c:ident) => {{ - let maybe_vec = $v.as_vec(); - if let Some(vec) = maybe_vec { - for ys in vec { - if let Some(s) = ys.as_str() { - $a = $a.$c(s); - } else { - panic!("Failed to convert YAML value {:?} to a string", ys); - } - } - } else { - if let Some(s) = $v.as_str() { + let maybe_vec = $v.as_vec(); + if let Some(vec) = maybe_vec { + for ys in vec { + if let Some(s) = ys.as_str() { $a = $a.$c(s); } else { - panic!("Failed to convert YAML value {:?} to either a vec or string", $v); + panic!("Failed to convert YAML value {:?} to a string", ys); } } - $a + } else { + if let Some(s) = $v.as_str() { + $a = $a.$c(s); + } else { + panic!( + "Failed to convert YAML value {:?} to either a vec or string", + $v + ); + } } - }; + $a + }}; } #[cfg(feature = "yaml")] macro_rules! yaml_opt_str { ($v:expr) => {{ if $v.is_null() { - Some($v.as_str().unwrap_or_else(|| panic!("failed to convert YAML {:?} value to a string", $v))) + Some( + $v.as_str() + .unwrap_or_else(|| panic!("failed to convert YAML {:?} value to a string", $v)), + ) } else { None } @@ -76,7 +79,8 @@ macro_rules! yaml_opt_str { #[cfg(feature = "yaml")] macro_rules! yaml_str { ($v:expr) => {{ - $v.as_str().unwrap_or_else(|| panic!("failed to convert YAML {:?} value to a string", $v)) + $v.as_str() + .unwrap_or_else(|| panic!("failed to convert YAML {:?} value to a string", $v)) }}; } @@ -90,20 +94,28 @@ macro_rules! yaml_to_str { #[cfg(feature = "yaml")] macro_rules! yaml_to_bool { ($a:ident, $v:ident, $c:ident) => {{ - $a.$c($v.as_bool().unwrap_or_else(|| panic!("failed to convert YAML {:?} value to a string", $v))) + $a.$c($v + .as_bool() + .unwrap_or_else(|| panic!("failed to convert YAML {:?} value to a string", $v))) }}; } #[cfg(feature = "yaml")] macro_rules! yaml_to_u64 { ($a:ident, $v:ident, $c:ident) => {{ - $a.$c($v.as_i64().unwrap_or_else(|| panic!("failed to convert YAML {:?} value to a string", $v)) as u64) + $a.$c($v + .as_i64() + .unwrap_or_else(|| panic!("failed to convert YAML {:?} value to a string", $v)) + as u64) }}; } #[cfg(feature = "yaml")] macro_rules! yaml_to_usize { ($a:ident, $v:ident, $c:ident) => {{ - $a.$c($v.as_i64().unwrap_or_else(|| panic!("failed to convert YAML {:?} value to a string", $v)) as usize) + $a.$c($v + .as_i64() + .unwrap_or_else(|| panic!("failed to convert YAML {:?} value to a string", $v)) + as usize) }}; } diff --git a/src/args/matched_arg.rs b/src/args/matched_arg.rs index eeda2611ca9..681e5d2aa76 100644 --- a/src/args/matched_arg.rs +++ b/src/args/matched_arg.rs @@ -4,9 +4,12 @@ use std::ffi::OsString; #[doc(hidden)] #[derive(Debug, Clone)] pub struct MatchedArg { - #[doc(hidden)] pub occurs: u64, - #[doc(hidden)] pub indices: Vec, - #[doc(hidden)] pub vals: Vec, + #[doc(hidden)] + pub occurs: u64, + #[doc(hidden)] + pub indices: Vec, + #[doc(hidden)] + pub vals: Vec, } impl Default for MatchedArg { @@ -20,5 +23,7 @@ impl Default for MatchedArg { } impl MatchedArg { - pub fn new() -> Self { MatchedArg::default() } + pub fn new() -> Self { + MatchedArg::default() + } } diff --git a/src/args/mod.rs b/src/args/mod.rs index 21f9b850d5f..8f076ea5c29 100644 --- a/src/args/mod.rs +++ b/src/args/mod.rs @@ -10,12 +10,12 @@ pub use self::subcommand::SubCommand; #[macro_use] mod macros; -mod arg; pub mod any_arg; -mod arg_matches; -mod arg_matcher; -mod subcommand; +mod arg; mod arg_builder; -mod matched_arg; +mod arg_matcher; +mod arg_matches; mod group; +mod matched_arg; pub mod settings; +mod subcommand; diff --git a/src/args/settings.rs b/src/args/settings.rs index 7b0e0a26c7a..833a1eafefa 100644 --- a/src/args/settings.rs +++ b/src/args/settings.rs @@ -33,9 +33,11 @@ bitflags! { pub struct ArgFlags(Flags); impl ArgFlags { - pub fn new() -> Self { ArgFlags::default() } + pub fn new() -> Self { + ArgFlags::default() + } - impl_settings!{ArgSettings, + impl_settings! {ArgSettings, Required => Flags::REQUIRED, Multiple => Flags::MULTIPLE, EmptyValues => Flags::EMPTY_VALS, @@ -60,7 +62,9 @@ impl ArgFlags { } impl Default for ArgFlags { - fn default() -> Self { ArgFlags(Flags::EMPTY_VALS | Flags::DELIM_NOT_SET) } + fn default() -> Self { + ArgFlags(Flags::EMPTY_VALS | Flags::DELIM_NOT_SET) + } } /// Various settings that apply to arguments and may be set, unset, and checked via getter/setter @@ -110,8 +114,10 @@ pub enum ArgSettings { HiddenShortHelp, /// The argument should **not** be shown in long help text HiddenLongHelp, - #[doc(hidden)] RequiredUnlessAll, - #[doc(hidden)] ValueDelimiterNotSet, + #[doc(hidden)] + RequiredUnlessAll, + #[doc(hidden)] + ValueDelimiterNotSet, } impl FromStr for ArgSettings { diff --git a/src/args/subcommand.rs b/src/args/subcommand.rs index eebbf827aec..8b8049ea7c5 100644 --- a/src/args/subcommand.rs +++ b/src/args/subcommand.rs @@ -29,8 +29,10 @@ use ArgMatches; /// [arguments]: ./struct.Arg.html #[derive(Debug, Clone)] pub struct SubCommand<'a> { - #[doc(hidden)] pub name: String, - #[doc(hidden)] pub matches: ArgMatches<'a>, + #[doc(hidden)] + pub name: String, + #[doc(hidden)] + pub matches: ArgMatches<'a>, } impl<'a> SubCommand<'a> { @@ -46,7 +48,9 @@ impl<'a> SubCommand<'a> { /// SubCommand::with_name("config")) /// # ; /// ``` - pub fn with_name<'b>(name: &str) -> App<'a, 'b> { App::new(name) } + pub fn with_name<'b>(name: &str) -> App<'a, 'b> { + App::new(name) + } /// Creates a new instance of a subcommand from a YAML (.yml) document /// @@ -62,5 +66,7 @@ impl<'a> SubCommand<'a> { /// # } /// ``` #[cfg(feature = "yaml")] - pub fn from_yaml(yaml: &Yaml) -> App { App::from_yaml(yaml) } + pub fn from_yaml(yaml: &Yaml) -> App { + App::from_yaml(yaml) + } } diff --git a/src/completions/bash.rs b/src/completions/bash.rs index 37dfa66983f..b712a68b461 100644 --- a/src/completions/bash.rs +++ b/src/completions/bash.rs @@ -14,7 +14,9 @@ where } impl<'a, 'b> BashGen<'a, 'b> { - pub fn new(p: &'b Parser<'a, 'b>) -> Self { BashGen { p: p } } + pub fn new(p: &'b Parser<'a, 'b>) -> Self { + BashGen { p: p } + } pub fn generate_to(&self, buf: &mut W) { w!( @@ -68,7 +70,8 @@ complete -F _{name} -o bashdefault -o default {name} self.option_details_for_path(self.p.meta.bin_name.as_ref().unwrap()), subcmds = self.all_subcommands(), subcmd_details = self.subcommand_details() - ).as_bytes() + ) + .as_bytes() ); } diff --git a/src/completions/elvish.rs b/src/completions/elvish.rs index 9a5f21a380d..12be03d7322 100644 --- a/src/completions/elvish.rs +++ b/src/completions/elvish.rs @@ -13,16 +13,18 @@ where } impl<'a, 'b> ElvishGen<'a, 'b> { - pub fn new(p: &'b Parser<'a, 'b>) -> Self { ElvishGen { p: p } } + pub fn new(p: &'b Parser<'a, 'b>) -> Self { + ElvishGen { p: p } + } pub fn generate_to(&self, buf: &mut W) { let bin_name = self.p.meta.bin_name.as_ref().unwrap(); let mut names = vec![]; - let subcommands_cases = - generate_inner(self.p, "", &mut names); + let subcommands_cases = generate_inner(self.p, "", &mut names); - let result = format!(r#" + let result = format!( + r#" edit:completion:arg-completer[{bin_name}] = [@words]{{ fn spaces [n]{{ repeat $n ' ' | joins '' @@ -51,12 +53,14 @@ edit:completion:arg-completer[{bin_name}] = [@words]{{ } // Escape string inside single quotes -fn escape_string(string: &str) -> String { string.replace("'", "''") } +fn escape_string(string: &str) -> String { + string.replace("'", "''") +} -fn get_tooltip(help: Option<&str>, data: T) -> String { +fn get_tooltip(help: Option<&str>, data: T) -> String { match help { Some(help) => escape_string(help), - _ => data.to_string() + _ => data.to_string(), } } @@ -112,13 +116,11 @@ fn generate_inner<'a, 'b, 'p>( r" &'{}'= {{{} }}", - &command_name, - completions + &command_name, completions ); for subcommand in &p.subcommands { - let subcommand_subcommands_cases = - generate_inner(&subcommand.p, &command_name, names); + let subcommand_subcommands_cases = generate_inner(&subcommand.p, &command_name, names); subcommands_cases.push_str(&subcommand_subcommands_cases); } diff --git a/src/completions/fish.rs b/src/completions/fish.rs index c2c5a5e70b1..a2bf888e4b8 100644 --- a/src/completions/fish.rs +++ b/src/completions/fish.rs @@ -12,7 +12,9 @@ where } impl<'a, 'b> FishGen<'a, 'b> { - pub fn new(p: &'b Parser<'a, 'b>) -> Self { FishGen { p: p } } + pub fn new(p: &'b Parser<'a, 'b>) -> Self { + FishGen { p: p } + } pub fn generate_to(&self, buf: &mut W) { let command = self.p.meta.bin_name.as_ref().unwrap(); @@ -23,7 +25,9 @@ impl<'a, 'b> FishGen<'a, 'b> { } // Escape string inside single quotes -fn escape_string(string: &str) -> String { string.replace("\\", "\\\\").replace("'", "\\'") } +fn escape_string(string: &str) -> String { + string.replace("\\", "\\\\").replace("'", "\\'") +} fn gen_fish_inner(root_command: &str, comp_gen: &FishGen, subcommand: &str, buffer: &mut String) { debugln!("FishGen::gen_fish_inner;"); diff --git a/src/completions/macros.rs b/src/completions/macros.rs index 653c72c4863..3a69de5d745 100644 --- a/src/completions/macros.rs +++ b/src/completions/macros.rs @@ -24,5 +24,5 @@ macro_rules! get_zsh_arg_conflicts { } else { String::new() } - } + }; } diff --git a/src/completions/mod.rs b/src/completions/mod.rs index a3306d72a1e..99d40052807 100644 --- a/src/completions/mod.rs +++ b/src/completions/mod.rs @@ -1,23 +1,23 @@ #[macro_use] mod macros; mod bash; +mod elvish; mod fish; -mod zsh; mod powershell; -mod elvish; mod shell; +mod zsh; // Std use std::io::Write; // Internal -use app::parser::Parser; use self::bash::BashGen; +use self::elvish::ElvishGen; use self::fish::FishGen; -use self::zsh::ZshGen; use self::powershell::PowerShellGen; -use self::elvish::ElvishGen; pub use self::shell::Shell; +use self::zsh::ZshGen; +use app::parser::Parser; pub struct ComplGen<'a, 'b> where @@ -27,7 +27,9 @@ where } impl<'a, 'b> ComplGen<'a, 'b> { - pub fn new(p: &'b Parser<'a, 'b>) -> Self { ComplGen { p: p } } + pub fn new(p: &'b Parser<'a, 'b>) -> Self { + ComplGen { p: p } + } pub fn generate(&self, for_shell: Shell, buf: &mut W) { match for_shell { @@ -155,13 +157,13 @@ pub fn get_all_subcommand_paths(p: &Parser, first: bool) -> Vec { } for sc in &p.subcommands { let name = &*sc.p.meta.name; - let path = sc.p - .meta - .bin_name - .as_ref() - .unwrap() - .clone() - .replace(" ", "__"); + let path = + sc.p.meta + .bin_name + .as_ref() + .unwrap() + .clone() + .replace(" ", "__"); subcmds.push(path.clone()); if let Some(ref aliases) = sc.p.meta.aliases { for &(n, _) in aliases { @@ -169,7 +171,8 @@ pub fn get_all_subcommand_paths(p: &Parser, first: bool) -> Vec { } } } - for sc_v in p.subcommands + for sc_v in p + .subcommands .iter() .map(|s| get_all_subcommand_paths(&s.p, false)) { diff --git a/src/completions/powershell.rs b/src/completions/powershell.rs index 9fc77c72a7f..5fafd8d8d5b 100644 --- a/src/completions/powershell.rs +++ b/src/completions/powershell.rs @@ -13,16 +13,18 @@ where } impl<'a, 'b> PowerShellGen<'a, 'b> { - pub fn new(p: &'b Parser<'a, 'b>) -> Self { PowerShellGen { p: p } } + pub fn new(p: &'b Parser<'a, 'b>) -> Self { + PowerShellGen { p: p } + } pub fn generate_to(&self, buf: &mut W) { let bin_name = self.p.meta.bin_name.as_ref().unwrap(); let mut names = vec![]; - let subcommands_cases = - generate_inner(self.p, "", &mut names); + let subcommands_cases = generate_inner(self.p, "", &mut names); - let result = format!(r#" + let result = format!( + r#" using namespace System.Management.Automation using namespace System.Management.Automation.Language @@ -58,12 +60,14 @@ Register-ArgumentCompleter -Native -CommandName '{bin_name}' -ScriptBlock {{ } // Escape string inside single quotes -fn escape_string(string: &str) -> String { string.replace("'", "''") } +fn escape_string(string: &str) -> String { + string.replace("'", "''") +} -fn get_tooltip(help: Option<&str>, data: T) -> String { +fn get_tooltip(help: Option<&str>, data: T) -> String { match help { Some(help) => escape_string(help), - _ => data.to_string() + _ => data.to_string(), } } @@ -86,14 +90,24 @@ fn generate_inner<'a, 'b, 'p>( if let Some(data) = option.s.short { let tooltip = get_tooltip(option.b.help, data); completions.push_str(&preamble); - completions.push_str(format!("'-{}', '{}', {}, '{}')", - data, data, "[CompletionResultType]::ParameterName", tooltip).as_str()); + completions.push_str( + format!( + "'-{}', '{}', {}, '{}')", + data, data, "[CompletionResultType]::ParameterName", tooltip + ) + .as_str(), + ); } if let Some(data) = option.s.long { let tooltip = get_tooltip(option.b.help, data); completions.push_str(&preamble); - completions.push_str(format!("'--{}', '{}', {}, '{}')", - data, data, "[CompletionResultType]::ParameterName", tooltip).as_str()); + completions.push_str( + format!( + "'--{}', '{}', {}, '{}')", + data, data, "[CompletionResultType]::ParameterName", tooltip + ) + .as_str(), + ); } } @@ -101,14 +115,24 @@ fn generate_inner<'a, 'b, 'p>( if let Some(data) = flag.s.short { let tooltip = get_tooltip(flag.b.help, data); completions.push_str(&preamble); - completions.push_str(format!("'-{}', '{}', {}, '{}')", - data, data, "[CompletionResultType]::ParameterName", tooltip).as_str()); + completions.push_str( + format!( + "'-{}', '{}', {}, '{}')", + data, data, "[CompletionResultType]::ParameterName", tooltip + ) + .as_str(), + ); } if let Some(data) = flag.s.long { let tooltip = get_tooltip(flag.b.help, data); completions.push_str(&preamble); - completions.push_str(format!("'--{}', '{}', {}, '{}')", - data, data, "[CompletionResultType]::ParameterName", tooltip).as_str()); + completions.push_str( + format!( + "'--{}', '{}', {}, '{}')", + data, data, "[CompletionResultType]::ParameterName", tooltip + ) + .as_str(), + ); } } @@ -116,8 +140,13 @@ fn generate_inner<'a, 'b, 'p>( let data = &subcommand.p.meta.name; let tooltip = get_tooltip(subcommand.p.meta.about, data); completions.push_str(&preamble); - completions.push_str(format!("'{}', '{}', {}, '{}')", - data, data, "[CompletionResultType]::ParameterValue", tooltip).as_str()); + completions.push_str( + format!( + "'{}', '{}', {}, '{}')", + data, data, "[CompletionResultType]::ParameterValue", tooltip + ) + .as_str(), + ); } let mut subcommands_cases = format!( @@ -125,13 +154,11 @@ fn generate_inner<'a, 'b, 'p>( '{}' {{{} break }}", - &command_name, - completions + &command_name, completions ); for subcommand in &p.subcommands { - let subcommand_subcommands_cases = - generate_inner(&subcommand.p, &command_name, names); + let subcommand_subcommands_cases = generate_inner(&subcommand.p, &command_name, names); subcommands_cases.push_str(&subcommand_subcommands_cases); } diff --git a/src/completions/shell.rs b/src/completions/shell.rs index 19aab8694d0..80999e6c03d 100644 --- a/src/completions/shell.rs +++ b/src/completions/shell.rs @@ -1,7 +1,7 @@ #[allow(deprecated, unused_imports)] use std::ascii::AsciiExt; -use std::str::FromStr; use std::fmt; +use std::str::FromStr; /// Describes which shell to produce a completions file for #[cfg_attr(feature = "lints", allow(enum_variant_names))] @@ -21,7 +21,9 @@ pub enum Shell { impl Shell { /// A list of possible variants in `&'static str` form - pub fn variants() -> [&'static str; 5] { ["zsh", "bash", "fish", "powershell", "elvish"] } + pub fn variants() -> [&'static str; 5] { + ["zsh", "bash", "fish", "powershell", "elvish"] + } } impl FromStr for Shell { @@ -34,7 +36,9 @@ impl FromStr for Shell { "BASH" | _ if s.eq_ignore_ascii_case("bash") => Ok(Shell::Bash), "POWERSHELL" | _ if s.eq_ignore_ascii_case("powershell") => Ok(Shell::PowerShell), "ELVISH" | _ if s.eq_ignore_ascii_case("elvish") => Ok(Shell::Elvish), - _ => Err(String::from("[valid values: bash, fish, zsh, powershell, elvish]")), + _ => Err(String::from( + "[valid values: bash, fish, zsh, powershell, elvish]", + )), } } } diff --git a/src/completions/zsh.rs b/src/completions/zsh.rs index 5d23fd28422..14cf2b6efe2 100644 --- a/src/completions/zsh.rs +++ b/src/completions/zsh.rs @@ -1,11 +1,11 @@ // Std -use std::io::Write; #[allow(deprecated, unused_imports)] use std::ascii::AsciiExt; +use std::io::Write; // Internal -use app::App; use app::parser::Parser; +use app::App; use args::{AnyArg, ArgSettings}; use completions; use INTERNAL_ERROR_MSG; @@ -56,7 +56,8 @@ _{name} \"$@\"", initial_args = get_args_of(self.p), subcommands = get_subcommands_of(self.p), subcommand_details = subcommand_details(self.p) - ).as_bytes() + ) + .as_bytes() ); } } @@ -91,9 +92,8 @@ _{name} \"$@\"", fn subcommand_details(p: &Parser) -> String { debugln!("ZshGen::subcommand_details;"); // First we do ourself - let mut ret = vec![ - format!( - "\ + let mut ret = vec![format!( + "\ (( $+functions[_{bin_name_underscore}_commands] )) || _{bin_name_underscore}_commands() {{ local commands; commands=( @@ -101,11 +101,10 @@ _{bin_name_underscore}_commands() {{ ) _describe -t commands '{bin_name} commands' commands \"$@\" }}", - bin_name_underscore = p.meta.bin_name.as_ref().unwrap().replace(" ", "__"), - bin_name = p.meta.bin_name.as_ref().unwrap(), - subcommands_and_args = subcommands_of(p) - ), - ]; + bin_name_underscore = p.meta.bin_name.as_ref().unwrap().replace(" ", "__"), + bin_name = p.meta.bin_name.as_ref().unwrap(), + subcommands_and_args = subcommands_of(p) + )]; // Next we start looping through all the children, grandchildren, etc. let mut all_subcommands = completions::all_subcommands(p); @@ -150,12 +149,12 @@ fn subcommands_of(p: &Parser) -> String { let s = format!( "\"{name}:{help}\" \\", name = n, - help = sc.p - .meta - .about - .unwrap_or("") - .replace("[", "\\[") - .replace("]", "\\]") + help = + sc.p.meta + .about + .unwrap_or("") + .replace("[", "\\[") + .replace("]", "\\]") ); if !s.is_empty() { ret.push(s); @@ -164,10 +163,7 @@ fn subcommands_of(p: &Parser) -> String { // The subcommands for sc in p.subcommands() { - debugln!( - "ZshGen::subcommands_of:iter: subcommand={}", - sc.p.meta.name - ); + debugln!("ZshGen::subcommands_of:iter: subcommand={}", sc.p.meta.name); add_sc(sc, &sc.p.meta.name, &mut ret); if let Some(ref v) = sc.p.meta.aliases { for alias in v.iter().filter(|&&(_, vis)| vis).map(|&(n, _)| n) { @@ -360,8 +356,14 @@ fn write_opts_of(p: &Parser) -> String { "" }; let pv = if let Some(pv_vec) = o.possible_vals() { - format!(": :({})", pv_vec.iter().map( - |v| escape_value(*v)).collect::>().join(" ")) + format!( + ": :({})", + pv_vec + .iter() + .map(|v| escape_value(*v)) + .collect::>() + .join(" ") + ) } else { String::new() }; @@ -451,16 +453,27 @@ fn write_positionals_of(p: &Parser) -> String { debugln!("write_positionals_of:iter: arg={}", arg.b.name); let a = format!( "'{optional}:{name}{help}:{action}' \\", - optional = if !arg.b.is_set(ArgSettings::Required) { ":" } else { "" }, + optional = if !arg.b.is_set(ArgSettings::Required) { + ":" + } else { + "" + }, name = arg.b.name, - help = arg.b + help = arg + .b .help .map_or("".to_owned(), |v| " -- ".to_owned() + v) .replace("[", "\\[") .replace("]", "\\]"), action = arg.possible_vals().map_or("_files".to_owned(), |values| { - format!("({})", - values.iter().map(|v| escape_value(*v)).collect::>().join(" ")) + format!( + "({})", + values + .iter() + .map(|v| escape_value(*v)) + .collect::>() + .join(" ") + ) }) ); diff --git a/src/errors.rs b/src/errors.rs index c6087c00a22..1f86720fd5b 100644 --- a/src/errors.rs +++ b/src/errors.rs @@ -403,7 +403,9 @@ impl Error { } #[doc(hidden)] - pub fn write_to(&self, w: &mut W) -> io::Result<()> { write!(w, "{}", self.message) } + pub fn write_to(&self, w: &mut W) -> io::Result<()> { + write!(w, "{}", self.message) + } #[doc(hidden)] pub fn argument_conflict( @@ -634,7 +636,6 @@ impl Error { } } - #[doc(hidden)] pub fn invalid_utf8(usage: U, color: ColorWhen) -> Self where @@ -721,8 +722,7 @@ impl Error { } #[doc(hidden)] - pub fn value_validation(arg: Option<&AnyArg>, err: String, color: ColorWhen) -> Self - { + pub fn value_validation(arg: Option<&AnyArg>, err: String, color: ColorWhen) -> Self { let c = Colorizer::new(ColorizerOption { use_stderr: true, when: color, @@ -894,15 +894,21 @@ impl Error { } impl StdError for Error { - fn description(&self) -> &str { &*self.message } + fn description(&self) -> &str { + &*self.message + } } impl Display for Error { - fn fmt(&self, f: &mut std_fmt::Formatter) -> std_fmt::Result { writeln!(f, "{}", self.message) } + fn fmt(&self, f: &mut std_fmt::Formatter) -> std_fmt::Result { + writeln!(f, "{}", self.message) + } } impl From for Error { - fn from(e: io::Error) -> Self { Error::with_description(e.description(), ErrorKind::Io) } + fn from(e: io::Error) -> Self { + Error::with_description(e.description(), ErrorKind::Io) + } } impl From for Error { diff --git a/src/fmt.rs b/src/fmt.rs index 108a6354b95..fa8b633452e 100644 --- a/src/fmt.rs +++ b/src/fmt.rs @@ -6,8 +6,8 @@ use ansi_term::Colour::{Green, Red, Yellow}; #[cfg(feature = "color")] use atty; -use std::fmt; use std::env; +use std::fmt; #[doc(hidden)] #[derive(Debug, Copy, Clone, PartialEq)] @@ -34,7 +34,9 @@ pub fn is_a_tty(_: bool) -> bool { false } -pub fn is_term_dumb() -> bool { env::var("TERM").ok() == Some(String::from("dumb")) } +pub fn is_term_dumb() -> bool { + env::var("TERM").ok() == Some(String::from("dumb")) +} #[doc(hidden)] pub struct ColorizerOption { @@ -66,7 +68,7 @@ impl Colorizer { ColorWhen::Auto if is_a_tty && !is_term_dumb => ColorWhen::Auto, ColorWhen::Auto => ColorWhen::Never, when => when, - } + }, } } @@ -152,22 +154,25 @@ impl Format { } } - #[cfg(all(feature = "color", not(target_os = "windows")))] impl> fmt::Display for Format { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", &self.format()) } + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}", &self.format()) + } } #[cfg(any(not(feature = "color"), target_os = "windows"))] impl fmt::Display for Format { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", &self.format()) } + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}", &self.format()) + } } #[cfg(all(test, feature = "color", not(target_os = "windows")))] mod test { + use super::Format; use ansi_term::ANSIString; use ansi_term::Colour::{Green, Red, Yellow}; - use super::Format; #[test] fn colored_output() { diff --git a/src/lib.rs b/src/lib.rs index ffd7142a943..98fcaee23c0 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -518,12 +518,21 @@ #![crate_type = "lib"] #![doc(html_root_url = "https://docs.rs/clap/2.33.0")] -#![deny(missing_docs, missing_debug_implementations, missing_copy_implementations, trivial_casts, - unused_import_braces, unused_allocation)] +#![deny( + missing_docs, + missing_debug_implementations, + missing_copy_implementations, + trivial_casts, + unused_import_braces, + unused_allocation +)] // Lints we'd like to deny but are currently failing for upstream crates // unused_qualifications (bitflags, clippy) // trivial_numeric_casts (bitflags) -#![cfg_attr(not(any(feature = "lints", feature = "nightly")), forbid(unstable_features))] +#![cfg_attr( + not(any(feature = "lints", feature = "nightly")), + forbid(unstable_features) +)] #![cfg_attr(feature = "lints", feature(plugin))] #![cfg_attr(feature = "lints", plugin(clippy))] // Need to disable deny(warnings) while deprecations are active @@ -549,26 +558,26 @@ extern crate vec_map; #[cfg(feature = "yaml")] extern crate yaml_rust; -#[cfg(feature = "yaml")] -pub use yaml_rust::YamlLoader; -pub use args::{Arg, ArgGroup, ArgMatches, ArgSettings, OsValues, SubCommand, Values}; pub use app::{App, AppSettings}; -pub use fmt::Format; -pub use errors::{Error, ErrorKind, Result}; +pub use args::{Arg, ArgGroup, ArgMatches, ArgSettings, OsValues, SubCommand, Values}; pub use completions::Shell; +pub use errors::{Error, ErrorKind, Result}; +pub use fmt::Format; +#[cfg(feature = "yaml")] +pub use yaml_rust::YamlLoader; #[macro_use] mod macros; mod app; mod args; -mod usage_parser; -mod fmt; -mod suggestions; +mod completions; mod errors; +mod fmt; +mod map; mod osstringext; mod strext; -mod completions; -mod map; +mod suggestions; +mod usage_parser; const INTERNAL_ERROR_MSG: &'static str = "Fatal internal error. Please consider filing a bug \ report at https://github.com/clap-rs/clap/issues"; @@ -582,7 +591,9 @@ mod derive { /// @TODO @release @docs pub trait ClapApp: IntoApp + FromArgMatches + Sized { /// @TODO @release @docs - fn parse() -> Self { Self::from_argmatches(Self::into_app().get_matches()) } + fn parse() -> Self { + Self::from_argmatches(Self::into_app().get_matches()) + } /// @TODO @release @docs fn parse_from(argv: I) -> Self @@ -598,7 +609,6 @@ mod derive { Self::try_from_argmatches(Self::into_app().get_matches_safe()?) } - /// @TODO @release @docs fn try_parse_from(argv: I) -> Result where diff --git a/src/macros.rs b/src/macros.rs index 8198e19badc..186cfc833c6 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -26,9 +26,9 @@ #[cfg(feature = "yaml")] #[macro_export] macro_rules! load_yaml { - ($yml:expr) => ( + ($yml:expr) => { &::clap::YamlLoader::load_from_str(include_str!($yml)).expect("failed to load YAML file")[0] - ); + }; } /// Convenience macro getting a typed value `T` where `T` implements [`std::str::FromStr`] from an @@ -66,9 +66,10 @@ macro_rules! value_t { if let Some(v) = $m.value_of($v) { match v.parse::<$t>() { Ok(val) => Ok(val), - Err(_) => - Err(::clap::Error::value_validation_auto( - format!("The argument '{}' isn't a valid value", v))), + Err(_) => Err(::clap::Error::value_validation_auto(format!( + "The argument '{}' isn't a valid value", + v + ))), } } else { Err(::clap::Error::argument_not_found_auto($v)) @@ -111,9 +112,11 @@ macro_rules! value_t_or_exit { if let Some(v) = $m.value_of($v) { match v.parse::<$t>() { Ok(val) => val, - Err(_) => - ::clap::Error::value_validation_auto( - format!("The argument '{}' isn't a valid value", v)).exit(), + Err(_) => ::clap::Error::value_validation_auto(format!( + "The argument '{}' isn't a valid value", + v + )) + .exit(), } } else { ::clap::Error::argument_not_found_auto($v).exit() @@ -163,9 +166,11 @@ macro_rules! values_t { match pv.parse::<$t>() { Ok(rv) => tmp.push(rv), Err(..) => { - err = Some(::clap::Error::value_validation_auto( - format!("The argument '{}' isn't a valid value", pv))); - break + err = Some(::clap::Error::value_validation_auto(format!( + "The argument '{}' isn't a valid value", + pv + ))); + break; } } } @@ -218,10 +223,15 @@ macro_rules! values_t_or_exit { }; ($m:ident.values_of($v:expr), $t:ty) => { if let Some(vals) = $m.values_of($v) { - vals.map(|v| v.parse::<$t>().unwrap_or_else(|_|{ - ::clap::Error::value_validation_auto( - format!("One or more arguments aren't valid values")).exit() - })).collect::>() + vals.map(|v| { + v.parse::<$t>().unwrap_or_else(|_| { + ::clap::Error::value_validation_auto(format!( + "One or more arguments aren't valid values" + )) + .exit() + }) + }) + .collect::>() } else { ::clap::Error::argument_not_found_auto($v).exit() } @@ -456,11 +466,13 @@ macro_rules! crate_version { macro_rules! crate_authors { ($sep:expr) => {{ use std::ops::Deref; - use std::sync::{ONCE_INIT, Once}; + use std::sync::{Once, ONCE_INIT}; #[allow(missing_copy_implementations)] #[allow(dead_code)] - struct CargoAuthors { __private_field: () }; + struct CargoAuthors { + __private_field: (), + }; impl Deref for CargoAuthors { type Target = str; @@ -481,7 +493,9 @@ macro_rules! crate_authors { } } - &*CargoAuthors { __private_field: () } + &*CargoAuthors { + __private_field: (), + } }}; () => { env!("CARGO_PKG_AUTHORS") @@ -855,16 +869,16 @@ mod debug_macros { #[cfg_attr(not(feature = "debug"), macro_use)] mod debug_macros { macro_rules! debugln { - ($fmt:expr) => (); - ($fmt:expr, $($arg:tt)*) => (); + ($fmt:expr) => {}; + ($fmt:expr, $($arg:tt)*) => {}; } macro_rules! sdebugln { - ($fmt:expr) => (); - ($fmt:expr, $($arg:tt)*) => (); + ($fmt:expr) => {}; + ($fmt:expr, $($arg:tt)*) => {}; } macro_rules! debug { - ($fmt:expr) => (); - ($fmt:expr, $($arg:tt)*) => (); + ($fmt:expr) => {}; + ($fmt:expr, $($arg:tt)*) => {}; } } @@ -873,12 +887,12 @@ mod debug_macros { // src/args/arg_builder/*.rs // src/app/mod.rs macro_rules! write_nspaces { - ($dst:expr, $num:expr) => ({ + ($dst:expr, $num:expr) => {{ debugln!("write_spaces!: num={}", $num); for _ in 0..$num { $dst.write_all(b" ")?; } - }) + }}; } // convenience macro for remove an item from a vec @@ -951,24 +965,23 @@ macro_rules! find_from { // }}; //} - macro_rules! find_any_by_name { - ($p:expr, $name:expr) => { - { - fn as_trait_obj<'a, 'b, T: AnyArg<'a, 'b>>(x: &T) -> &AnyArg<'a, 'b> { x } - find_by_name!($p, $name, flags, iter).map(as_trait_obj).or( - find_by_name!($p, $name, opts, iter).map(as_trait_obj).or( - find_by_name!($p, $name, positionals, values).map(as_trait_obj) - ) - ) + ($p:expr, $name:expr) => {{ + fn as_trait_obj<'a, 'b, T: AnyArg<'a, 'b>>(x: &T) -> &AnyArg<'a, 'b> { + x } - } + find_by_name!($p, $name, flags, iter) + .map(as_trait_obj) + .or(find_by_name!($p, $name, opts, iter) + .map(as_trait_obj) + .or(find_by_name!($p, $name, positionals, values).map(as_trait_obj))) + }}; } // Finds an arg by name macro_rules! find_by_name { ($p:expr, $name:expr, $what:ident, $how:ident) => { $p.$what.$how().find(|o| o.b.name == $name) - } + }; } // Finds an option including if it's aliased @@ -992,59 +1005,59 @@ macro_rules! find_flag_by_long { macro_rules! _find_by_long { ($_self:ident, $long:expr, $what:ident) => {{ - $_self.$what + $_self + .$what .iter() .filter(|a| a.s.long.is_some()) .find(|a| { - a.s.long.unwrap() == $long || - (a.s.aliases.is_some() && - a.s - .aliases - .as_ref() - .unwrap() - .iter() - .any(|&(alias, _)| alias == $long)) + a.s.long.unwrap() == $long + || (a.s.aliases.is_some() + && a.s + .aliases + .as_ref() + .unwrap() + .iter() + .any(|&(alias, _)| alias == $long)) }) - }} + }}; } // Finds an option macro_rules! find_opt_by_short { ($_self:ident, $short:expr) => {{ _find_by_short!($_self, $short, opts) - }} + }}; } macro_rules! find_flag_by_short { ($_self:ident, $short:expr) => {{ _find_by_short!($_self, $short, flags) - }} + }}; } macro_rules! _find_by_short { ($_self:ident, $short:expr, $what:ident) => {{ - $_self.$what + $_self + .$what .iter() .filter(|a| a.s.short.is_some()) .find(|a| a.s.short.unwrap() == $short) - }} + }}; } macro_rules! find_subcmd { ($_self:expr, $sc:expr) => {{ - $_self.subcommands - .iter() - .find(|s| { - &*s.p.meta.name == $sc || - (s.p.meta.aliases.is_some() && - s.p - .meta - .aliases - .as_ref() - .unwrap() - .iter() - .any(|&(n, _)| n == $sc)) - }) + $_self.subcommands.iter().find(|s| { + &*s.p.meta.name == $sc + || (s.p.meta.aliases.is_some() + && s.p + .meta + .aliases + .as_ref() + .unwrap() + .iter() + .any(|&(n, _)| n == $sc)) + }) }}; } @@ -1054,7 +1067,6 @@ macro_rules! shorts { }}; } - macro_rules! longs { ($_self:ident) => {{ _shorts_longs!($_self, long) @@ -1063,13 +1075,18 @@ macro_rules! longs { macro_rules! _shorts_longs { ($_self:ident, $what:ident) => {{ - $_self.flags - .iter() - .filter(|f| f.s.$what.is_some()) - .map(|f| f.s.$what.as_ref().unwrap()) - .chain($_self.opts.iter() - .filter(|o| o.s.$what.is_some()) - .map(|o| o.s.$what.as_ref().unwrap())) + $_self + .flags + .iter() + .filter(|f| f.s.$what.is_some()) + .map(|f| f.s.$what.as_ref().unwrap()) + .chain( + $_self + .opts + .iter() + .filter(|o| o.s.$what.is_some()) + .map(|o| o.s.$what.as_ref().unwrap()), + ) }}; } @@ -1087,22 +1104,21 @@ macro_rules! sc_names { macro_rules! _names { (@args $_self:ident) => {{ - $_self.flags + $_self.flags.iter().map(|f| &*f.b.name).chain( + $_self + .opts .iter() - .map(|f| &*f.b.name) - .chain($_self.opts.iter() - .map(|o| &*o.b.name) - .chain($_self.positionals.values() - .map(|p| &*p.b.name))) + .map(|o| &*o.b.name) + .chain($_self.positionals.values().map(|p| &*p.b.name)), + ) }}; (@sc $_self:ident) => {{ - $_self.subcommands - .iter() - .map(|s| &*s.p.meta.name) - .chain($_self.subcommands - .iter() - .filter(|s| s.p.meta.aliases.is_some()) - .flat_map(|s| s.p.meta.aliases.as_ref().unwrap().iter().map(|&(n, _)| n))) - - }} + $_self.subcommands.iter().map(|s| &*s.p.meta.name).chain( + $_self + .subcommands + .iter() + .filter(|s| s.p.meta.aliases.is_some()) + .flat_map(|s| s.p.meta.aliases.as_ref().unwrap().iter().map(|&(n, _)| n)), + ) + }}; } diff --git a/src/map.rs b/src/map.rs index 063a8602883..13497834d42 100644 --- a/src/map.rs +++ b/src/map.rs @@ -6,8 +6,8 @@ pub use self::vec_map::{Values, VecMap}; #[cfg(not(feature = "vec_map"))] mod vec_map { - use std::collections::BTreeMap; use std::collections::btree_map; + use std::collections::BTreeMap; use std::fmt::{self, Debug, Formatter}; #[derive(Clone, Default, Debug)] @@ -22,15 +22,21 @@ mod vec_map { } } - pub fn len(&self) -> usize { self.inner.len() } + pub fn len(&self) -> usize { + self.inner.len() + } - pub fn is_empty(&self) -> bool { self.inner.is_empty() } + pub fn is_empty(&self) -> bool { + self.inner.is_empty() + } pub fn insert(&mut self, key: usize, value: V) -> Option { self.inner.insert(key, value) } - pub fn values(&self) -> Values { self.inner.values() } + pub fn values(&self) -> Values { + self.inner.values() + } pub fn iter(&self) -> Iter { Iter { @@ -38,11 +44,17 @@ mod vec_map { } } - pub fn contains_key(&self, key: usize) -> bool { self.inner.contains_key(&key) } + pub fn contains_key(&self, key: usize) -> bool { + self.inner.contains_key(&key) + } - pub fn entry(&mut self, key: usize) -> Entry { self.inner.entry(key) } + pub fn entry(&mut self, key: usize) -> Entry { + self.inner.entry(key) + } - pub fn get(&self, key: usize) -> Option<&V> { self.inner.get(&key) } + pub fn get(&self, key: usize) -> Option<&V> { + self.inner.get(&key) + } } pub type Values<'a, V> = btree_map::Values<'a, usize, V>; @@ -63,7 +75,9 @@ mod vec_map { impl<'a, V: 'a> Iterator for Iter<'a, V> { type Item = (usize, &'a V); - fn next(&mut self) -> Option { self.inner.next().map(|(k, v)| (*k, v)) } + fn next(&mut self) -> Option { + self.inner.next().map(|(k, v)| (*k, v)) + } } impl<'a, V: 'a> DoubleEndedIterator for Iter<'a, V> { diff --git a/src/osstringext.rs b/src/osstringext.rs index 061c01ddd40..50b0970fc03 100644 --- a/src/osstringext.rs +++ b/src/osstringext.rs @@ -1,8 +1,8 @@ -#[cfg(any(target_os = "windows", target_arch = "wasm32"))] -use INVALID_UTF8; use std::ffi::OsStr; #[cfg(not(any(target_os = "windows", target_arch = "wasm32")))] use std::os::unix::ffi::OsStrExt; +#[cfg(any(target_os = "windows", target_arch = "wasm32"))] +use INVALID_UTF8; #[cfg(any(target_os = "windows", target_arch = "wasm32"))] pub trait OsStrExt3 { diff --git a/src/suggestions.rs b/src/suggestions.rs index 06071d216e0..1157b26da41 100644 --- a/src/suggestions.rs +++ b/src/suggestions.rs @@ -57,7 +57,7 @@ where "\n\tDid you mean {}{}?", Format::Good("--"), Format::Good(candidate) - ); + ); return (suffix, Some(candidate)); } @@ -73,11 +73,11 @@ where let candidate = match did_you_mean(arg, opts) { Some(candidate) => candidate, - None => return None + None => return None, }; let score = match args_rest.iter().position(|x| *x == subcommand.get_name()) { Some(score) => score, - None => return None + None => return None, }; let suffix = format!( diff --git a/src/usage_parser.rs b/src/usage_parser.rs index f6d5ac60696..0a383eb414b 100644 --- a/src/usage_parser.rs +++ b/src/usage_parser.rs @@ -1,8 +1,8 @@ // Internal -use INTERNAL_ERROR_MSG; -use args::Arg; use args::settings::ArgSettings; +use args::Arg; use map::VecMap; +use INTERNAL_ERROR_MSG; #[derive(PartialEq, Debug)] enum UsageToken { @@ -76,10 +76,13 @@ impl<'a> UsageParser<'a> { fn name(&mut self, arg: &mut Arg<'a, 'a>) { debugln!("UsageParser::name;"); - if *self.usage + if *self + .usage .as_bytes() .get(self.pos) - .expect(INTERNAL_ERROR_MSG) == b'<' && !self.explicit_name_set + .expect(INTERNAL_ERROR_MSG) + == b'<' + && !self.explicit_name_set { arg.setb(ArgSettings::Required); } @@ -124,10 +127,12 @@ impl<'a> UsageParser<'a> { fn short_or_long(&mut self, arg: &mut Arg<'a, 'a>) { debugln!("UsageParser::short_or_long;"); self.pos += 1; - if *self.usage + if *self + .usage .as_bytes() .get(self.pos) - .expect(INTERNAL_ERROR_MSG) == b'-' + .expect(INTERNAL_ERROR_MSG) + == b'-' { self.pos += 1; self.long(arg); @@ -206,10 +211,14 @@ impl<'a> UsageParser<'a> { } #[inline] -fn name_end(b: u8) -> bool { b != b']' && b != b'>' } +fn name_end(b: u8) -> bool { + b != b']' && b != b'>' +} #[inline] -fn token(b: u8) -> bool { b != b'\'' && b != b'.' && b != b'<' && b != b'[' && b != b'-' } +fn token(b: u8) -> bool { + b != b'\'' && b != b'.' && b != b'<' && b != b'[' && b != b'-' +} #[inline] fn long_end(b: u8) -> bool { @@ -217,7 +226,9 @@ fn long_end(b: u8) -> bool { } #[inline] -fn help_start(b: u8) -> bool { b != b'\'' } +fn help_start(b: u8) -> bool { + b != b'\'' +} #[cfg(test)] mod test { diff --git a/tests/app_settings.rs b/tests/app_settings.rs index 3d72a3b7bf6..6dd2c6ef35f 100644 --- a/tests/app_settings.rs +++ b/tests/app_settings.rs @@ -1,7 +1,7 @@ extern crate clap; extern crate regex; -use clap::{App, Arg, SubCommand, AppSettings, ErrorKind}; +use clap::{App, AppSettings, Arg, ErrorKind, SubCommand}; include!("../clap-test.rs"); @@ -77,9 +77,7 @@ ARGS: fn sub_command_negate_required() { App::new("sub_command_negate") .setting(AppSettings::SubcommandsNegateReqs) - .arg(Arg::with_name("test") - .required(true) - .index(1)) + .arg(Arg::with_name("test").required(true).index(1)) .subcommand(SubCommand::with_name("sub1")) .get_matches_from(vec!["myprog", "sub1"]); } @@ -98,9 +96,7 @@ fn global_version() { fn sub_command_negate_required_2() { let result = App::new("sub_command_negate") .setting(AppSettings::SubcommandsNegateReqs) - .arg(Arg::with_name("test") - .required(true) - .index(1)) + .arg(Arg::with_name("test").required(true).index(1)) .subcommand(SubCommand::with_name("sub1")) .get_matches_from_safe(vec![""]); assert!(result.is_err()); @@ -123,8 +119,7 @@ fn sub_command_required() { fn arg_required_else_help() { let result = App::new("arg_required") .setting(AppSettings::ArgRequiredElseHelp) - .arg(Arg::with_name("test") - .index(1)) + .arg(Arg::with_name("test").index(1)) .get_matches_from_safe(vec![""]); assert!(result.is_err()); let err = result.err().unwrap(); @@ -135,8 +130,7 @@ fn arg_required_else_help() { fn arg_required_else_help_over_reqs() { let result = App::new("arg_required") .setting(AppSettings::ArgRequiredElseHelp) - .arg(Arg::with_name("test") - .index(1).required(true)) + .arg(Arg::with_name("test").index(1).required(true)) .get_matches_from_safe(vec![""]); assert!(result.is_err()); let err = result.err().unwrap(); @@ -150,9 +144,7 @@ fn infer_subcommands_fail_no_args() { .setting(AppSettings::InferSubcommands) .subcommand(SubCommand::with_name("test")) .subcommand(SubCommand::with_name("temp")) - .get_matches_from_safe(vec![ - "prog", "te" - ]); + .get_matches_from_safe(vec!["prog", "te"]); assert!(m.is_err(), "{:#?}", m.unwrap()); assert_eq!(m.unwrap_err().kind, ErrorKind::UnrecognizedSubcommand); } @@ -164,9 +156,7 @@ fn infer_subcommands_fail_no_args() { .setting(AppSettings::InferSubcommands) .subcommand(SubCommand::with_name("test")) .subcommand(SubCommand::with_name("temp")) - .get_matches_from_safe(vec![ - "prog", "te" - ]); + .get_matches_from_safe(vec!["prog", "te"]); assert!(m.is_err(), "{:#?}", m.unwrap()); assert_eq!(m.unwrap_err().kind, ErrorKind::InvalidSubcommand); } @@ -178,9 +168,7 @@ fn infer_subcommands_fail_with_args() { .arg(Arg::with_name("some")) .subcommand(SubCommand::with_name("test")) .subcommand(SubCommand::with_name("temp")) - .get_matches_from_safe(vec![ - "prog", "t" - ]); + .get_matches_from_safe(vec!["prog", "t"]); assert!(m.is_ok(), "{:?}", m.unwrap_err().kind); assert_eq!(m.unwrap().value_of("some"), Some("t")); } @@ -192,9 +180,7 @@ fn infer_subcommands_fail_with_args2() { .arg(Arg::with_name("some")) .subcommand(SubCommand::with_name("test")) .subcommand(SubCommand::with_name("temp")) - .get_matches_from_safe(vec![ - "prog", "te" - ]); + .get_matches_from_safe(vec!["prog", "te"]); assert!(m.is_ok(), "{:?}", m.unwrap_err().kind); assert_eq!(m.unwrap().value_of("some"), Some("te")); } @@ -204,9 +190,7 @@ fn infer_subcommands_pass() { let m = App::new("prog") .setting(AppSettings::InferSubcommands) .subcommand(SubCommand::with_name("test")) - .get_matches_from(vec![ - "prog", "te" - ]); + .get_matches_from(vec!["prog", "te"]); assert_eq!(m.subcommand_name(), Some("test")); } @@ -216,9 +200,7 @@ fn infer_subcommands_pass_close() { .setting(AppSettings::InferSubcommands) .subcommand(SubCommand::with_name("test")) .subcommand(SubCommand::with_name("temp")) - .get_matches_from(vec![ - "prog", "tes" - ]); + .get_matches_from(vec!["prog", "tes"]); assert_eq!(m.subcommand_name(), Some("test")); } @@ -229,9 +211,7 @@ fn infer_subcommands_pass_exact_match() { .subcommand(SubCommand::with_name("test")) .subcommand(SubCommand::with_name("testa")) .subcommand(SubCommand::with_name("testb")) - .get_matches_from(vec![ - "prog", "test" - ]); + .get_matches_from(vec!["prog", "test"]); assert_eq!(m.subcommand_name(), Some("test")); } @@ -242,9 +222,7 @@ fn infer_subcommands_fail_suggestions() { .setting(AppSettings::InferSubcommands) .subcommand(SubCommand::with_name("test")) .subcommand(SubCommand::with_name("temp")) - .get_matches_from_safe(vec![ - "prog", "temps" - ]); + .get_matches_from_safe(vec!["prog", "temps"]); assert!(m.is_err(), "{:#?}", m.unwrap()); assert_eq!(m.unwrap_err().kind, ErrorKind::InvalidSubcommand); } @@ -256,9 +234,7 @@ fn infer_subcommands_fail_suggestions() { .setting(AppSettings::InferSubcommands) .subcommand(SubCommand::with_name("test")) .subcommand(SubCommand::with_name("temp")) - .get_matches_from_safe(vec![ - "prog", "temps" - ]); + .get_matches_from_safe(vec!["prog", "temps"]); assert!(m.is_err(), "{:#?}", m.unwrap()); assert_eq!(m.unwrap_err().kind, ErrorKind::UnrecognizedSubcommand); } @@ -267,9 +243,7 @@ fn infer_subcommands_fail_suggestions() { fn no_bin_name() { let result = App::new("arg_required") .setting(AppSettings::NoBinaryName) - .arg(Arg::with_name("test") - .required(true) - .index(1)) + .arg(Arg::with_name("test").required(true).index(1)) .get_matches_from_safe(vec!["testing"]); assert!(result.is_ok()); let matches = result.unwrap(); @@ -284,11 +258,18 @@ fn unified_help() { .about("tests stuff") .version("1.3") .setting(AppSettings::UnifiedHelpMessage) - .args_from_usage("-f, --flag 'some flag' + .args_from_usage( + "-f, --flag 'some flag' [arg1] 'some pos arg' - --option [opt] 'some option'"); + --option [opt] 'some option'", + ); - assert!(test::compare_output(app, "test --help", UNIFIED_HELP, false)); + assert!(test::compare_output( + app, + "test --help", + UNIFIED_HELP, + false + )); } #[test] @@ -298,10 +279,17 @@ fn skip_possible_values() { .about("tests stuff") .version("1.3") .setting(AppSettings::HidePossibleValuesInHelp) - .args(&[Arg::from_usage("-o, --opt [opt] 'some option'").possible_values(&["one", "two"]), - Arg::from_usage("[arg1] 'some pos arg'").possible_values(&["three", "four"])]); + .args(&[ + Arg::from_usage("-o, --opt [opt] 'some option'").possible_values(&["one", "two"]), + Arg::from_usage("[arg1] 'some pos arg'").possible_values(&["three", "four"]), + ]); - assert!(test::compare_output(app, "test --help", SKIP_POS_VALS, false)); + assert!(test::compare_output( + app, + "test --help", + SKIP_POS_VALS, + false + )); } #[test] @@ -310,16 +298,15 @@ fn global_setting() { .global_setting(AppSettings::ColoredHelp) .subcommand(SubCommand::with_name("subcmd")); app.p.propagate_settings(); - assert!(app.p - .subcommands - .iter() - .filter(|s| s.p - .meta - .name == "subcmd") - .next() - .unwrap() - .p - .is_set(AppSettings::ColoredHelp)); + assert!(app + .p + .subcommands + .iter() + .filter(|s| s.p.meta.name == "subcmd") + .next() + .unwrap() + .p + .is_set(AppSettings::ColoredHelp)); } #[test] @@ -328,41 +315,43 @@ fn global_settings() { .global_settings(&[AppSettings::ColoredHelp, AppSettings::TrailingVarArg]) .subcommand(SubCommand::with_name("subcmd")); app.p.propagate_settings(); - assert!(app.p - .subcommands - .iter() - .filter(|s| s.p - .meta - .name == "subcmd") - .next() - .unwrap() - .p - .is_set(AppSettings::ColoredHelp)); - assert!(app.p - .subcommands - .iter() - .filter(|s| s.p - .meta - .name == "subcmd") - .next() - .unwrap() - .p - .is_set(AppSettings::TrailingVarArg)); - + assert!(app + .p + .subcommands + .iter() + .filter(|s| s.p.meta.name == "subcmd") + .next() + .unwrap() + .p + .is_set(AppSettings::ColoredHelp)); + assert!(app + .p + .subcommands + .iter() + .filter(|s| s.p.meta.name == "subcmd") + .next() + .unwrap() + .p + .is_set(AppSettings::TrailingVarArg)); } #[test] fn stop_delim_values_only_pos_follows() { let r = App::new("onlypos") .setting(AppSettings::DontDelimitTrailingValues) - .args(&[Arg::from_usage("-f [flag] 'some opt'"), - Arg::from_usage("[arg]... 'some arg'")]) + .args(&[ + Arg::from_usage("-f [flag] 'some opt'"), + Arg::from_usage("[arg]... 'some arg'"), + ]) .get_matches_from_safe(vec!["", "--", "-f", "-g,x"]); assert!(r.is_ok()); let m = r.unwrap(); assert!(m.is_present("arg")); assert!(!m.is_present("f")); - assert_eq!(m.values_of("arg").unwrap().collect::>(), &["-f", "-g,x"]); + assert_eq!( + m.values_of("arg").unwrap().collect::>(), + &["-f", "-g,x"] + ); } #[test] @@ -370,62 +359,75 @@ fn dont_delim_values_trailingvararg() { let m = App::new("positional") .setting(AppSettings::TrailingVarArg) .setting(AppSettings::DontDelimitTrailingValues) - .arg( - Arg::from_usage("[opt]... 'some pos'"), - ) + .arg(Arg::from_usage("[opt]... 'some pos'")) .get_matches_from(vec!["", "test", "--foo", "-Wl,-bar"]); assert!(m.is_present("opt")); - assert_eq!(m.values_of("opt").unwrap().collect::>(), &["test", "--foo", "-Wl,-bar"]); + assert_eq!( + m.values_of("opt").unwrap().collect::>(), + &["test", "--foo", "-Wl,-bar"] + ); } #[test] fn delim_values_only_pos_follows() { let r = App::new("onlypos") - .args(&[Arg::from_usage("-f [flag] 'some opt'"), - Arg::from_usage("[arg]... 'some arg'")]) + .args(&[ + Arg::from_usage("-f [flag] 'some opt'"), + Arg::from_usage("[arg]... 'some arg'"), + ]) .get_matches_from_safe(vec!["", "--", "-f", "-g,x"]); assert!(r.is_ok()); let m = r.unwrap(); assert!(m.is_present("arg")); assert!(!m.is_present("f")); - assert_eq!(m.values_of("arg").unwrap().collect::>(), &["-f", "-g,x"]); + assert_eq!( + m.values_of("arg").unwrap().collect::>(), + &["-f", "-g,x"] + ); } #[test] fn delim_values_trailingvararg() { let m = App::new("positional") .setting(AppSettings::TrailingVarArg) - .arg( - Arg::from_usage("[opt]... 'some pos'"), - ) + .arg(Arg::from_usage("[opt]... 'some pos'")) .get_matches_from(vec!["", "test", "--foo", "-Wl,-bar"]); assert!(m.is_present("opt")); - assert_eq!(m.values_of("opt").unwrap().collect::>(), &["test", "--foo", "-Wl,-bar"]); + assert_eq!( + m.values_of("opt").unwrap().collect::>(), + &["test", "--foo", "-Wl,-bar"] + ); } #[test] fn delim_values_only_pos_follows_with_delim() { let r = App::new("onlypos") - .args(&[Arg::from_usage("-f [flag] 'some opt'"), - Arg::from_usage("[arg]... 'some arg'").use_delimiter(true)]) + .args(&[ + Arg::from_usage("-f [flag] 'some opt'"), + Arg::from_usage("[arg]... 'some arg'").use_delimiter(true), + ]) .get_matches_from_safe(vec!["", "--", "-f", "-g,x"]); assert!(r.is_ok()); let m = r.unwrap(); assert!(m.is_present("arg")); assert!(!m.is_present("f")); - assert_eq!(m.values_of("arg").unwrap().collect::>(), &["-f", "-g", "x"]); + assert_eq!( + m.values_of("arg").unwrap().collect::>(), + &["-f", "-g", "x"] + ); } #[test] fn delim_values_trailingvararg_with_delim() { let m = App::new("positional") .setting(AppSettings::TrailingVarArg) - .arg( - Arg::from_usage("[opt]... 'some pos'").use_delimiter(true), - ) + .arg(Arg::from_usage("[opt]... 'some pos'").use_delimiter(true)) .get_matches_from(vec!["", "test", "--foo", "-Wl,-bar"]); assert!(m.is_present("opt")); - assert_eq!(m.values_of("opt").unwrap().collect::>(), &["test", "--foo", "-Wl", "-bar"]); + assert_eq!( + m.values_of("opt").unwrap().collect::>(), + &["test", "--foo", "-Wl", "-bar"] + ); } #[test] @@ -433,8 +435,7 @@ fn leading_hyphen_short() { let res = App::new("leadhy") .setting(AppSettings::AllowLeadingHyphen) .arg(Arg::with_name("some")) - .arg(Arg::with_name("other") - .short("o")) + .arg(Arg::with_name("other").short("o")) .get_matches_from_safe(vec!["", "-bar", "-o"]); assert!(res.is_ok(), "Error: {:?}", res.unwrap_err().kind); let m = res.unwrap(); @@ -448,8 +449,7 @@ fn leading_hyphen_long() { let res = App::new("leadhy") .setting(AppSettings::AllowLeadingHyphen) .arg(Arg::with_name("some")) - .arg(Arg::with_name("other") - .short("o")) + .arg(Arg::with_name("other").short("o")) .get_matches_from_safe(vec!["", "--bar", "-o"]); assert!(res.is_ok(), "Error: {:?}", res.unwrap_err().kind); let m = res.unwrap(); @@ -462,11 +462,8 @@ fn leading_hyphen_long() { fn leading_hyphen_opt() { let res = App::new("leadhy") .setting(AppSettings::AllowLeadingHyphen) - .arg(Arg::with_name("some") - .takes_value(true) - .long("opt")) - .arg(Arg::with_name("other") - .short("o")) + .arg(Arg::with_name("some").takes_value(true).long("opt")) + .arg(Arg::with_name("other").short("o")) .get_matches_from_safe(vec!["", "--opt", "--bar", "-o"]); assert!(res.is_ok(), "Error: {:?}", res.unwrap_err().kind); let m = res.unwrap(); @@ -480,9 +477,7 @@ fn allow_negative_numbers() { let res = App::new("negnum") .setting(AppSettings::AllowNegativeNumbers) .arg(Arg::with_name("panum")) - .arg(Arg::with_name("onum") - .short("o") - .takes_value(true)) + .arg(Arg::with_name("onum").short("o").takes_value(true)) .get_matches_from_safe(vec!["negnum", "-20", "-o", "-1.2"]); assert!(res.is_ok(), "Error: {:?}", res.unwrap_err().kind); let m = res.unwrap(); @@ -495,9 +490,7 @@ fn allow_negative_numbers_fail() { let res = App::new("negnum") .setting(AppSettings::AllowNegativeNumbers) .arg(Arg::with_name("panum")) - .arg(Arg::with_name("onum") - .short("o") - .takes_value(true)) + .arg(Arg::with_name("onum").short("o").takes_value(true)) .get_matches_from_safe(vec!["negnum", "--foo", "-o", "-1.2"]); assert!(res.is_err()); assert_eq!(res.unwrap_err().kind, ErrorKind::UnknownArgument) @@ -508,12 +501,13 @@ fn leading_double_hyphen_trailingvararg() { let m = App::new("positional") .setting(AppSettings::TrailingVarArg) .setting(AppSettings::AllowLeadingHyphen) - .arg( - Arg::from_usage("[opt]... 'some pos'"), - ) + .arg(Arg::from_usage("[opt]... 'some pos'")) .get_matches_from(vec!["", "--foo", "-Wl", "bar"]); assert!(m.is_present("opt")); - assert_eq!(m.values_of("opt").unwrap().collect::>(), &["--foo", "-Wl", "bar"]); + assert_eq!( + m.values_of("opt").unwrap().collect::>(), + &["--foo", "-Wl", "bar"] + ); } #[test] @@ -531,8 +525,7 @@ fn test_unset_settings() { assert!(&m.p.is_set(AppSettings::AllowInvalidUtf8)); assert!(&m.p.is_set(AppSettings::ColorAuto)); - let m = m.unset_settings(&[AppSettings::AllowInvalidUtf8, - AppSettings::ColorAuto]); + let m = m.unset_settings(&[AppSettings::AllowInvalidUtf8, AppSettings::ColorAuto]); assert!(!m.p.is_set(AppSettings::AllowInvalidUtf8)); assert!(!m.p.is_set(AppSettings::ColorAuto)); } @@ -558,38 +551,45 @@ fn dont_collapse_args() { Arg::with_name("arg2").help("some"), Arg::with_name("arg3").help("some"), ]); - assert!(test::compare_output(app, "clap-test --help", DONT_COLLAPSE_ARGS, false)); + assert!(test::compare_output( + app, + "clap-test --help", + DONT_COLLAPSE_ARGS, + false + )); } #[test] fn require_eq() { - let app = App::new("clap-test") - .version("v1.4.8") - .arg( - Arg::with_name("opt") + let app = App::new("clap-test").version("v1.4.8").arg( + Arg::with_name("opt") .long("opt") .short("o") .required(true) .require_equals(true) .value_name("FILE") .help("some"), - ); - assert!(test::compare_output(app, "clap-test --help", REQUIRE_EQUALS, false)); + ); + assert!(test::compare_output( + app, + "clap-test --help", + REQUIRE_EQUALS, + false + )); } #[test] fn args_negate_subcommands_one_level() { - let res = App::new("disablehelp") - .setting(AppSettings::ArgsNegateSubcommands) - .setting(AppSettings::SubcommandsNegateReqs) - .arg_from_usage(" 'some arg'") - .arg_from_usage(" 'some arg'") - .subcommand(SubCommand::with_name("sub1") - .subcommand(SubCommand::with_name("sub2") - .subcommand(SubCommand::with_name("sub3")) - ) - ) - .get_matches_from_safe(vec!["", "pickles", "sub1"]); + let res = + App::new("disablehelp") + .setting(AppSettings::ArgsNegateSubcommands) + .setting(AppSettings::SubcommandsNegateReqs) + .arg_from_usage(" 'some arg'") + .arg_from_usage(" 'some arg'") + .subcommand(SubCommand::with_name("sub1").subcommand( + SubCommand::with_name("sub2").subcommand(SubCommand::with_name("sub3")), + )) + .get_matches_from_safe(vec!["", "pickles", "sub1"]); assert!(res.is_ok(), "error: {:?}", res.unwrap_err().kind); let m = res.unwrap(); assert_eq!(m.value_of("arg2"), Some("sub1")); @@ -602,20 +602,23 @@ fn args_negate_subcommands_two_levels() { .global_setting(AppSettings::SubcommandsNegateReqs) .arg_from_usage(" 'some arg'") .arg_from_usage(" 'some arg'") - .subcommand(SubCommand::with_name("sub1") - .arg_from_usage(" 'some'") - .arg_from_usage(" 'some'") - .subcommand(SubCommand::with_name("sub2") - .subcommand(SubCommand::with_name("sub3")) - ) + .subcommand( + SubCommand::with_name("sub1") + .arg_from_usage(" 'some'") + .arg_from_usage(" 'some'") + .subcommand( + SubCommand::with_name("sub2").subcommand(SubCommand::with_name("sub3")), + ), ) .get_matches_from_safe(vec!["", "sub1", "arg", "sub2"]); assert!(res.is_ok(), "error: {:?}", res.unwrap_err().kind); let m = res.unwrap(); - assert_eq!(m.subcommand_matches("sub1").unwrap().value_of("arg2"), Some("sub2")); + assert_eq!( + m.subcommand_matches("sub1").unwrap().value_of("arg2"), + Some("sub2") + ); } - #[test] fn propagate_vals_down() { let m = App::new("myprog") @@ -670,7 +673,10 @@ fn missing_positional_no_hyphen() { let expected_args = vec!["arg1", "arg2", "arg3"]; assert_eq!(m.value_of("BENCH"), expected_bench); - assert_eq!(m.values_of("ARGS").unwrap().collect::>(), &*expected_args); + assert_eq!( + m.values_of("ARGS").unwrap().collect::>(), + &*expected_args + ); } #[test] @@ -688,7 +694,10 @@ fn missing_positional_hyphen() { let expected_args = vec!["arg1", "arg2", "arg3"]; assert_eq!(m.value_of("BENCH"), expected_bench); - assert_eq!(m.values_of("ARGS").unwrap().collect::>(), &*expected_args); + assert_eq!( + m.values_of("ARGS").unwrap().collect::>(), + &*expected_args + ); } #[test] @@ -712,7 +721,10 @@ fn missing_positional_hyphen_far_back() { assert_eq!(m.value_of("BENCH1"), expected_bench1); assert_eq!(m.value_of("BENCH2"), expected_bench2); assert_eq!(m.value_of("BENCH3"), expected_bench3); - assert_eq!(m.values_of("ARGS").unwrap().collect::>(), &*expected_args); + assert_eq!( + m.values_of("ARGS").unwrap().collect::>(), + &*expected_args + ); } #[test] @@ -765,10 +777,14 @@ fn issue_1093_allow_ext_sc() { let app = App::new("clap-test") .version("v1.4.8") .setting(AppSettings::AllowExternalSubcommands); - assert!(test::compare_output(app, "clap-test --help", ALLOW_EXT_SC, false)); + assert!(test::compare_output( + app, + "clap-test --help", + ALLOW_EXT_SC, + false + )); } - #[test] fn allow_ext_sc_when_sc_required() { let res = App::new("clap-test") @@ -809,9 +825,9 @@ fn external_subcommand_looks_like_built_in() { fn aaos_flags() { // flags let res = App::new("posix") - .setting(AppSettings::AllArgsOverrideSelf) - .arg(Arg::from_usage("--flag 'some flag'")) - .get_matches_from_safe(vec!["", "--flag", "--flag"]); + .setting(AppSettings::AllArgsOverrideSelf) + .arg(Arg::from_usage("--flag 'some flag'")) + .get_matches_from_safe(vec!["", "--flag", "--flag"]); assert!(res.is_ok()); let m = res.unwrap(); assert!(m.is_present("flag")); @@ -822,9 +838,9 @@ fn aaos_flags() { fn aaos_flags_mult() { // flags with multiple let res = App::new("posix") - .setting(AppSettings::AllArgsOverrideSelf) - .arg(Arg::from_usage("--flag... 'some flag'")) - .get_matches_from_safe(vec!["", "--flag", "--flag", "--flag", "--flag"]); + .setting(AppSettings::AllArgsOverrideSelf) + .arg(Arg::from_usage("--flag... 'some flag'")) + .get_matches_from_safe(vec!["", "--flag", "--flag", "--flag", "--flag"]); assert!(res.is_ok()); let m = res.unwrap(); assert!(m.is_present("flag")); @@ -835,9 +851,9 @@ fn aaos_flags_mult() { fn aaos_opts() { // opts let res = App::new("posix") - .setting(AppSettings::AllArgsOverrideSelf) - .arg(Arg::from_usage("--opt [val] 'some option'")) - .get_matches_from_safe(vec!["", "--opt=some", "--opt=other"]); + .setting(AppSettings::AllArgsOverrideSelf) + .arg(Arg::from_usage("--opt [val] 'some option'")) + .get_matches_from_safe(vec!["", "--opt=some", "--opt=other"]); assert!(res.is_ok()); let m = res.unwrap(); assert!(m.is_present("opt")); @@ -849,10 +865,10 @@ fn aaos_opts() { fn aaos_opts_w_other_overrides() { // opts with other overrides let res = App::new("posix") - .setting(AppSettings::AllArgsOverrideSelf) - .arg(Arg::from_usage("--opt [val] 'some option'")) - .arg(Arg::from_usage("--other [val] 'some other option'").overrides_with("opt")) - .get_matches_from_safe(vec!["", "--opt=some", "--other=test", "--opt=other"]); + .setting(AppSettings::AllArgsOverrideSelf) + .arg(Arg::from_usage("--opt [val] 'some option'")) + .arg(Arg::from_usage("--other [val] 'some other option'").overrides_with("opt")) + .get_matches_from_safe(vec!["", "--opt=some", "--other=test", "--opt=other"]); assert!(res.is_ok()); let m = res.unwrap(); assert!(m.is_present("opt")); @@ -865,10 +881,10 @@ fn aaos_opts_w_other_overrides() { fn aaos_opts_w_other_overrides_rev() { // opts with other overrides, rev let res = App::new("posix") - .setting(AppSettings::AllArgsOverrideSelf) - .arg(Arg::from_usage("--opt [val] 'some option'")) - .arg(Arg::from_usage("--other [val] 'some other option'").overrides_with("opt")) - .get_matches_from_safe(vec!["", "--opt=some", "--opt=other", "--other=val"]); + .setting(AppSettings::AllArgsOverrideSelf) + .arg(Arg::from_usage("--opt [val] 'some option'")) + .arg(Arg::from_usage("--other [val] 'some other option'").overrides_with("opt")) + .get_matches_from_safe(vec!["", "--opt=some", "--opt=other", "--other=val"]); assert!(res.is_ok()); let m = res.unwrap(); assert!(!m.is_present("opt")); @@ -880,10 +896,10 @@ fn aaos_opts_w_other_overrides_rev() { fn aaos_opts_w_other_overrides_2() { // opts with other overrides let res = App::new("posix") - .setting(AppSettings::AllArgsOverrideSelf) - .arg(Arg::from_usage("--opt [val] 'some option'").overrides_with("other")) - .arg(Arg::from_usage("--other [val] 'some other option'")) - .get_matches_from_safe(vec!["", "--opt=some", "--other=test", "--opt=other"]); + .setting(AppSettings::AllArgsOverrideSelf) + .arg(Arg::from_usage("--opt [val] 'some option'").overrides_with("other")) + .arg(Arg::from_usage("--other [val] 'some other option'")) + .get_matches_from_safe(vec!["", "--opt=some", "--other=test", "--opt=other"]); assert!(res.is_ok()); let m = res.unwrap(); assert!(m.is_present("opt")); @@ -896,10 +912,10 @@ fn aaos_opts_w_other_overrides_2() { fn aaos_opts_w_other_overrides_rev_2() { // opts with other overrides, rev let res = App::new("posix") - .setting(AppSettings::AllArgsOverrideSelf) - .arg(Arg::from_usage("--opt [val] 'some option'").overrides_with("other")) - .arg(Arg::from_usage("--other [val] 'some other option'")) - .get_matches_from_safe(vec!["", "--opt=some", "--opt=other", "--other=val"]); + .setting(AppSettings::AllArgsOverrideSelf) + .arg(Arg::from_usage("--opt [val] 'some option'").overrides_with("other")) + .arg(Arg::from_usage("--other [val] 'some other option'")) + .get_matches_from_safe(vec!["", "--opt=some", "--opt=other", "--other=val"]); assert!(res.is_ok()); let m = res.unwrap(); assert!(!m.is_present("opt")); @@ -911,55 +927,69 @@ fn aaos_opts_w_other_overrides_rev_2() { fn aaos_opts_mult() { // opts with multiple let res = App::new("posix") - .setting(AppSettings::AllArgsOverrideSelf) - .arg(Arg::from_usage("--opt [val]... 'some option'") - .number_of_values(1) - .require_delimiter(true)) - .get_matches_from_safe(vec!["", "--opt=some", "--opt=other", "--opt=one,two"]); + .setting(AppSettings::AllArgsOverrideSelf) + .arg( + Arg::from_usage("--opt [val]... 'some option'") + .number_of_values(1) + .require_delimiter(true), + ) + .get_matches_from_safe(vec!["", "--opt=some", "--opt=other", "--opt=one,two"]); assert!(res.is_ok()); let m = res.unwrap(); assert!(m.is_present("opt")); assert_eq!(m.occurrences_of("opt"), 3); - assert_eq!(m.values_of("opt").unwrap().collect::>(), &["some", "other", "one", "two"]); + assert_eq!( + m.values_of("opt").unwrap().collect::>(), + &["some", "other", "one", "two"] + ); } #[test] fn aaos_opts_mult_req_delims() { // opts with multiple and require delims let res = App::new("posix") - .setting(AppSettings::AllArgsOverrideSelf) - .arg(Arg::from_usage("--opt [val]... 'some option'")) - .get_matches_from_safe(vec!["", "--opt", "first", "overides", "--opt", "some", "other", "val"]); + .setting(AppSettings::AllArgsOverrideSelf) + .arg(Arg::from_usage("--opt [val]... 'some option'")) + .get_matches_from_safe(vec![ + "", "--opt", "first", "overides", "--opt", "some", "other", "val", + ]); assert!(res.is_ok()); let m = res.unwrap(); assert!(m.is_present("opt")); assert_eq!(m.occurrences_of("opt"), 2); - assert_eq!(m.values_of("opt").unwrap().collect::>(), &["first", "overides", "some", "other", "val"]); + assert_eq!( + m.values_of("opt").unwrap().collect::>(), + &["first", "overides", "some", "other", "val"] + ); } #[test] fn aaos_pos_mult() { // opts with multiple let res = App::new("posix") - .setting(AppSettings::AllArgsOverrideSelf) - .arg(Arg::from_usage("[val]... 'some pos'")) - .get_matches_from_safe(vec!["", "some", "other", "value"]); + .setting(AppSettings::AllArgsOverrideSelf) + .arg(Arg::from_usage("[val]... 'some pos'")) + .get_matches_from_safe(vec!["", "some", "other", "value"]); assert!(res.is_ok()); let m = res.unwrap(); assert!(m.is_present("val")); assert_eq!(m.occurrences_of("val"), 3); - assert_eq!(m.values_of("val").unwrap().collect::>(), &["some", "other", "value"]); + assert_eq!( + m.values_of("val").unwrap().collect::>(), + &["some", "other", "value"] + ); } #[test] fn aaos_option_use_delim_false() { - let m = App::new("posix") - .setting(AppSettings::AllArgsOverrideSelf) - .arg(Arg::from_usage("--opt [val] 'some option'") - .use_delimiter(false)) - .get_matches_from(vec!["", "--opt=some,other", "--opt=one,two"]); + .setting(AppSettings::AllArgsOverrideSelf) + .arg(Arg::from_usage("--opt [val] 'some option'").use_delimiter(false)) + .get_matches_from(vec!["", "--opt=some,other", "--opt=one,two"]); assert!(m.is_present("opt")); assert_eq!(m.occurrences_of("opt"), 1); - assert_eq!(m.values_of("opt").unwrap().collect::>(), &["one,two"]); + assert_eq!( + m.values_of("opt").unwrap().collect::>(), + &["one,two"] + ); } diff --git a/tests/arg_aliases.rs b/tests/arg_aliases.rs index 77bcd17d90f..80634100359 100644 --- a/tests/arg_aliases.rs +++ b/tests/arg_aliases.rs @@ -36,14 +36,14 @@ OPTIONS: #[test] fn single_alias_of_option() { let a = App::new("single_alias") - .arg(Arg::with_name("alias") - .long("alias") - .takes_value(true) - .help("single alias") - .alias("new-opt")) - .get_matches_from_safe(vec![ - "", "--new-opt", "cool" - ]); + .arg( + Arg::with_name("alias") + .long("alias") + .takes_value(true) + .help("single alias") + .alias("new-opt"), + ) + .get_matches_from_safe(vec!["", "--new-opt", "cool"]); assert!(a.is_ok()); let a = a.unwrap(); assert!(a.is_present("alias")); @@ -52,37 +52,34 @@ fn single_alias_of_option() { #[test] fn multiple_aliases_of_option() { - let a = App::new("multiple_aliases") - .arg(Arg::with_name("aliases") + let a = App::new("multiple_aliases").arg( + Arg::with_name("aliases") .long("aliases") .takes_value(true) .help("multiple aliases") - .aliases(&[ - "alias1", - "alias2", - "alias3" - ])); - let long = a.clone().get_matches_from_safe(vec![ - "", "--aliases", "value" - ]); + .aliases(&["alias1", "alias2", "alias3"]), + ); + let long = a + .clone() + .get_matches_from_safe(vec!["", "--aliases", "value"]); assert!(long.is_ok()); let long = long.unwrap(); - let als1 = a.clone().get_matches_from_safe(vec![ - "", "--alias1", "value" - ]); + let als1 = a + .clone() + .get_matches_from_safe(vec!["", "--alias1", "value"]); assert!(als1.is_ok()); let als1 = als1.unwrap(); - let als2 = a.clone().get_matches_from_safe(vec![ - "", "--alias2", "value" - ]); + let als2 = a + .clone() + .get_matches_from_safe(vec!["", "--alias2", "value"]); assert!(als2.is_ok()); let als2 = als2.unwrap(); - let als3 = a.clone().get_matches_from_safe(vec![ - "", "--alias3", "value" - ]); + let als3 = a + .clone() + .get_matches_from_safe(vec!["", "--alias3", "value"]); assert!(als3.is_ok()); let als3 = als3.unwrap(); @@ -99,10 +96,8 @@ fn multiple_aliases_of_option() { #[test] fn single_alias_of_flag() { let a = App::new("test") - .arg(Arg::with_name("flag") - .long("flag") - .alias("alias")) - .get_matches_from_safe(vec!["", "--alias"]); + .arg(Arg::with_name("flag").long("flag").alias("alias")) + .get_matches_from_safe(vec!["", "--alias"]); assert!(a.is_ok()); let a = a.unwrap(); assert!(a.is_present("flag")); @@ -110,12 +105,13 @@ fn single_alias_of_flag() { #[test] fn multiple_aliases_of_flag() { - let a = App::new("test") - .arg(Arg::with_name("flag") - .long("flag") - .aliases(&["invisible", - "set", "of", - "cool", "aliases"])); + let a = App::new("test").arg(Arg::with_name("flag").long("flag").aliases(&[ + "invisible", + "set", + "of", + "cool", + "aliases", + ])); let flag = a.clone().get_matches_from_safe(vec!["", "--flag"]); assert!(flag.is_ok()); @@ -142,19 +138,22 @@ fn multiple_aliases_of_flag() { #[test] fn alias_on_a_subcommand_option() { let m = App::new("test") - .subcommand(SubCommand::with_name("some") - .arg(Arg::with_name("test") - .short("t") - .long("test") - .takes_value(true) - .alias("opt") - .help("testing testing"))) - .arg(Arg::with_name("other") - .long("other") - .aliases(&["o1", "o2", "o3"])) - .get_matches_from(vec![ - "test", "some", "--opt", "awesome" - ]); + .subcommand( + SubCommand::with_name("some").arg( + Arg::with_name("test") + .short("t") + .long("test") + .takes_value(true) + .alias("opt") + .help("testing testing"), + ), + ) + .arg( + Arg::with_name("other") + .long("other") + .aliases(&["o1", "o2", "o3"]), + ) + .get_matches_from(vec!["test", "some", "--opt", "awesome"]); assert!(m.subcommand_matches("some").is_some()); let sub_m = m.subcommand_matches("some").unwrap(); @@ -164,37 +163,52 @@ fn alias_on_a_subcommand_option() { #[test] fn invisible_arg_aliases_help_output() { - let app = App::new("ct") - .author("Salim Afiune") - .subcommand(SubCommand::with_name("test") + let app = App::new("ct").author("Salim Afiune").subcommand( + SubCommand::with_name("test") .about("Some help") .version("1.2") - .arg(Arg::with_name("opt") - .long("opt") - .short("o") - .takes_value(true) - .aliases(&["invisible", "als1", "more"])) - .arg(Arg::from_usage("-f, --flag") - .aliases(&["invisible", "flg1", "anyway"]))); - assert!(test::compare_output(app, "ct test --help", SC_INVISIBLE_ALIAS_HELP, false)); + .arg( + Arg::with_name("opt") + .long("opt") + .short("o") + .takes_value(true) + .aliases(&["invisible", "als1", "more"]), + ) + .arg(Arg::from_usage("-f, --flag").aliases(&["invisible", "flg1", "anyway"])), + ); + assert!(test::compare_output( + app, + "ct test --help", + SC_INVISIBLE_ALIAS_HELP, + false + )); } #[test] fn visible_arg_aliases_help_output() { - let app = App::new("ct") - .author("Salim Afiune") - .subcommand(SubCommand::with_name("test") + let app = App::new("ct").author("Salim Afiune").subcommand( + SubCommand::with_name("test") .about("Some help") .version("1.2") - .arg(Arg::with_name("opt") - .long("opt") - .short("o") - .takes_value(true) - .alias("invisible") - .visible_alias("visible")) - .arg(Arg::with_name("flg") - .long("flag") - .short("f") - .visible_aliases(&["v_flg", "flag2", "flg3"]))); - assert!(test::compare_output(app, "ct test --help", SC_VISIBLE_ALIAS_HELP, false)); + .arg( + Arg::with_name("opt") + .long("opt") + .short("o") + .takes_value(true) + .alias("invisible") + .visible_alias("visible"), + ) + .arg( + Arg::with_name("flg") + .long("flag") + .short("f") + .visible_aliases(&["v_flg", "flag2", "flg3"]), + ), + ); + assert!(test::compare_output( + app, + "ct test --help", + SC_VISIBLE_ALIAS_HELP, + false + )); } diff --git a/tests/borrowed.rs b/tests/borrowed.rs index e7a184b5795..a510d5bd787 100644 --- a/tests/borrowed.rs +++ b/tests/borrowed.rs @@ -7,8 +7,14 @@ include!("../clap-test.rs"); #[test] fn borrowed_args() { - let arg = Arg::with_name("some").short("s").long("some").help("other help"); - let arg2 = Arg::with_name("some2").short("S").long("some-thing").help("other help"); + let arg = Arg::with_name("some") + .short("s") + .long("some") + .help("other help"); + let arg2 = Arg::with_name("some2") + .short("S") + .long("some-thing") + .help("other help"); let result = App::new("sub_command_negate") .arg(Arg::with_name("test").index(1)) .arg(&arg) diff --git a/tests/completions.rs b/tests/completions.rs index 24409ade044..76e8077f0c9 100644 --- a/tests/completions.rs +++ b/tests/completions.rs @@ -1,7 +1,7 @@ -extern crate regex; extern crate clap; +extern crate regex; -use clap::{App, Arg, SubCommand, Shell}; +use clap::{App, Arg, Shell, SubCommand}; use regex::Regex; static BASH: &'static str = r#"_myapp() { @@ -715,51 +715,71 @@ fn compare(left: &str, right: &str) -> bool { b } -fn build_app() -> App<'static, 'static> { build_app_with_name("myapp") } +fn build_app() -> App<'static, 'static> { + build_app_with_name("myapp") +} fn build_app_with_name(s: &'static str) -> App<'static, 'static> { App::new(s) .about("Tests completions") .arg(Arg::with_name("file").help("some input file")) - .subcommand(SubCommand::with_name("test") - .about("tests things") - .arg(Arg::with_name("case") - .long("case") - .takes_value(true) - .help("the case to test"))) + .subcommand( + SubCommand::with_name("test").about("tests things").arg( + Arg::with_name("case") + .long("case") + .takes_value(true) + .help("the case to test"), + ), + ) } fn build_app_special_commands() -> App<'static, 'static> { build_app_with_name("my_app") - .subcommand(SubCommand::with_name("some_cmd") - .about("tests other things") - .arg(Arg::with_name("config") - .long("--config") - .takes_value(true) - .help("the other case to test"))) + .subcommand( + SubCommand::with_name("some_cmd") + .about("tests other things") + .arg( + Arg::with_name("config") + .long("--config") + .takes_value(true) + .help("the other case to test"), + ), + ) .subcommand(SubCommand::with_name("some-cmd-with-hypens")) } fn build_app_special_help() -> App<'static, 'static> { App::new("my_app") - .arg(Arg::with_name("single-quotes") - .long("single-quotes") - .help("Can be 'always', 'auto', or 'never'")) - .arg(Arg::with_name("double-quotes") - .long("double-quotes") - .help("Can be \"always\", \"auto\", or \"never\"")) - .arg(Arg::with_name("backticks") - .long("backticks") - .help("For more information see `echo test`")) - .arg(Arg::with_name("backslash") - .long("backslash") - .help("Avoid '\\n'")) - .arg(Arg::with_name("brackets") - .long("brackets") - .help("List packages [filter]")) - .arg(Arg::with_name("expansions") - .long("expansions") - .help("Execute the shell command with $SHELL")) + .arg( + Arg::with_name("single-quotes") + .long("single-quotes") + .help("Can be 'always', 'auto', or 'never'"), + ) + .arg( + Arg::with_name("double-quotes") + .long("double-quotes") + .help("Can be \"always\", \"auto\", or \"never\""), + ) + .arg( + Arg::with_name("backticks") + .long("backticks") + .help("For more information see `echo test`"), + ) + .arg( + Arg::with_name("backslash") + .long("backslash") + .help("Avoid '\\n'"), + ) + .arg( + Arg::with_name("brackets") + .long("brackets") + .help("List packages [filter]"), + ) + .arg( + Arg::with_name("expansions") + .long("expansions") + .help("Execute the shell command with $SHELL"), + ) } #[test] diff --git a/tests/conflicts.rs b/tests/conflicts.rs index 72a9e05f3a1..f1d4ef4cea6 100644 --- a/tests/conflicts.rs +++ b/tests/conflicts.rs @@ -3,7 +3,7 @@ extern crate regex; include!("../clap-test.rs"); -use clap::{App, Arg, ErrorKind, ArgGroup}; +use clap::{App, Arg, ArgGroup, ErrorKind}; static CONFLICT_ERR: &'static str = "error: The argument '-F' cannot be used with '--flag' @@ -22,8 +22,7 @@ For more information try --help"; #[test] fn flag_conflict() { let result = App::new("flag_conflict") - .arg(Arg::from_usage("-f, --flag 'some flag'") - .conflicts_with("other")) + .arg(Arg::from_usage("-f, --flag 'some flag'").conflicts_with("other")) .arg(Arg::from_usage("-o, --other 'some flag'")) .get_matches_from_safe(vec!["myprog", "-f", "-o"]); assert!(result.is_err()); @@ -34,8 +33,7 @@ fn flag_conflict() { #[test] fn flag_conflict_2() { let result = App::new("flag_conflict") - .arg(Arg::from_usage("-f, --flag 'some flag'") - .conflicts_with("other")) + .arg(Arg::from_usage("-f, --flag 'some flag'").conflicts_with("other")) .arg(Arg::from_usage("-o, --other 'some flag'")) .get_matches_from_safe(vec!["myprog", "-o", "-f"]); assert!(result.is_err()); @@ -46,12 +44,13 @@ fn flag_conflict_2() { #[test] fn group_conflict() { let result = App::new("group_conflict") - .arg(Arg::from_usage("-f, --flag 'some flag'") - .conflicts_with("gr")) - .group(ArgGroup::with_name("gr") - .required(true) - .arg("some") - .arg("other")) + .arg(Arg::from_usage("-f, --flag 'some flag'").conflicts_with("gr")) + .group( + ArgGroup::with_name("gr") + .required(true) + .arg("some") + .arg("other"), + ) .arg(Arg::from_usage("--some 'some arg'")) .arg(Arg::from_usage("--other 'other arg'")) .get_matches_from_safe(vec!["myprog", "--other", "-f"]); @@ -63,12 +62,13 @@ fn group_conflict() { #[test] fn group_conflict_2() { let result = App::new("group_conflict") - .arg(Arg::from_usage("-f, --flag 'some flag'") - .conflicts_with("gr")) - .group(ArgGroup::with_name("gr") - .required(true) - .arg("some") - .arg("other")) + .arg(Arg::from_usage("-f, --flag 'some flag'").conflicts_with("gr")) + .group( + ArgGroup::with_name("gr") + .required(true) + .arg("some") + .arg("other"), + ) .arg(Arg::from_usage("--some 'some arg'")) .arg(Arg::from_usage("--other 'other arg'")) .get_matches_from_safe(vec!["myprog", "-f", "--some"]); @@ -79,21 +79,29 @@ fn group_conflict_2() { #[test] fn conflict_output() { - test::compare_output(test::complex_app(), "clap-test val1 --flag --long-option-2 val2 -F", CONFLICT_ERR, true); + test::compare_output( + test::complex_app(), + "clap-test val1 --flag --long-option-2 val2 -F", + CONFLICT_ERR, + true, + ); } #[test] fn conflict_output_rev() { - test::compare_output(test::complex_app(), "clap-test val1 -F --long-option-2 val2 --flag", CONFLICT_ERR_REV, true); + test::compare_output( + test::complex_app(), + "clap-test val1 -F --long-option-2 val2 --flag", + CONFLICT_ERR_REV, + true, + ); } #[test] fn conflict_with_unused_default_value() { let result = App::new("conflict") - .arg(Arg::from_usage("-o, --opt=[opt] 'some opt'") - .default_value("default")) - .arg(Arg::from_usage("-f, --flag 'some flag'") - .conflicts_with("opt")) + .arg(Arg::from_usage("-o, --opt=[opt] 'some opt'").default_value("default")) + .arg(Arg::from_usage("-f, --flag 'some flag'").conflicts_with("opt")) .get_matches_from_safe(vec!["myprog", "-f"]); assert!(result.is_ok()); let m = result.unwrap(); diff --git a/tests/default_vals.rs b/tests/default_vals.rs index 0dfd3c86045..2b59608601c 100644 --- a/tests/default_vals.rs +++ b/tests/default_vals.rs @@ -8,9 +8,7 @@ use clap::{App, Arg, ErrorKind}; #[test] fn opts() { let r = App::new("df") - .arg( - Arg::from_usage("-o [opt] 'some opt'").default_value("default"), - ) + .arg(Arg::from_usage("-o [opt] 'some opt'").default_value("default")) .get_matches_from_safe(vec![""]); assert!(r.is_ok()); let m = r.unwrap(); @@ -21,9 +19,7 @@ fn opts() { #[test] fn opt_user_override() { let r = App::new("df") - .arg( - Arg::from_usage("--opt [FILE] 'some arg'").default_value("default"), - ) + .arg(Arg::from_usage("--opt [FILE] 'some arg'").default_value("default")) .get_matches_from_safe(vec!["", "--opt", "value"]); assert!(r.is_ok()); let m = r.unwrap(); @@ -61,9 +57,7 @@ fn osstr_opts() { let expected = OsStr::new("default"); let r = App::new("df") - .arg( - Arg::from_usage("-o [opt] 'some opt'").default_value_os(expected), - ) + .arg(Arg::from_usage("-o [opt] 'some opt'").default_value_os(expected)) .get_matches_from_safe(vec![""]); assert!(r.is_ok()); let m = r.unwrap(); @@ -77,9 +71,7 @@ fn osstr_opt_user_override() { let default = OsStr::new("default"); let r = App::new("df") - .arg( - Arg::from_usage("--opt [FILE] 'some arg'").default_value_os(default), - ) + .arg(Arg::from_usage("--opt [FILE] 'some arg'").default_value_os(default)) .get_matches_from_safe(vec!["", "--opt", "value"]); assert!(r.is_ok()); let m = r.unwrap(); @@ -93,9 +85,7 @@ fn osstr_positionals() { let expected = OsStr::new("default"); let r = App::new("df") - .arg( - Arg::from_usage("[arg] 'some opt'").default_value_os(expected), - ) + .arg(Arg::from_usage("[arg] 'some opt'").default_value_os(expected)) .get_matches_from_safe(vec![""]); assert!(r.is_ok()); let m = r.unwrap(); @@ -109,9 +99,7 @@ fn osstr_positional_user_override() { let default = OsStr::new("default"); let r = App::new("df") - .arg( - Arg::from_usage("[arg] 'some arg'").default_value_os(default), - ) + .arg(Arg::from_usage("[arg] 'some arg'").default_value_os(default)) .get_matches_from_safe(vec!["", "value"]); assert!(r.is_ok()); let m = r.unwrap(); @@ -125,11 +113,7 @@ fn osstr_positional_user_override() { fn default_if_arg_present_no_default() { let r = App::new("df") .arg(Arg::from_usage("--opt [FILE] 'some arg'")) - .arg(Arg::from_usage("[arg] 'some arg'").default_value_if( - "opt", - None, - "default", - )) + .arg(Arg::from_usage("[arg] 'some arg'").default_value_if("opt", None, "default")) .get_matches_from_safe(vec!["", "--opt", "some"]); assert!(r.is_ok()); let m = r.unwrap(); @@ -141,11 +125,7 @@ fn default_if_arg_present_no_default() { fn default_if_arg_present_no_default_user_override() { let r = App::new("df") .arg(Arg::from_usage("--opt [FILE] 'some arg'")) - .arg(Arg::from_usage("[arg] 'some arg'").default_value_if( - "opt", - None, - "default", - )) + .arg(Arg::from_usage("[arg] 'some arg'").default_value_if("opt", None, "default")) .get_matches_from_safe(vec!["", "--opt", "some", "other"]); assert!(r.is_ok()); let m = r.unwrap(); @@ -223,11 +203,7 @@ fn default_if_arg_present_no_arg_with_default_user_override() { fn default_if_arg_present_with_value_no_default() { let r = App::new("df") .arg(Arg::from_usage("--opt [FILE] 'some arg'")) - .arg(Arg::from_usage("[arg] 'some arg'").default_value_if( - "opt", - Some("value"), - "default", - )) + .arg(Arg::from_usage("[arg] 'some arg'").default_value_if("opt", Some("value"), "default")) .get_matches_from_safe(vec!["", "--opt", "value"]); assert!(r.is_ok()); let m = r.unwrap(); @@ -239,11 +215,7 @@ fn default_if_arg_present_with_value_no_default() { fn default_if_arg_present_with_value_no_default_fail() { let r = App::new("df") .arg(Arg::from_usage("--opt [FILE] 'some arg'")) - .arg(Arg::from_usage("[arg] 'some arg'").default_value_if( - "opt", - Some("value"), - "default", - )) + .arg(Arg::from_usage("[arg] 'some arg'").default_value_if("opt", Some("value"), "default")) .get_matches_from_safe(vec!["", "--opt", "other"]); assert!(r.is_ok()); let m = r.unwrap(); @@ -255,11 +227,7 @@ fn default_if_arg_present_with_value_no_default_fail() { fn default_if_arg_present_with_value_no_default_user_override() { let r = App::new("df") .arg(Arg::from_usage("--opt [FILE] 'some arg'")) - .arg(Arg::from_usage("[arg] 'some arg'").default_value_if( - "opt", - Some("some"), - "default", - )) + .arg(Arg::from_usage("[arg] 'some arg'").default_value_if("opt", Some("some"), "default")) .get_matches_from_safe(vec!["", "--opt", "some", "other"]); assert!(r.is_ok()); let m = r.unwrap(); diff --git a/tests/delimiters.rs b/tests/delimiters.rs index d5b60b9cb7a..ac612c6d749 100644 --- a/tests/delimiters.rs +++ b/tests/delimiters.rs @@ -5,13 +5,8 @@ use clap::{App, Arg}; #[test] fn opt_default_no_delim() { let m = App::new("no_delim") - .arg(Arg::with_name("option") - .long("option") - .takes_value(true)) - .get_matches_from_safe(vec![ - "", - "--option", "val1,val2,val3", - ]); + .arg(Arg::with_name("option").long("option").takes_value(true)) + .get_matches_from_safe(vec!["", "--option", "val1,val2,val3"]); assert!(m.is_ok()); let m = m.unwrap(); @@ -24,13 +19,8 @@ fn opt_default_no_delim() { #[test] fn opt_eq_no_delim() { let m = App::new("no_delim") - .arg(Arg::with_name("option") - .long("option") - .takes_value(true)) - .get_matches_from_safe(vec![ - "", - "--option=val1,val2,val3", - ]); + .arg(Arg::with_name("option").long("option").takes_value(true)) + .get_matches_from_safe(vec!["", "--option=val1,val2,val3"]); assert!(m.is_ok()); let m = m.unwrap(); @@ -43,13 +33,8 @@ fn opt_eq_no_delim() { #[test] fn opt_s_eq_no_delim() { let m = App::new("no_delim") - .arg(Arg::with_name("option") - .short("o") - .takes_value(true)) - .get_matches_from_safe(vec![ - "", - "-o=val1,val2,val3", - ]); + .arg(Arg::with_name("option").short("o").takes_value(true)) + .get_matches_from_safe(vec!["", "-o=val1,val2,val3"]); assert!(m.is_ok(), "{:?}", m.unwrap_err()); let m = m.unwrap(); @@ -62,13 +47,8 @@ fn opt_s_eq_no_delim() { #[test] fn opt_s_default_no_delim() { let m = App::new("no_delim") - .arg(Arg::with_name("option") - .short("o") - .takes_value(true)) - .get_matches_from_safe(vec![ - "", - "-o", "val1,val2,val3", - ]); + .arg(Arg::with_name("option").short("o").takes_value(true)) + .get_matches_from_safe(vec!["", "-o", "val1,val2,val3"]); assert!(m.is_ok(), "{:?}", m.unwrap_err()); let m = m.unwrap(); @@ -81,13 +61,8 @@ fn opt_s_default_no_delim() { #[test] fn opt_s_no_space_no_delim() { let m = App::new("no_delim") - .arg(Arg::with_name("option") - .short("o") - .takes_value(true)) - .get_matches_from_safe(vec![ - "", - "-o", "val1,val2,val3", - ]); + .arg(Arg::with_name("option").short("o").takes_value(true)) + .get_matches_from_safe(vec!["", "-o", "val1,val2,val3"]); assert!(m.is_ok()); let m = m.unwrap(); @@ -100,14 +75,13 @@ fn opt_s_no_space_no_delim() { #[test] fn opt_s_no_space_mult_no_delim() { let m = App::new("no_delim") - .arg(Arg::with_name("option") - .short("o") - .multiple(true) - .takes_value(true)) - .get_matches_from_safe(vec![ - "", - "-o", "val1,val2,val3", - ]); + .arg( + Arg::with_name("option") + .short("o") + .multiple(true) + .takes_value(true), + ) + .get_matches_from_safe(vec!["", "-o", "val1,val2,val3"]); assert!(m.is_ok()); let m = m.unwrap(); @@ -120,20 +94,22 @@ fn opt_s_no_space_mult_no_delim() { #[test] fn opt_eq_mult_def_delim() { let m = App::new("no_delim") - .arg(Arg::with_name("option") - .long("opt") - .multiple(true) - .use_delimiter(true) - .takes_value(true)) - .get_matches_from_safe(vec![ - "", - "--opt=val1,val2,val3", - ]); + .arg( + Arg::with_name("option") + .long("opt") + .multiple(true) + .use_delimiter(true) + .takes_value(true), + ) + .get_matches_from_safe(vec!["", "--opt=val1,val2,val3"]); assert!(m.is_ok()); let m = m.unwrap(); assert!(m.is_present("option")); assert_eq!(m.occurrences_of("option"), 1); - assert_eq!(m.values_of("option").unwrap().collect::>(), &["val1", "val2", "val3"]); + assert_eq!( + m.values_of("option").unwrap().collect::>(), + &["val1", "val2", "val3"] + ); } diff --git a/tests/derive_order.rs b/tests/derive_order.rs index b30c8ade8a0..438a69121eb 100644 --- a/tests/derive_order.rs +++ b/tests/derive_order.rs @@ -3,7 +3,7 @@ extern crate regex; use std::str; -use clap::{App, Arg, SubCommand, AppSettings}; +use clap::{App, AppSettings, Arg, SubCommand}; include!("../clap-test.rs"); @@ -119,16 +119,25 @@ OPTIONS: #[test] fn no_derive_order() { - let app = App::new("test") - .version("1.2") - .args(&[ - Arg::with_name("flag_b").long("flag_b").help("first flag"), - Arg::with_name("option_b").long("option_b").takes_value(true).help("first option"), - Arg::with_name("flag_a").long("flag_a").help("second flag"), - Arg::with_name("option_a").long("option_a").takes_value(true).help("second option"), - ]); - - assert!(test::compare_output(app, "test --help", NO_DERIVE_ORDER, false)); + let app = App::new("test").version("1.2").args(&[ + Arg::with_name("flag_b").long("flag_b").help("first flag"), + Arg::with_name("option_b") + .long("option_b") + .takes_value(true) + .help("first option"), + Arg::with_name("flag_a").long("flag_a").help("second flag"), + Arg::with_name("option_a") + .long("option_a") + .takes_value(true) + .help("second option"), + ]); + + assert!(test::compare_output( + app, + "test --help", + NO_DERIVE_ORDER, + false + )); } #[test] @@ -138,12 +147,23 @@ fn derive_order() { .version("1.2") .args(&[ Arg::with_name("flag_b").long("flag_b").help("first flag"), - Arg::with_name("option_b").long("option_b").takes_value(true).help("first option"), + Arg::with_name("option_b") + .long("option_b") + .takes_value(true) + .help("first option"), Arg::with_name("flag_a").long("flag_a").help("second flag"), - Arg::with_name("option_a").long("option_a").takes_value(true).help("second option"), + Arg::with_name("option_a") + .long("option_a") + .takes_value(true) + .help("second option"), ]); - assert!(test::compare_output(app, "test --help", DERIVE_ORDER, false)); + assert!(test::compare_output( + app, + "test --help", + DERIVE_ORDER, + false + )); } #[test] @@ -153,12 +173,23 @@ fn unified_help() { .version("1.2") .args(&[ Arg::with_name("flag_b").long("flag_b").help("first flag"), - Arg::with_name("option_b").long("option_b").takes_value(true).help("first option"), + Arg::with_name("option_b") + .long("option_b") + .takes_value(true) + .help("first option"), Arg::with_name("flag_a").long("flag_a").help("second flag"), - Arg::with_name("option_a").long("option_a").takes_value(true).help("second option"), + Arg::with_name("option_a") + .long("option_a") + .takes_value(true) + .help("second option"), ]); - assert!(test::compare_output(app, "test --help", UNIFIED_HELP, false)); + assert!(test::compare_output( + app, + "test --help", + UNIFIED_HELP, + false + )); } #[test] @@ -169,12 +200,23 @@ fn unified_help_and_derive_order() { .version("1.2") .args(&[ Arg::with_name("flag_b").long("flag_b").help("first flag"), - Arg::with_name("option_b").long("option_b").takes_value(true).help("first option"), + Arg::with_name("option_b") + .long("option_b") + .takes_value(true) + .help("first option"), Arg::with_name("flag_a").long("flag_a").help("second flag"), - Arg::with_name("option_a").long("option_a").takes_value(true).help("second option"), + Arg::with_name("option_a") + .long("option_a") + .takes_value(true) + .help("second option"), ]); - assert!(test::compare_output(app, "test --help", UNIFIED_HELP_AND_DERIVE, false)); + assert!(test::compare_output( + app, + "test --help", + UNIFIED_HELP_AND_DERIVE, + false + )); } #[test] @@ -182,32 +224,54 @@ fn derive_order_subcommand_propagate() { let app = App::new("test") .global_setting(AppSettings::DeriveDisplayOrder) .version("1.2") - .subcommand(SubCommand::with_name("sub") - .version("1.2") - .args(&[ + .subcommand( + SubCommand::with_name("sub").version("1.2").args(&[ Arg::with_name("flag_b").long("flag_b").help("first flag"), - Arg::with_name("option_b").long("option_b").takes_value(true).help("first option"), + Arg::with_name("option_b") + .long("option_b") + .takes_value(true) + .help("first option"), Arg::with_name("flag_a").long("flag_a").help("second flag"), - Arg::with_name("option_a").long("option_a").takes_value(true).help("second option"), - ])); - - assert!(test::compare_output(app, "test sub --help", DERIVE_ORDER_SC_PROP, false)); + Arg::with_name("option_a") + .long("option_a") + .takes_value(true) + .help("second option"), + ]), + ); + + assert!(test::compare_output( + app, + "test sub --help", + DERIVE_ORDER_SC_PROP, + false + )); } #[test] fn unified_help_subcommand_propagate() { let app = App::new("test") .global_setting(AppSettings::UnifiedHelpMessage) - .subcommand(SubCommand::with_name("sub") - .version("1.2") - .args(&[ + .subcommand( + SubCommand::with_name("sub").version("1.2").args(&[ Arg::with_name("flag_b").long("flag_b").help("first flag"), - Arg::with_name("option_b").long("option_b").takes_value(true).help("first option"), + Arg::with_name("option_b") + .long("option_b") + .takes_value(true) + .help("first option"), Arg::with_name("flag_a").long("flag_a").help("second flag"), - Arg::with_name("option_a").long("option_a").takes_value(true).help("second option"), - ])); - - assert!(test::compare_output(app, "test sub --help", UNIFIED_SC_PROP, false)); + Arg::with_name("option_a") + .long("option_a") + .takes_value(true) + .help("second option"), + ]), + ); + + assert!(test::compare_output( + app, + "test sub --help", + UNIFIED_SC_PROP, + false + )); } #[test] @@ -215,16 +279,27 @@ fn unified_help_and_derive_order_subcommand_propagate() { let app = App::new("test") .global_setting(AppSettings::DeriveDisplayOrder) .global_setting(AppSettings::UnifiedHelpMessage) - .subcommand(SubCommand::with_name("sub") - .version("1.2") - .args(&[ + .subcommand( + SubCommand::with_name("sub").version("1.2").args(&[ Arg::with_name("flag_b").long("flag_b").help("first flag"), - Arg::with_name("option_b").long("option_b").takes_value(true).help("first option"), + Arg::with_name("option_b") + .long("option_b") + .takes_value(true) + .help("first option"), Arg::with_name("flag_a").long("flag_a").help("second flag"), - Arg::with_name("option_a").long("option_a").takes_value(true).help("second option"), - ])); - - assert!(test::compare_output(app, "test sub --help", UNIFIED_DERIVE_SC_PROP, false)); + Arg::with_name("option_a") + .long("option_a") + .takes_value(true) + .help("second option"), + ]), + ); + + assert!(test::compare_output( + app, + "test sub --help", + UNIFIED_DERIVE_SC_PROP, + false + )); } #[test] @@ -232,14 +307,28 @@ fn unified_help_and_derive_order_subcommand_propagate_with_explicit_display_orde let app = App::new("test") .global_setting(AppSettings::DeriveDisplayOrder) .global_setting(AppSettings::UnifiedHelpMessage) - .subcommand(SubCommand::with_name("sub") - .version("1.2") - .args(&[ + .subcommand( + SubCommand::with_name("sub").version("1.2").args(&[ Arg::with_name("flag_b").long("flag_b").help("first flag"), - Arg::with_name("option_b").long("option_b").takes_value(true).help("first option"), - Arg::with_name("flag_a").long("flag_a").help("second flag").display_order(0), - Arg::with_name("option_a").long("option_a").takes_value(true).help("second option"), - ])); - - assert!(test::compare_output(app, "test sub --help", UNIFIED_DERIVE_SC_PROP_EXPLICIT_ORDER, false)); + Arg::with_name("option_b") + .long("option_b") + .takes_value(true) + .help("first option"), + Arg::with_name("flag_a") + .long("flag_a") + .help("second flag") + .display_order(0), + Arg::with_name("option_a") + .long("option_a") + .takes_value(true) + .help("second option"), + ]), + ); + + assert!(test::compare_output( + app, + "test sub --help", + UNIFIED_DERIVE_SC_PROP_EXPLICIT_ORDER, + false + )); } diff --git a/tests/env.rs b/tests/env.rs index 62833ba0d72..aded47bd8ca 100644 --- a/tests/env.rs +++ b/tests/env.rs @@ -25,9 +25,7 @@ fn env_os() { env::set_var("CLP_TEST_ENV", "env"); let r = App::new("df") - .arg( - Arg::from_usage("[arg] 'some opt'").env_os(OsStr::new("CLP_TEST_ENV")), - ) + .arg(Arg::from_usage("[arg] 'some opt'").env_os(OsStr::new("CLP_TEST_ENV"))) .get_matches_from_safe(vec![""]); assert!(r.is_ok()); @@ -78,9 +76,7 @@ fn opt_user_override() { env::set_var("CLP_TEST_ENV", "env"); let r = App::new("df") - .arg( - Arg::from_usage("--arg [FILE] 'some arg'").env("CLP_TEST_ENV"), - ) + .arg(Arg::from_usage("--arg [FILE] 'some arg'").env("CLP_TEST_ENV")) .get_matches_from_safe(vec!["", "--arg", "opt"]); assert!(r.is_ok()); @@ -204,7 +200,6 @@ fn possible_value() { assert_eq!(m.value_of("arg").unwrap(), "env"); } - #[test] fn not_possible_value() { env::set_var("CLP_TEST_ENV", "env"); @@ -228,10 +223,12 @@ fn validator() { .arg( Arg::from_usage("[arg] 'some opt'") .env("CLP_TEST_ENV") - .validator(|s| if s == "env" { - Ok(()) - } else { - Err("not equal".to_string()) + .validator(|s| { + if s == "env" { + Ok(()) + } else { + Err("not equal".to_string()) + } }), ) .get_matches_from_safe(vec![""]); @@ -251,10 +248,12 @@ fn validator_invalid() { .arg( Arg::from_usage("[arg] 'some opt'") .env("CLP_TEST_ENV") - .validator(|s| if s != "env" { - Ok(()) - } else { - Err("is equal".to_string()) + .validator(|s| { + if s != "env" { + Ok(()) + } else { + Err("is equal".to_string()) + } }), ) .get_matches_from_safe(vec![""]); diff --git a/tests/flags.rs b/tests/flags.rs index 143404ee2db..1068b4df6c9 100644 --- a/tests/flags.rs +++ b/tests/flags.rs @@ -7,8 +7,8 @@ fn flag_using_short() { let m = App::new("flag") .args(&[ Arg::from_usage("-f, --flag 'some flag'"), - Arg::from_usage("-c, --color 'some other flag'") - ]) + Arg::from_usage("-c, --color 'some other flag'"), + ]) .get_matches_from(vec!["", "-f", "-c"]); assert!(m.is_present("flag")); assert!(m.is_present("color")); @@ -17,38 +17,31 @@ fn flag_using_short() { #[test] fn lots_o_flags_sep() { let r = App::new("opts") - .arg( - Arg::from_usage("-o... 'some flag'"), - ) - .get_matches_from_safe(vec!["", - "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", - "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", - "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", - "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", - "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", - "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", - "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", - "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", - "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", - "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", - "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", - "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", - "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", - "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", - "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", - "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", - "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", - "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", - "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", - "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", - "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", - "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", - "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", - "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", - "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", - "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", - "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", - ]); + .arg(Arg::from_usage("-o... 'some flag'")) + .get_matches_from_safe(vec![ + "", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", + "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", + "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", + "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", + "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", + "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", + "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", + "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", + "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", + "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", + "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", + "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", + "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", + "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", + "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", + "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", + "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", + "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", + "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", + "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", + "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", "-o", + "-o", "-o", "-o", + ]); assert!(r.is_ok()); let m = r.unwrap(); assert!(m.is_present("o")); @@ -58,16 +51,15 @@ fn lots_o_flags_sep() { #[test] fn lots_o_flags_combined() { let r = App::new("opts") - .arg( - Arg::from_usage("-o... 'some flag'"), - ) - .get_matches_from_safe(vec!["", + .arg(Arg::from_usage("-o... 'some flag'")) + .get_matches_from_safe(vec![ + "", "-oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo", "-oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo", "-oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo", "-oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo", "-ooooooooooooooooooooooooooooooooooooooooo", - ]); + ]); assert!(r.is_ok()); let m = r.unwrap(); assert!(m.is_present("o")); @@ -79,8 +71,8 @@ fn flag_using_long() { let m = App::new("flag") .args(&[ Arg::from_usage("--flag 'some flag'"), - Arg::from_usage("--color 'some other flag'") - ]) + Arg::from_usage("--color 'some other flag'"), + ]) .get_matches_from(vec!["", "--flag", "--color"]); assert!(m.is_present("flag")); assert!(m.is_present("color")); @@ -91,8 +83,8 @@ fn flag_using_mixed() { let m = App::new("flag") .args(&[ Arg::from_usage("-f, --flag 'some flag'"), - Arg::from_usage("-c, --color 'some other flag'") - ]) + Arg::from_usage("-c, --color 'some other flag'"), + ]) .get_matches_from(vec!["", "-f", "--color"]); assert!(m.is_present("flag")); assert!(m.is_present("color")); @@ -100,8 +92,8 @@ fn flag_using_mixed() { let m = App::new("flag") .args(&[ Arg::from_usage("-f, --flag 'some flag'"), - Arg::from_usage("-c, --color 'some other flag'") - ]) + Arg::from_usage("-c, --color 'some other flag'"), + ]) .get_matches_from(vec!["", "--flag", "-c"]); assert!(m.is_present("flag")); assert!(m.is_present("color")); @@ -113,8 +105,8 @@ fn multiple_flags_in_single() { .args(&[ Arg::from_usage("-f, --flag 'some flag'"), Arg::from_usage("-c, --color 'some other flag'"), - Arg::from_usage("-d, --debug 'another other flag'") - ]) + Arg::from_usage("-d, --debug 'another other flag'"), + ]) .get_matches_from(vec!["", "-fcd"]); assert!(m.is_present("flag")); assert!(m.is_present("color")); @@ -143,5 +135,4 @@ fn short_flag_name_missing() { assert!(!a.is_set(ArgSettings::Multiple)); assert!(a.v.val_names.is_none()); assert!(a.v.num_vals.is_none()); - } diff --git a/tests/global_args.rs b/tests/global_args.rs index 4adc6858206..7b359f7a543 100644 --- a/tests/global_args.rs +++ b/tests/global_args.rs @@ -8,23 +8,22 @@ mod tests { fn get_app() -> App<'static, 'static> { App::new("myprog") - .arg(Arg::with_name("GLOBAL_ARG") - .long("global-arg") - .help( - "Specifies something needed by the subcommands", - ) - .global(true) - .takes_value(true) - .default_value("default_value")) - .arg(Arg::with_name("GLOBAL_FLAG") - .long("global-flag") - .help( - "Specifies something needed by the subcommands", - ) - .multiple(true) - .global(true)) - .subcommand(SubCommand::with_name("outer") - .subcommand(SubCommand::with_name("inner"))) + .arg( + Arg::with_name("GLOBAL_ARG") + .long("global-arg") + .help("Specifies something needed by the subcommands") + .global(true) + .takes_value(true) + .default_value("default_value"), + ) + .arg( + Arg::with_name("GLOBAL_FLAG") + .long("global-flag") + .help("Specifies something needed by the subcommands") + .multiple(true) + .global(true), + ) + .subcommand(SubCommand::with_name("outer").subcommand(SubCommand::with_name("inner"))) } #[test] diff --git a/tests/groups.rs b/tests/groups.rs index bb108eac7c0..c7f39239534 100644 --- a/tests/groups.rs +++ b/tests/groups.rs @@ -13,14 +13,16 @@ USAGE: For more information try --help"; -static REQ_GROUP_CONFLICT_USAGE: &'static str = "error: The argument '' cannot be used with '--delete' +static REQ_GROUP_CONFLICT_USAGE: &'static str = + "error: The argument '' cannot be used with '--delete' USAGE: clap-test For more information try --help"; -static REQ_GROUP_CONFLICT_REV: &'static str = "error: The argument '--delete' cannot be used with 'base' +static REQ_GROUP_CONFLICT_REV: &'static str = + "error: The argument '--delete' cannot be used with 'base' USAGE: clap-test @@ -30,11 +32,15 @@ For more information try --help"; #[test] fn required_group_missing_arg() { let result = App::new("group") - .args_from_usage("-f, --flag 'some flag' - -c, --color 'some other flag'") - .group(ArgGroup::with_name("req") - .args(&["flag", "color"]) - .required(true)) + .args_from_usage( + "-f, --flag 'some flag' + -c, --color 'some other flag'", + ) + .group( + ArgGroup::with_name("req") + .args(&["flag", "color"]) + .required(true), + ) .get_matches_from_safe(vec![""]); assert!(result.is_err()); let err = result.err().unwrap(); @@ -45,11 +51,15 @@ fn required_group_missing_arg() { #[should_panic] fn non_existing_arg() { let _ = App::new("group") - .args_from_usage("-f, --flag 'some flag' - -c, --color 'some other flag'") - .group(ArgGroup::with_name("req") - .args(&["flg", "color"]) - .required(true)) + .args_from_usage( + "-f, --flag 'some flag' + -c, --color 'some other flag'", + ) + .group( + ArgGroup::with_name("req") + .args(&["flg", "color"]) + .required(true), + ) .get_matches_from_safe(vec![""]); } @@ -58,22 +68,19 @@ fn non_existing_arg() { fn non_existing_arg_in_subcommand_help() { let _ = App::new("a") .subcommand( - SubCommand::with_name("b") - .group( - ArgGroup::with_name("c") - .args(&["d"]) - .required(true), - ) - ).get_matches_from_safe(vec!["a", "help", "b"]); + SubCommand::with_name("b").group(ArgGroup::with_name("c").args(&["d"]).required(true)), + ) + .get_matches_from_safe(vec!["a", "help", "b"]); } #[test] fn group_single_value() { let res = App::new("group") - .args_from_usage("-f, --flag 'some flag' - -c, --color [color] 'some option'") - .group(ArgGroup::with_name("grp") - .args(&["flag", "color"])) + .args_from_usage( + "-f, --flag 'some flag' + -c, --color [color] 'some option'", + ) + .group(ArgGroup::with_name("grp").args(&["flag", "color"])) .get_matches_from_safe(vec!["", "-c", "blue"]); assert!(res.is_ok()); @@ -85,10 +92,11 @@ fn group_single_value() { #[test] fn group_single_flag() { let res = App::new("group") - .args_from_usage("-f, --flag 'some flag' - -c, --color [color] 'some option'") - .group(ArgGroup::with_name("grp") - .args(&["flag", "color"])) + .args_from_usage( + "-f, --flag 'some flag' + -c, --color [color] 'some option'", + ) + .group(ArgGroup::with_name("grp").args(&["flag", "color"])) .get_matches_from_safe(vec!["", "-f"]); assert!(res.is_ok()); @@ -100,10 +108,11 @@ fn group_single_flag() { #[test] fn group_empty() { let res = App::new("group") - .args_from_usage("-f, --flag 'some flag' - -c, --color [color] 'some option'") - .group(ArgGroup::with_name("grp") - .args(&["flag", "color"])) + .args_from_usage( + "-f, --flag 'some flag' + -c, --color [color] 'some option'", + ) + .group(ArgGroup::with_name("grp").args(&["flag", "color"])) .get_matches_from_safe(vec![""]); assert!(res.is_ok()); @@ -115,11 +124,15 @@ fn group_empty() { #[test] fn group_reqired_flags_empty() { let result = App::new("group") - .args_from_usage("-f, --flag 'some flag' - -c, --color 'some option'") - .group(ArgGroup::with_name("grp") - .required(true) - .args(&["flag", "color"])) + .args_from_usage( + "-f, --flag 'some flag' + -c, --color 'some option'", + ) + .group( + ArgGroup::with_name("grp") + .required(true) + .args(&["flag", "color"]), + ) .get_matches_from_safe(vec![""]); assert!(result.is_err()); let err = result.err().unwrap(); @@ -129,24 +142,27 @@ fn group_reqired_flags_empty() { #[test] fn group_multi_value_single_arg() { let res = App::new("group") - .args_from_usage("-f, --flag 'some flag' - -c, --color [color]... 'some option'") - .group(ArgGroup::with_name("grp") - .args(&["flag", "color"])) + .args_from_usage( + "-f, --flag 'some flag' + -c, --color [color]... 'some option'", + ) + .group(ArgGroup::with_name("grp").args(&["flag", "color"])) .get_matches_from_safe(vec!["", "-c", "blue", "red", "green"]); assert!(res.is_ok(), "{:?}", res.unwrap_err().kind); let m = res.unwrap(); assert!(m.is_present("grp")); - assert_eq!(&*m.values_of("grp").unwrap().collect::>(), &["blue", "red", "green"]); + assert_eq!( + &*m.values_of("grp").unwrap().collect::>(), + &["blue", "red", "green"] + ); } #[test] fn empty_group() { let r = App::new("empty_group") .arg(Arg::from_usage("-f, --flag 'some flag'")) - .group(ArgGroup::with_name("vers") - .required(true)) + .group(ArgGroup::with_name("vers").required(true)) .get_matches_from_safe(vec!["empty_prog"]); assert!(r.is_err()); let err = r.err().unwrap(); @@ -156,36 +172,59 @@ fn empty_group() { #[test] fn req_group_usage_string() { let app = App::new("req_group") - .args_from_usage("[base] 'Base commit' - -d, --delete 'Remove the base commit information'") - .group(ArgGroup::with_name("base_or_delete") - .args(&["base", "delete"]) - .required(true)); - - assert!(test::compare_output(app, "clap-test", REQ_GROUP_USAGE, true)); + .args_from_usage( + "[base] 'Base commit' + -d, --delete 'Remove the base commit information'", + ) + .group( + ArgGroup::with_name("base_or_delete") + .args(&["base", "delete"]) + .required(true), + ); + + assert!(test::compare_output( + app, + "clap-test", + REQ_GROUP_USAGE, + true + )); } #[test] fn req_group_with_conflict_usage_string() { let app = App::new("req_group") .arg(Arg::from_usage("[base] 'Base commit'").conflicts_with("delete")) - .arg(Arg::from_usage("-d, --delete 'Remove the base commit information'")) - .group(ArgGroup::with_name("base_or_delete") - .args(&["base", "delete"]) - .required(true)); - - assert!(test::compare_output2(app, "clap-test --delete base", REQ_GROUP_CONFLICT_REV, REQ_GROUP_CONFLICT_USAGE, true)); + .arg(Arg::from_usage( + "-d, --delete 'Remove the base commit information'", + )) + .group( + ArgGroup::with_name("base_or_delete") + .args(&["base", "delete"]) + .required(true), + ); + + assert!(test::compare_output2( + app, + "clap-test --delete base", + REQ_GROUP_CONFLICT_REV, + REQ_GROUP_CONFLICT_USAGE, + true + )); } #[test] fn required_group_multiple_args() { let result = App::new("group") - .args_from_usage("-f, --flag 'some flag' - -c, --color 'some other flag'") - .group(ArgGroup::with_name("req") - .args(&["flag", "color"]) - .required(true) - .multiple(true)) + .args_from_usage( + "-f, --flag 'some flag' + -c, --color 'some other flag'", + ) + .group( + ArgGroup::with_name("req") + .args(&["flag", "color"]) + .required(true) + .multiple(true), + ) .get_matches_from_safe(vec!["group", "-f", "-c"]); assert!(result.is_ok()); let m = result.unwrap(); @@ -196,10 +235,11 @@ fn required_group_multiple_args() { #[test] fn group_multiple_args_error() { let result = App::new("group") - .args_from_usage("-f, --flag 'some flag' - -c, --color 'some other flag'") - .group(ArgGroup::with_name("req") - .args(&["flag", "color"])) + .args_from_usage( + "-f, --flag 'some flag' + -c, --color 'some other flag'", + ) + .group(ArgGroup::with_name("req").args(&["flag", "color"])) .get_matches_from_safe(vec!["group", "-f", "-c"]); assert!(result.is_err()); let err = result.unwrap_err(); diff --git a/tests/help.rs b/tests/help.rs index 4b15281f4b9..babfa917734 100644 --- a/tests/help.rs +++ b/tests/help.rs @@ -4,7 +4,7 @@ extern crate regex; include!("../clap-test.rs"); -use clap::{App, AppSettings, SubCommand, ErrorKind, Arg}; +use clap::{App, AppSettings, Arg, ErrorKind, SubCommand}; static REQUIRE_DELIM_HELP: &'static str = "test 1.3 Kevin K. @@ -180,7 +180,6 @@ FLAGS: -h, --help Prints help information -V, --version Prints version information"; - static MULTI_SC_HELP: &'static str = "ctest-subcmd-multi 0.1 Kevin K. tests subcommands @@ -526,8 +525,7 @@ fn setup() -> App<'static, 'static> { #[test] fn help_short() { - let m = setup() - .get_matches_from_safe(vec!["myprog", "-h"]); + let m = setup().get_matches_from_safe(vec!["myprog", "-h"]); assert!(m.is_err()); assert_eq!(m.unwrap_err().kind, ErrorKind::HelpDisplayed); @@ -535,8 +533,7 @@ fn help_short() { #[test] fn help_long() { - let m = setup() - .get_matches_from_safe(vec!["myprog", "--help"]); + let m = setup().get_matches_from_safe(vec!["myprog", "--help"]); assert!(m.is_err()); assert_eq!(m.unwrap_err().kind, ErrorKind::HelpDisplayed); @@ -544,8 +541,7 @@ fn help_long() { #[test] fn help_no_subcommand() { - let m = setup() - .get_matches_from_safe(vec!["myprog", "help"]); + let m = setup().get_matches_from_safe(vec!["myprog", "help"]); assert!(m.is_err()); assert_eq!(m.unwrap_err().kind, ErrorKind::UnknownArgument); @@ -554,9 +550,11 @@ fn help_no_subcommand() { #[test] fn help_subcommand() { let m = setup() - .subcommand(SubCommand::with_name("test") - .about("tests things") - .arg_from_usage("-v --verbose 'with verbosity'")) + .subcommand( + SubCommand::with_name("test") + .about("tests things") + .arg_from_usage("-v --verbose 'with verbosity'"), + ) .get_matches_from_safe(vec!["myprog", "help"]); assert!(m.is_err()); @@ -570,7 +568,12 @@ fn req_last_arg_usage() { (@arg FIRST: ... * "First") (@arg SECOND: ... * +last "Second") ); - assert!(test::compare_output(app, "example --help", LAST_ARG_REQ_MULT, false)); + assert!(test::compare_output( + app, + "example --help", + LAST_ARG_REQ_MULT, + false + )); } #[test] @@ -578,38 +581,48 @@ fn args_with_last_usage() { let app = App::new("flamegraph") .version("0.1") .setting(AppSettings::TrailingVarArg) - .arg(Arg::with_name("verbose") - .help("Prints out more stuff.") - .short("v") - .long("verbose") - .multiple(true) + .arg( + Arg::with_name("verbose") + .help("Prints out more stuff.") + .short("v") + .long("verbose") + .multiple(true), ) - .arg(Arg::with_name("timeout") - .help("Timeout in seconds.") - .short("t") - .long("timeout") - .value_name("SECONDS") - .takes_value(true) + .arg( + Arg::with_name("timeout") + .help("Timeout in seconds.") + .short("t") + .long("timeout") + .value_name("SECONDS") + .takes_value(true), ) - .arg(Arg::with_name("frequency") - .help("The sampling frequency.") - .short("f") - .long("frequency") - .value_name("HERTZ") - .takes_value(true) + .arg( + Arg::with_name("frequency") + .help("The sampling frequency.") + .short("f") + .long("frequency") + .value_name("HERTZ") + .takes_value(true), ) - .arg(Arg::with_name("binary path") - .help("The path of the binary to be profiled. for a binary.") - .takes_value(true) - .value_name("BINFILE") + .arg( + Arg::with_name("binary path") + .help("The path of the binary to be profiled. for a binary.") + .takes_value(true) + .value_name("BINFILE"), ) - .arg(Arg::with_name("pass through args") - .help("Any arguments you wish to pass to the being profiled.") - .value_name("ARGS") - .last(true) - .multiple(true) + .arg( + Arg::with_name("pass through args") + .help("Any arguments you wish to pass to the being profiled.") + .value_name("ARGS") + .last(true) + .multiple(true), ); - assert!(test::compare_output(app, "flamegraph --help", LAST_ARG_USAGE, false)); + assert!(test::compare_output( + app, + "flamegraph --help", + LAST_ARG_USAGE, + false + )); } #[test] @@ -638,7 +651,12 @@ fn subcommand_help_rev() { #[test] fn complex_help_output() { - assert!(test::compare_output(test::complex_app(), "clap-test --help", HELP, false)); + assert!(test::compare_output( + test::complex_app(), + "clap-test --help", + HELP, + false + )); } #[test] @@ -648,83 +666,125 @@ fn after_and_before_help_output() { .about("tests clap library") .before_help("some text that comes before the help") .after_help("some text that comes after the help"); - assert!(test::compare_output(app, "clap-test --help", AFTER_HELP, false)); + assert!(test::compare_output( + app, + "clap-test --help", + AFTER_HELP, + false + )); } #[test] fn multi_level_sc_help() { - let app = App::new("ctest") - .subcommand(SubCommand::with_name("subcmd").subcommand(SubCommand::with_name("multi") - .about("tests subcommands") - .author("Kevin K. ") - .version("0.1") - .args_from_usage(" + let app = App::new("ctest").subcommand( + SubCommand::with_name("subcmd").subcommand( + SubCommand::with_name("multi") + .about("tests subcommands") + .author("Kevin K. ") + .version("0.1") + .args_from_usage( + " -f, --flag 'tests flags' -o, --option [scoption]... 'tests options' - "))); - assert!(test::compare_output(app, "ctest help subcmd multi", MULTI_SC_HELP, false)); + ", + ), + ), + ); + assert!(test::compare_output( + app, + "ctest help subcmd multi", + MULTI_SC_HELP, + false + )); } #[test] fn no_wrap_help() { - let app = App::new("ctest") - .set_term_width(0) - .help(MULTI_SC_HELP); - assert!(test::compare_output(app, "ctest --help", MULTI_SC_HELP, false)); + let app = App::new("ctest").set_term_width(0).help(MULTI_SC_HELP); + assert!(test::compare_output( + app, + "ctest --help", + MULTI_SC_HELP, + false + )); } #[test] fn no_wrap_default_help() { let app = App::new("ctest").version("1.0").set_term_width(0); - assert!(test::compare_output(app, "ctest --help", DEFAULT_HELP, false)); + assert!(test::compare_output( + app, + "ctest --help", + DEFAULT_HELP, + false + )); } #[test] fn complex_subcommand_help_output() { let a = test::complex_app(); - assert!(test::compare_output(a, "clap-test subcmd --help", SC_HELP, false)); + assert!(test::compare_output( + a, + "clap-test subcmd --help", + SC_HELP, + false + )); } - #[test] fn issue_626_unicode_cutoff() { - let app = App::new("ctest") - .version("0.1") - .set_term_width(70) - .arg(Arg::with_name("cafe") + let app = App::new("ctest").version("0.1").set_term_width(70).arg( + Arg::with_name("cafe") .short("c") .long("cafe") .value_name("FILE") - .help("A coffeehouse, coffee shop, or café is an establishment \ + .help( + "A coffeehouse, coffee shop, or café is an establishment \ which primarily serves hot coffee, related coffee beverages \ (e.g., café latte, cappuccino, espresso), tea, and other hot \ beverages. Some coffeehouses also serve cold beverages such as \ iced coffee and iced tea. Many cafés also serve some type of \ - food, such as light snacks, muffins, or pastries.") - .takes_value(true)); - assert!(test::compare_output(app, "ctest --help", ISSUE_626_CUTOFF, false)); + food, such as light snacks, muffins, or pastries.", + ) + .takes_value(true), + ); + assert!(test::compare_output( + app, + "ctest --help", + ISSUE_626_CUTOFF, + false + )); } #[test] fn hide_possible_vals() { let app = App::new("ctest") .version("0.1") - .arg(Arg::with_name("pos") - .short("p") - .long("pos") - .value_name("VAL") - .possible_values(&["fast", "slow"]) - .help("Some vals") - .takes_value(true)) - .arg(Arg::with_name("cafe") - .short("c") - .long("cafe") - .value_name("FILE") - .hide_possible_values(true) - .possible_values(&["fast", "slow"]) - .help("A coffeehouse, coffee shop, or café.") - .takes_value(true)); - assert!(test::compare_output(app, "ctest --help", HIDE_POS_VALS, false)); + .arg( + Arg::with_name("pos") + .short("p") + .long("pos") + .value_name("VAL") + .possible_values(&["fast", "slow"]) + .help("Some vals") + .takes_value(true), + ) + .arg( + Arg::with_name("cafe") + .short("c") + .long("cafe") + .value_name("FILE") + .hide_possible_values(true) + .possible_values(&["fast", "slow"]) + .help("A coffeehouse, coffee shop, or café.") + .takes_value(true), + ); + assert!(test::compare_output( + app, + "ctest --help", + HIDE_POS_VALS, + false + )); } #[test] @@ -740,7 +800,12 @@ fn issue_626_panic() { d'Afrique et d'Asie, dans des plantations qui sont cultivées pour les marchés d'exportation. \ Le café est souvent une contribution majeure aux exportations des régions productrices.") .takes_value(true)); - assert!(test::compare_output(app, "ctest --help", ISSUE_626_PANIC, false)); + assert!(test::compare_output( + app, + "ctest --help", + ISSUE_626_PANIC, + false + )); } #[test] @@ -764,29 +829,45 @@ fn issue_626_variable_panic() { #[test] fn final_word_wrapping() { let app = App::new("ctest").version("0.1").set_term_width(24); - assert!(test::compare_output(app, "ctest --help", FINAL_WORD_WRAPPING, false)); + assert!(test::compare_output( + app, + "ctest --help", + FINAL_WORD_WRAPPING, + false + )); } #[test] fn wrapping_newline_chars() { let app = App::new("ctest") .version("0.1") - .set_term_width(60) - .arg(Arg::with_name("mode") - .help("x, max, maximum 20 characters, contains symbols.{n}\ + .set_term_width(60) + .arg(Arg::with_name("mode").help( + "x, max, maximum 20 characters, contains symbols.{n}\ l, long Copy-friendly, 14 characters, contains symbols.{n}\ - m, med, medium Copy-friendly, 8 characters, contains symbols.{n}")); - assert!(test::compare_output(app, "ctest --help", WRAPPING_NEWLINE_CHARS, false)); + m, med, medium Copy-friendly, 8 characters, contains symbols.{n}", + )); + assert!(test::compare_output( + app, + "ctest --help", + WRAPPING_NEWLINE_CHARS, + false + )); } #[test] fn old_newline_chars() { - let app = App::new("ctest") - .version("0.1") - .arg(Arg::with_name("mode") + let app = App::new("ctest").version("0.1").arg( + Arg::with_name("mode") .short("m") - .help("Some help with some wrapping{n}(Defaults to something)")); - assert!(test::compare_output(app, "ctest --help", OLD_NEWLINE_CHARS, false)); + .help("Some help with some wrapping{n}(Defaults to something)"), + ); + assert!(test::compare_output( + app, + "ctest --help", + OLD_NEWLINE_CHARS, + false + )); } #[test] @@ -834,25 +915,29 @@ fn issue_702_multiple_values() { .author("foo") .about("bar") .arg(Arg::with_name("arg1").help("some option")) - .arg(Arg::with_name("arg2") - .multiple(true) - .help("some option")) - .arg(Arg::with_name("some") - .help("some option") - .short("s") - .long("some") - .takes_value(true)) - .arg(Arg::with_name("other") - .help("some other option") - .short("o") - .long("other") - .takes_value(true)) - .arg(Arg::with_name("label") - .help("a label") - .short("l") - .long("label") - .multiple(true) - .takes_value(true)); + .arg(Arg::with_name("arg2").multiple(true).help("some option")) + .arg( + Arg::with_name("some") + .help("some option") + .short("s") + .long("some") + .takes_value(true), + ) + .arg( + Arg::with_name("other") + .help("some other option") + .short("o") + .long("other") + .takes_value(true), + ) + .arg( + Arg::with_name("label") + .help("a label") + .short("l") + .long("label") + .multiple(true) + .takes_value(true), + ); assert!(test::compare_output(app, "myapp --help", ISSUE_702, false)); } @@ -862,7 +947,9 @@ fn long_about() { .version("1.0") .author("foo") .about("bar") - .long_about("something really really long, with\nmultiple lines of text\nthat should be displayed") + .long_about( + "something really really long, with\nmultiple lines of text\nthat should be displayed", + ) .arg(Arg::with_name("arg1").help("some option")); assert!(test::compare_output(app, "myapp --help", LONG_ABOUT, false)); } @@ -871,29 +958,33 @@ fn long_about() { fn issue_760() { let app = App::new("ctest") .version("0.1") - .arg(Arg::with_name("option") - .help("tests options") - .short("o") - .long("option") - .takes_value(true) - .multiple(true) - .number_of_values(1)) - .arg(Arg::with_name("opt") - .help("tests options") - .short("O") - .long("opt") - .takes_value(true)); + .arg( + Arg::with_name("option") + .help("tests options") + .short("o") + .long("option") + .takes_value(true) + .multiple(true) + .number_of_values(1), + ) + .arg( + Arg::with_name("opt") + .help("tests options") + .short("O") + .long("opt") + .takes_value(true), + ); assert!(test::compare_output(app, "ctest --help", ISSUE_760, false)); } #[test] fn ripgrep_usage() { - let app = App::new("ripgrep") - .version("0.5") - .usage("rg [OPTIONS] [ ...] + let app = App::new("ripgrep").version("0.5").usage( + "rg [OPTIONS] [ ...] rg [OPTIONS] [-e PATTERN | -f FILE ]... [ ...] rg [OPTIONS] --files [ ...] - rg [OPTIONS] --type-list"); + rg [OPTIONS] --type-list", + ); assert!(test::compare_output(app, "rg --help", RIPGREP_USAGE, false)); } @@ -902,18 +993,22 @@ fn ripgrep_usage() { fn ripgrep_usage_using_templates() { let app = App::new("ripgrep") .version("0.5") - .usage(" + .usage( + " rg [OPTIONS] [ ...] rg [OPTIONS] [-e PATTERN | -f FILE ]... [ ...] rg [OPTIONS] --files [ ...] - rg [OPTIONS] --type-list") - .template("\ + rg [OPTIONS] --type-list", + ) + .template( + "\ {bin} {version} USAGE:{usage} FLAGS: -{flags}"); +{flags}", + ); assert!(test::compare_output(app, "rg --help", RIPGREP_USAGE, false)); } @@ -926,15 +1021,22 @@ fn sc_negates_reqs() { .arg_from_usage("-o, --opt 'tests options'") .arg(Arg::with_name("PATH").help("help")) .subcommand(SubCommand::with_name("test")); - assert!(test::compare_output(app, "prog --help", SC_NEGATES_REQS, false)); + assert!(test::compare_output( + app, + "prog --help", + SC_NEGATES_REQS, + false + )); } #[test] fn hidden_args() { let app = App::new("prog") .version("1.0") - .args_from_usage("-f, --flag 'testing flags' - -o, --opt [FILE] 'tests options'") + .args_from_usage( + "-f, --flag 'testing flags' + -o, --opt [FILE] 'tests options'", + ) .arg(Arg::with_name("pos").hidden(true)); assert!(test::compare_output(app, "prog --help", HIDDEN_ARGS, false)); } @@ -944,22 +1046,36 @@ fn args_negate_sc() { let app = App::new("prog") .version("1.0") .setting(AppSettings::ArgsNegateSubcommands) - .args_from_usage("-f, --flag 'testing flags' - -o, --opt [FILE] 'tests options'") + .args_from_usage( + "-f, --flag 'testing flags' + -o, --opt [FILE] 'tests options'", + ) .arg(Arg::with_name("PATH").help("help")) .subcommand(SubCommand::with_name("test")); - assert!(test::compare_output(app, "prog --help", ARGS_NEGATE_SC, false)); + assert!(test::compare_output( + app, + "prog --help", + ARGS_NEGATE_SC, + false + )); } #[test] fn issue_1046_hidden_scs() { let app = App::new("prog") .version("1.0") - .args_from_usage("-f, --flag 'testing flags' - -o, --opt [FILE] 'tests options'") + .args_from_usage( + "-f, --flag 'testing flags' + -o, --opt [FILE] 'tests options'", + ) .arg(Arg::with_name("PATH").help("some")) .subcommand(SubCommand::with_name("test").setting(AppSettings::Hidden)); - assert!(test::compare_output(app, "prog --help", ISSUE_1046_HIDDEN_SCS, false)); + assert!(test::compare_output( + app, + "prog --help", + ISSUE_1046_HIDDEN_SCS, + false + )); } #[test] @@ -982,74 +1098,118 @@ fn customize_version_and_help() { .help_message("Print help information") .version_short("v") .version_message("Print version information"); - assert!(test::compare_output(app, "customize --help", CUSTOM_VERSION_AND_HELP, false)); + assert!(test::compare_output( + app, + "customize --help", + CUSTOM_VERSION_AND_HELP, + false + )); } #[test] fn last_arg_mult_usage() { let app = App::new("last") - .version("0.1") - .arg(Arg::with_name("TARGET").required(true).help("some")) - .arg(Arg::with_name("CORPUS").help("some")) - .arg(Arg::with_name("ARGS").multiple(true).last(true).help("some")); + .version("0.1") + .arg(Arg::with_name("TARGET").required(true).help("some")) + .arg(Arg::with_name("CORPUS").help("some")) + .arg( + Arg::with_name("ARGS") + .multiple(true) + .last(true) + .help("some"), + ); assert!(test::compare_output(app, "last --help", LAST_ARG, false)); } #[test] fn last_arg_mult_usage_req() { let app = App::new("last") - .version("0.1") - .arg(Arg::with_name("TARGET").required(true).help("some")) - .arg(Arg::with_name("CORPUS").help("some")) - .arg(Arg::with_name("ARGS").multiple(true).last(true).required(true).help("some")); - assert!(test::compare_output(app, "last --help", LAST_ARG_REQ, false)); + .version("0.1") + .arg(Arg::with_name("TARGET").required(true).help("some")) + .arg(Arg::with_name("CORPUS").help("some")) + .arg( + Arg::with_name("ARGS") + .multiple(true) + .last(true) + .required(true) + .help("some"), + ); + assert!(test::compare_output( + app, + "last --help", + LAST_ARG_REQ, + false + )); } #[test] fn last_arg_mult_usage_req_with_sc() { let app = App::new("last") - .version("0.1") - .setting(AppSettings::SubcommandsNegateReqs) - .arg(Arg::with_name("TARGET").required(true).help("some")) - .arg(Arg::with_name("CORPUS").help("some")) - .arg(Arg::with_name("ARGS").multiple(true).last(true).required(true).help("some")) - .subcommand(SubCommand::with_name("test").about("some")); - assert!(test::compare_output(app, "last --help", LAST_ARG_REQ_SC, false)); + .version("0.1") + .setting(AppSettings::SubcommandsNegateReqs) + .arg(Arg::with_name("TARGET").required(true).help("some")) + .arg(Arg::with_name("CORPUS").help("some")) + .arg( + Arg::with_name("ARGS") + .multiple(true) + .last(true) + .required(true) + .help("some"), + ) + .subcommand(SubCommand::with_name("test").about("some")); + assert!(test::compare_output( + app, + "last --help", + LAST_ARG_REQ_SC, + false + )); } #[test] fn last_arg_mult_usage_with_sc() { let app = App::new("last") - .version("0.1") - .setting(AppSettings::ArgsNegateSubcommands) - .arg(Arg::with_name("TARGET").required(true).help("some")) - .arg(Arg::with_name("CORPUS").help("some")) - .arg(Arg::with_name("ARGS").multiple(true).last(true).help("some")) - .subcommand(SubCommand::with_name("test").about("some")); + .version("0.1") + .setting(AppSettings::ArgsNegateSubcommands) + .arg(Arg::with_name("TARGET").required(true).help("some")) + .arg(Arg::with_name("CORPUS").help("some")) + .arg( + Arg::with_name("ARGS") + .multiple(true) + .last(true) + .help("some"), + ) + .subcommand(SubCommand::with_name("test").about("some")); assert!(test::compare_output(app, "last --help", LAST_ARG_SC, false)); } - #[test] fn hidden_default_val() { - let app1 = App::new("default") - .version("0.1") - .set_term_width(120) - .arg(Arg::with_name("argument") - .help("Pass an argument to the program. [default: default-argument]") - .long("arg") - .default_value("default-argument") - .hide_default_value(true)); - assert!(test::compare_output(app1, "default --help", HIDE_DEFAULT_VAL, false)); - - let app2 = App::new("default") - .version("0.1") - .set_term_width(120) - .arg(Arg::with_name("argument") - .help("Pass an argument to the program.") - .long("arg") - .default_value("default-argument")); - assert!(test::compare_output(app2, "default --help", HIDE_DEFAULT_VAL, false)); + let app1 = App::new("default").version("0.1").set_term_width(120).arg( + Arg::with_name("argument") + .help("Pass an argument to the program. [default: default-argument]") + .long("arg") + .default_value("default-argument") + .hide_default_value(true), + ); + assert!(test::compare_output( + app1, + "default --help", + HIDE_DEFAULT_VAL, + false + )); + + let app2 = App::new("default").version("0.1").set_term_width(120).arg( + Arg::with_name("argument") + .help("Pass an argument to the program.") + .long("arg") + .default_value("default-argument"), + ); + assert!(test::compare_output( + app2, + "default --help", + HIDE_DEFAULT_VAL, + false + )); } fn issue_1112_setup() -> App<'static, 'static> { @@ -1058,14 +1218,12 @@ fn issue_1112_setup() -> App<'static, 'static> { .about("tests stuff") .version("1.3") .arg(Arg::from_usage("-h, --help 'some help'")) - .subcommand(SubCommand::with_name("foo") - .arg(Arg::from_usage("-h, --help 'some help'"))) + .subcommand(SubCommand::with_name("foo").arg(Arg::from_usage("-h, --help 'some help'"))) } #[test] fn issue_1112_override_help_long() { - let m = issue_1112_setup() - .get_matches_from_safe(vec!["test", "--help"]); + let m = issue_1112_setup().get_matches_from_safe(vec!["test", "--help"]); assert!(m.is_ok()); assert!(m.unwrap().is_present("help")); @@ -1073,8 +1231,7 @@ fn issue_1112_override_help_long() { #[test] fn issue_1112_override_help_short() { - let m = issue_1112_setup() - .get_matches_from_safe(vec!["test", "-h"]); + let m = issue_1112_setup().get_matches_from_safe(vec!["test", "-h"]); assert!(m.is_ok()); assert!(m.unwrap().is_present("help")); @@ -1082,20 +1239,26 @@ fn issue_1112_override_help_short() { #[test] fn issue_1112_override_help_subcmd_long() { - let m = issue_1112_setup() - .get_matches_from_safe(vec!["test", "foo", "--help"]); + let m = issue_1112_setup().get_matches_from_safe(vec!["test", "foo", "--help"]); assert!(m.is_ok()); - assert!(m.unwrap().subcommand_matches("foo").unwrap().is_present("help")); + assert!(m + .unwrap() + .subcommand_matches("foo") + .unwrap() + .is_present("help")); } #[test] fn issue_1112_override_help_subcmd_short() { - let m = issue_1112_setup() - .get_matches_from_safe(vec!["test", "foo", "-h"]); + let m = issue_1112_setup().get_matches_from_safe(vec!["test", "foo", "-h"]); assert!(m.is_ok()); - assert!(m.unwrap().subcommand_matches("foo").unwrap().is_present("help")); + assert!(m + .unwrap() + .subcommand_matches("foo") + .unwrap() + .is_present("help")); } #[test] @@ -1104,9 +1267,18 @@ fn issue_1052_require_delim_help() { .author("Kevin K.") .about("tests stuff") .version("1.3") - .arg(Arg::from_usage("-f, --fake 'some help'").require_delimiter(true).value_delimiter(":")); + .arg( + Arg::from_usage("-f, --fake 'some help'") + .require_delimiter(true) + .value_delimiter(":"), + ); - assert!(test::compare_output(app, "test --help", REQUIRE_DELIM_HELP, false)); + assert!(test::compare_output( + app, + "test --help", + REQUIRE_DELIM_HELP, + false + )); } #[test] @@ -1116,22 +1288,31 @@ fn hide_env_vals() { env::set_var("ENVVAR", "MYVAL"); let app = App::new("ctest") .version("0.1") - .arg(Arg::with_name("pos") - .short("p") - .long("pos") - .value_name("VAL") - .possible_values(&["fast", "slow"]) - .help("Some vals") - .takes_value(true)) - .arg(Arg::with_name("cafe") - .short("c") - .long("cafe") - .value_name("FILE") - .hide_env_values(true) - .env("ENVVAR") - .help("A coffeehouse, coffee shop, or café.") - .takes_value(true)); - assert!(test::compare_output(app, "ctest --help", HIDE_ENV_VALS, false)); + .arg( + Arg::with_name("pos") + .short("p") + .long("pos") + .value_name("VAL") + .possible_values(&["fast", "slow"]) + .help("Some vals") + .takes_value(true), + ) + .arg( + Arg::with_name("cafe") + .short("c") + .long("cafe") + .value_name("FILE") + .hide_env_values(true) + .env("ENVVAR") + .help("A coffeehouse, coffee shop, or café.") + .takes_value(true), + ); + assert!(test::compare_output( + app, + "ctest --help", + HIDE_ENV_VALS, + false + )); } #[test] @@ -1141,22 +1322,31 @@ fn show_env_vals() { env::set_var("ENVVAR", "MYVAL"); let app = App::new("ctest") .version("0.1") - .arg(Arg::with_name("pos") - .short("p") - .long("pos") - .value_name("VAL") - .possible_values(&["fast", "slow"]) - .help("Some vals") - .takes_value(true)) - .arg(Arg::with_name("cafe") - .short("c") - .long("cafe") - .value_name("FILE") - .hide_possible_values(true) - .env("ENVVAR") - .help("A coffeehouse, coffee shop, or café.") - .takes_value(true)); - assert!(test::compare_output(app, "ctest --help", SHOW_ENV_VALS, false)); + .arg( + Arg::with_name("pos") + .short("p") + .long("pos") + .value_name("VAL") + .possible_values(&["fast", "slow"]) + .help("Some vals") + .takes_value(true), + ) + .arg( + Arg::with_name("cafe") + .short("c") + .long("cafe") + .value_name("FILE") + .hide_possible_values(true) + .env("ENVVAR") + .help("A coffeehouse, coffee shop, or café.") + .takes_value(true), + ); + assert!(test::compare_output( + app, + "ctest --help", + SHOW_ENV_VALS, + false + )); } static ISSUE_897: &'static str = "ctest-foo 0.1 @@ -1174,13 +1364,18 @@ FLAGS: #[test] fn show_long_about_issue_897() { - let app = App::new("ctest") - .version("0.1") - .subcommand(SubCommand::with_name("foo") + let app = App::new("ctest").version("0.1").subcommand( + SubCommand::with_name("foo") .version("0.1") .about("About foo") - .long_about("Long about foo")); - assert!(test::compare_output(app, "ctest foo --help", ISSUE_897, false)); + .long_about("Long about foo"), + ); + assert!(test::compare_output( + app, + "ctest foo --help", + ISSUE_897, + false + )); } static ISSUE_897_SHORT: &'static str = "ctest-foo 0.1 @@ -1195,11 +1390,16 @@ FLAGS: #[test] fn show_short_about_issue_897() { - let app = App::new("ctest") - .version("0.1") - .subcommand(SubCommand::with_name("foo") + let app = App::new("ctest").version("0.1").subcommand( + SubCommand::with_name("foo") .version("0.1") .about("About foo") - .long_about("Long about foo")); - assert!(test::compare_output(app, "ctest foo -h", ISSUE_897_SHORT, false)); + .long_about("Long about foo"), + ); + assert!(test::compare_output( + app, + "ctest foo -h", + ISSUE_897_SHORT, + false + )); } diff --git a/tests/hidden_args.rs b/tests/hidden_args.rs index 635e25e2ae5..39ea5eae899 100644 --- a/tests/hidden_args.rs +++ b/tests/hidden_args.rs @@ -26,10 +26,12 @@ fn hidden_args() { .author("Kevin K.") .about("tests stuff") .version("1.4") - .args(&[Arg::from_usage("-f, --flag 'some flag'").hidden(true), - Arg::from_usage("-F, --flag2 'some other flag'"), - Arg::from_usage("--option [opt] 'some option'"), - Arg::with_name("DUMMY").required(false).hidden(true)]); + .args(&[ + Arg::from_usage("-f, --flag 'some flag'").hidden(true), + Arg::from_usage("-F, --flag2 'some other flag'"), + Arg::from_usage("--option [opt] 'some option'"), + Arg::with_name("DUMMY").required(false).hidden(true), + ]); assert!(test::compare_output(app, "test --help", HIDDEN_ARGS, false)); } @@ -77,13 +79,19 @@ fn hidden_short_args() { .short("c") .long("config") .hidden_short_help(true) - .help("Some help text describing the --config arg"), + .help("Some help text describing the --config arg"), Arg::with_name("visible") .short("v") .long("visible") - .help("This text should be visible")]); - - assert!(test::compare_output(app, "test -h", HIDDEN_SHORT_ARGS, false)); + .help("This text should be visible"), + ]); + + assert!(test::compare_output( + app, + "test -h", + HIDDEN_SHORT_ARGS, + false + )); } /// Ensure visible with opposite option @@ -98,13 +106,19 @@ fn hidden_short_args_long_help() { .short("c") .long("config") .hidden_short_help(true) - .help("Some help text describing the --config arg"), + .help("Some help text describing the --config arg"), Arg::with_name("visible") .short("v") .long("visible") - .help("This text should be visible")]); - - assert!(test::compare_output(app, "test --help", HIDDEN_SHORT_ARGS_LONG_HELP, false)); + .help("This text should be visible"), + ]); + + assert!(test::compare_output( + app, + "test --help", + HIDDEN_SHORT_ARGS_LONG_HELP, + false + )); } static HIDDEN_LONG_ARGS: &'static str = "test 2.31.2 @@ -135,13 +149,19 @@ fn hidden_long_args() { .short("c") .long("config") .hidden_long_help(true) - .help("Some help text describing the --config arg"), + .help("Some help text describing the --config arg"), Arg::with_name("visible") .short("v") .long("visible") - .help("This text should be visible")]); - - assert!(test::compare_output(app, "test --help", HIDDEN_LONG_ARGS, false)); + .help("This text should be visible"), + ]); + + assert!(test::compare_output( + app, + "test --help", + HIDDEN_LONG_ARGS, + false + )); } static HIDDEN_LONG_ARGS_SHORT_HELP: &'static str = "test 2.31.2 @@ -168,11 +188,17 @@ fn hidden_long_args_short_help() { .short("c") .long("config") .hidden_long_help(true) - .help("Some help text describing the --config arg"), + .help("Some help text describing the --config arg"), Arg::with_name("visible") .short("v") .long("visible") - .help("This text should be visible")]); - - assert!(test::compare_output(app, "test -h", HIDDEN_LONG_ARGS_SHORT_HELP, false)); + .help("This text should be visible"), + ]); + + assert!(test::compare_output( + app, + "test -h", + HIDDEN_LONG_ARGS_SHORT_HELP, + false + )); } diff --git a/tests/indices.rs b/tests/indices.rs index 910529ec754..9be4c0ef217 100644 --- a/tests/indices.rs +++ b/tests/indices.rs @@ -7,168 +7,187 @@ use clap::{App, Arg}; #[test] fn indices_mult_opts() { - let m = App::new("ind") - .arg(Arg::with_name("exclude") - .short("e") - .takes_value(true) - .multiple(true)) - .arg(Arg::with_name("include") - .short("i") - .takes_value(true) - .multiple(true)) - .get_matches_from(vec!["ind", "-e", "A", "B", "-i", "B", "C", "-e", "C"]); - - assert_eq!(m.indices_of("exclude").unwrap().collect::>(), &[2, 3, 8]); - assert_eq!(m.indices_of("include").unwrap().collect::>(), &[5, 6]); + let m = App::new("ind") + .arg( + Arg::with_name("exclude") + .short("e") + .takes_value(true) + .multiple(true), + ) + .arg( + Arg::with_name("include") + .short("i") + .takes_value(true) + .multiple(true), + ) + .get_matches_from(vec!["ind", "-e", "A", "B", "-i", "B", "C", "-e", "C"]); + + assert_eq!( + m.indices_of("exclude").unwrap().collect::>(), + &[2, 3, 8] + ); + assert_eq!( + m.indices_of("include").unwrap().collect::>(), + &[5, 6] + ); } #[test] fn index_mult_opts() { - let m = App::new("ind") - .arg(Arg::with_name("exclude") - .short("e") - .takes_value(true) - .multiple(true)) - .arg(Arg::with_name("include") - .short("i") - .takes_value(true) - .multiple(true)) - .get_matches_from(vec!["ind", "-e", "A", "B", "-i", "B", "C", "-e", "C"]); - - assert_eq!(m.index_of("exclude"), Some(2)); - assert_eq!(m.index_of("include"), Some(5)); + let m = App::new("ind") + .arg( + Arg::with_name("exclude") + .short("e") + .takes_value(true) + .multiple(true), + ) + .arg( + Arg::with_name("include") + .short("i") + .takes_value(true) + .multiple(true), + ) + .get_matches_from(vec!["ind", "-e", "A", "B", "-i", "B", "C", "-e", "C"]); + + assert_eq!(m.index_of("exclude"), Some(2)); + assert_eq!(m.index_of("include"), Some(5)); } #[test] fn index_flag() { - let m = App::new("ind") - .arg(Arg::with_name("exclude") - .short("e")) - .arg(Arg::with_name("include") - .short("i")) - .get_matches_from(vec!["ind", "-e", "-i"]); - - assert_eq!(m.index_of("exclude"), Some(1)); - assert_eq!(m.index_of("include"), Some(2)); + let m = App::new("ind") + .arg(Arg::with_name("exclude").short("e")) + .arg(Arg::with_name("include").short("i")) + .get_matches_from(vec!["ind", "-e", "-i"]); + + assert_eq!(m.index_of("exclude"), Some(1)); + assert_eq!(m.index_of("include"), Some(2)); } #[test] fn index_flags() { - let m = App::new("ind") - .arg(Arg::with_name("exclude") - .short("e") - .multiple(true)) - .arg(Arg::with_name("include") - .short("i") - .multiple(true)) - .get_matches_from(vec!["ind", "-e", "-i", "-e", "-e", "-i"]); - - assert_eq!(m.index_of("exclude"), Some(1)); - assert_eq!(m.index_of("include"), Some(2)); + let m = App::new("ind") + .arg(Arg::with_name("exclude").short("e").multiple(true)) + .arg(Arg::with_name("include").short("i").multiple(true)) + .get_matches_from(vec!["ind", "-e", "-i", "-e", "-e", "-i"]); + + assert_eq!(m.index_of("exclude"), Some(1)); + assert_eq!(m.index_of("include"), Some(2)); } #[test] fn indices_mult_flags() { - let m = App::new("ind") - .arg(Arg::with_name("exclude") - .short("e") - .multiple(true)) - .arg(Arg::with_name("include") - .short("i") - .multiple(true)) - .get_matches_from(vec!["ind", "-e", "-i", "-e", "-e", "-i"]); - - assert_eq!(m.indices_of("exclude").unwrap().collect::>(), &[1, 3, 4]); - assert_eq!(m.indices_of("include").unwrap().collect::>(), &[2, 5]); + let m = App::new("ind") + .arg(Arg::with_name("exclude").short("e").multiple(true)) + .arg(Arg::with_name("include").short("i").multiple(true)) + .get_matches_from(vec!["ind", "-e", "-i", "-e", "-e", "-i"]); + + assert_eq!( + m.indices_of("exclude").unwrap().collect::>(), + &[1, 3, 4] + ); + assert_eq!( + m.indices_of("include").unwrap().collect::>(), + &[2, 5] + ); } #[test] fn indices_mult_flags_combined() { - let m = App::new("ind") - .arg(Arg::with_name("exclude") - .short("e") - .multiple(true)) - .arg(Arg::with_name("include") - .short("i") - .multiple(true)) - .get_matches_from(vec!["ind", "-eieei"]); - - assert_eq!(m.indices_of("exclude").unwrap().collect::>(), &[1, 3, 4]); - assert_eq!(m.indices_of("include").unwrap().collect::>(), &[2, 5]); + let m = App::new("ind") + .arg(Arg::with_name("exclude").short("e").multiple(true)) + .arg(Arg::with_name("include").short("i").multiple(true)) + .get_matches_from(vec!["ind", "-eieei"]); + + assert_eq!( + m.indices_of("exclude").unwrap().collect::>(), + &[1, 3, 4] + ); + assert_eq!( + m.indices_of("include").unwrap().collect::>(), + &[2, 5] + ); } #[test] fn indices_mult_flags_opt_combined() { - let m = App::new("ind") - .arg(Arg::with_name("exclude") - .short("e") - .multiple(true)) - .arg(Arg::with_name("include") - .short("i") - .multiple(true)) - .arg(Arg::with_name("option") - .short("o") - .takes_value(true)) - .get_matches_from(vec!["ind", "-eieeio", "val"]); - - assert_eq!(m.indices_of("exclude").unwrap().collect::>(), &[1, 3, 4]); - assert_eq!(m.indices_of("include").unwrap().collect::>(), &[2, 5]); - assert_eq!(m.indices_of("option").unwrap().collect::>(), &[7]); + let m = App::new("ind") + .arg(Arg::with_name("exclude").short("e").multiple(true)) + .arg(Arg::with_name("include").short("i").multiple(true)) + .arg(Arg::with_name("option").short("o").takes_value(true)) + .get_matches_from(vec!["ind", "-eieeio", "val"]); + + assert_eq!( + m.indices_of("exclude").unwrap().collect::>(), + &[1, 3, 4] + ); + assert_eq!( + m.indices_of("include").unwrap().collect::>(), + &[2, 5] + ); + assert_eq!(m.indices_of("option").unwrap().collect::>(), &[7]); } #[test] fn indices_mult_flags_opt_combined_eq() { - let m = App::new("ind") - .arg(Arg::with_name("exclude") - .short("e") - .multiple(true)) - .arg(Arg::with_name("include") - .short("i") - .multiple(true)) - .arg(Arg::with_name("option") - .short("o") - .takes_value(true)) - .get_matches_from(vec!["ind", "-eieeio=val"]); - - assert_eq!(m.indices_of("exclude").unwrap().collect::>(), &[1, 3, 4]); - assert_eq!(m.indices_of("include").unwrap().collect::>(), &[2, 5]); - assert_eq!(m.indices_of("option").unwrap().collect::>(), &[7]); + let m = App::new("ind") + .arg(Arg::with_name("exclude").short("e").multiple(true)) + .arg(Arg::with_name("include").short("i").multiple(true)) + .arg(Arg::with_name("option").short("o").takes_value(true)) + .get_matches_from(vec!["ind", "-eieeio=val"]); + + assert_eq!( + m.indices_of("exclude").unwrap().collect::>(), + &[1, 3, 4] + ); + assert_eq!( + m.indices_of("include").unwrap().collect::>(), + &[2, 5] + ); + assert_eq!(m.indices_of("option").unwrap().collect::>(), &[7]); } #[test] fn indices_mult_opt_value_delim_eq() { let m = App::new("myapp") - .arg(Arg::with_name("option") - .short("o") - .takes_value(true) - .use_delimiter(true) - .multiple(true)) - .get_matches_from(vec!["myapp", "-o=val1,val2,val3"]); - assert_eq!(m.indices_of("option").unwrap().collect::>(), &[2, 3, 4]); + .arg( + Arg::with_name("option") + .short("o") + .takes_value(true) + .use_delimiter(true) + .multiple(true), + ) + .get_matches_from(vec!["myapp", "-o=val1,val2,val3"]); + assert_eq!( + m.indices_of("option").unwrap().collect::>(), + &[2, 3, 4] + ); } #[test] fn indices_mult_opt_value_no_delim_eq() { let m = App::new("myapp") - .arg(Arg::with_name("option") - .short("o") - .takes_value(true) - .multiple(true)) - .get_matches_from(vec!["myapp", "-o=val1,val2,val3"]); + .arg( + Arg::with_name("option") + .short("o") + .takes_value(true) + .multiple(true), + ) + .get_matches_from(vec!["myapp", "-o=val1,val2,val3"]); assert_eq!(m.indices_of("option").unwrap().collect::>(), &[2]); } #[test] fn indices_mult_opt_mult_flag() { let m = App::new("myapp") - .arg(Arg::with_name("option") - .short("o") - .takes_value(true) - .multiple(true)) - .arg(Arg::with_name("flag") - .short("f") - .multiple(true)) - .get_matches_from(vec!["myapp", "-o", "val1", "-f", "-o", "val2", "-f"]); + .arg( + Arg::with_name("option") + .short("o") + .takes_value(true) + .multiple(true), + ) + .arg(Arg::with_name("flag").short("f").multiple(true)) + .get_matches_from(vec!["myapp", "-o", "val1", "-f", "-o", "val2", "-f"]); assert_eq!(m.indices_of("option").unwrap().collect::>(), &[2, 5]); assert_eq!(m.indices_of("flag").unwrap().collect::>(), &[3, 6]); diff --git a/tests/macros.rs b/tests/macros.rs index 0cdcb527639..368aa33d1b8 100755 --- a/tests/macros.rs +++ b/tests/macros.rs @@ -71,7 +71,8 @@ fn quoted_app_name() { assert_eq!(app.p.meta.name, "app name with spaces-and-hyphens"); let mut help_text = vec![]; - app.write_help(&mut help_text).expect("Could not write help text."); + app.write_help(&mut help_text) + .expect("Could not write help text."); let help_text = String::from_utf8(help_text).expect("Help text is not valid utf-8"); assert!(help_text.starts_with("app name with spaces-and-hyphens 0.1\n")); } @@ -108,7 +109,8 @@ fn quoted_arg_long_name() { (@arg scpositional: index(1) "tests positionals")) ); - let matches = app.get_matches_from_safe(vec!["bin_name", "value1", "value2", "--long-option-2"]) + let matches = app + .get_matches_from_safe(vec!["bin_name", "value1", "value2", "--long-option-2"]) .expect("Expected to successfully match the given args."); assert!(matches.is_present("option2")); } @@ -145,7 +147,8 @@ fn quoted_arg_name() { (@arg scpositional: index(1) "tests positionals")) ); - let matches = app.get_matches_from_safe(vec!["bin_name", "value1", "value2", "--long-option-2"]) + let matches = app + .get_matches_from_safe(vec!["bin_name", "value1", "value2", "--long-option-2"]) .expect("Expected to successfully match the given args."); assert!(matches.is_present("option2")); } @@ -251,16 +254,18 @@ fn group_macro_set_not_required() { #[test] fn multiarg() { - let app = || clap_app!( - claptests => - (@arg flag: --flag "value") - (@arg multiarg: --multiarg - default_value("flag-unset") default_value_if("flag", None, "flag-set") - "multiarg") - (@arg multiarg2: --multiarg2 - default_value("flag-unset") default_value_if("flag", None, "flag-set",) - "multiarg2") - ); + let app = || { + clap_app!( + claptests => + (@arg flag: --flag "value") + (@arg multiarg: --multiarg + default_value("flag-unset") default_value_if("flag", None, "flag-set") + "multiarg") + (@arg multiarg2: --multiarg2 + default_value("flag-unset") default_value_if("flag", None, "flag-set",) + "multiarg2") + ) + }; let matches = app() .get_matches_from_safe(vec!["bin_name"]) @@ -313,7 +318,7 @@ fn arg_enum() { // Tests for each pattern // meta NO, pub NO, trailing comma NO - test_greek_no_meta!{ + test_greek_no_meta! { arg_enum!{ enum Greek { Alpha, @@ -322,7 +327,7 @@ fn arg_enum() { } }; // meta NO, pub NO, trailing comma YES - test_greek_no_meta!{ + test_greek_no_meta! { arg_enum!{ enum Greek { Alpha, @@ -331,7 +336,7 @@ fn arg_enum() { } }; // meta NO, pub YES, trailing comma NO - test_greek_no_meta!{ + test_greek_no_meta! { arg_enum!{ pub enum Greek { Alpha, @@ -340,7 +345,7 @@ fn arg_enum() { } }; // meta NO, pub YES, trailing comma YES - test_greek_no_meta!{ + test_greek_no_meta! { arg_enum!{ pub enum Greek { Alpha, @@ -349,7 +354,7 @@ fn arg_enum() { } }; // meta YES, pub NO, trailing comma NO - test_greek_meta!{ + test_greek_meta! { arg_enum!{ #[derive(Debug, PartialEq, Copy, Clone)] enum Greek { @@ -359,7 +364,7 @@ fn arg_enum() { } }; // meta YES, pub NO, trailing comma YES - test_greek_meta!{ + test_greek_meta! { arg_enum!{ #[derive(Debug, PartialEq, Copy, Clone)] enum Greek { @@ -369,7 +374,7 @@ fn arg_enum() { } }; // meta YES, pub YES, trailing comma NO - test_greek_meta!{ + test_greek_meta! { arg_enum!{ #[derive(Debug, PartialEq, Copy, Clone)] pub enum Greek { @@ -379,7 +384,7 @@ fn arg_enum() { } }; // meta YES, pub YES, trailing comma YES - test_greek_meta!{ + test_greek_meta! { arg_enum!{ #[derive(Debug, PartialEq, Copy, Clone)] pub enum Greek { diff --git a/tests/multiple_occurrences.rs b/tests/multiple_occurrences.rs index 2f92fb1d941..4bbd1b287f7 100644 --- a/tests/multiple_occurrences.rs +++ b/tests/multiple_occurrences.rs @@ -5,15 +5,9 @@ use clap::{App, Arg}; #[test] fn multiple_occurrences_of_flags_long() { let m = App::new("mo_flags_long") - .arg(Arg::from_usage("--multflag 'allowed multiple flag'") - .multiple(true)) - .arg(Arg::from_usage("--flag 'disallowed multiple flag'")) - .get_matches_from(vec![ - "", - "--multflag", - "--flag", - "--multflag" - ]); + .arg(Arg::from_usage("--multflag 'allowed multiple flag'").multiple(true)) + .arg(Arg::from_usage("--flag 'disallowed multiple flag'")) + .get_matches_from(vec!["", "--multflag", "--flag", "--multflag"]); assert!(m.is_present("multflag")); assert_eq!(m.occurrences_of("multflag"), 2); assert!(m.is_present("flag")); @@ -23,15 +17,9 @@ fn multiple_occurrences_of_flags_long() { #[test] fn multiple_occurrences_of_flags_short() { let m = App::new("mo_flags_short") - .arg(Arg::from_usage("-m --multflag 'allowed multiple flag'") - .multiple(true)) - .arg(Arg::from_usage("-f --flag 'disallowed multiple flag'")) - .get_matches_from(vec![ - "", - "-m", - "-f", - "-m" - ]); + .arg(Arg::from_usage("-m --multflag 'allowed multiple flag'").multiple(true)) + .arg(Arg::from_usage("-f --flag 'disallowed multiple flag'")) + .get_matches_from(vec!["", "-m", "-f", "-m"]); assert!(m.is_present("multflag")); assert_eq!(m.occurrences_of("multflag"), 2); assert!(m.is_present("flag")); @@ -41,20 +29,18 @@ fn multiple_occurrences_of_flags_short() { #[test] fn multiple_occurrences_of_flags_mixed() { let m = App::new("mo_flags_mixed") - .arg(Arg::from_usage("-m, --multflag1 'allowed multiple flag'") - .multiple(true)) - .arg(Arg::from_usage("-n, --multflag2 'another allowed multiple flag'") - .multiple(true)) - .arg(Arg::from_usage("-f, --flag 'disallowed multiple flag'")) - .get_matches_from(vec![ - "", - "-m", - "-f", - "-n", - "--multflag1", - "-m", - "--multflag2" - ]); + .arg(Arg::from_usage("-m, --multflag1 'allowed multiple flag'").multiple(true)) + .arg(Arg::from_usage("-n, --multflag2 'another allowed multiple flag'").multiple(true)) + .arg(Arg::from_usage("-f, --flag 'disallowed multiple flag'")) + .get_matches_from(vec![ + "", + "-m", + "-f", + "-n", + "--multflag1", + "-m", + "--multflag2", + ]); assert!(m.is_present("multflag1")); assert_eq!(m.occurrences_of("multflag1"), 3); assert!(m.is_present("multflag2")); @@ -65,11 +51,13 @@ fn multiple_occurrences_of_flags_mixed() { #[test] fn multiple_occurrences_of_flags_large_quantity() { - let args : Vec<&str> = vec![""].into_iter().chain(vec!["-m"; 1024].into_iter()).collect(); + let args: Vec<&str> = vec![""] + .into_iter() + .chain(vec!["-m"; 1024].into_iter()) + .collect(); let m = App::new("mo_flags_larg_qty") - .arg(Arg::from_usage("-m --multflag 'allowed multiple flag'") - .multiple(true)) - .get_matches_from(args); + .arg(Arg::from_usage("-m --multflag 'allowed multiple flag'").multiple(true)) + .get_matches_from(args); assert!(m.is_present("multflag")); assert_eq!(m.occurrences_of("multflag"), 1024); } diff --git a/tests/multiple_values.rs b/tests/multiple_values.rs index 551aff1bdc6..6197bc5e3e6 100644 --- a/tests/multiple_values.rs +++ b/tests/multiple_values.rs @@ -5,16 +5,15 @@ use clap::{App, Arg, ErrorKind, SubCommand}; #[test] fn option_long() { let m = App::new("multiple_values") - .arg(Arg::with_name("option") - .long("option") - .help("multiple options") - .takes_value(true) - .multiple(true)) + .arg( + Arg::with_name("option") + .long("option") + .help("multiple options") + .takes_value(true) + .multiple(true), + ) .get_matches_from_safe(vec![ - "", - "--option", "val1", - "--option", "val2", - "--option", "val3", + "", "--option", "val1", "--option", "val2", "--option", "val3", ]); assert!(m.is_ok()); @@ -22,47 +21,48 @@ fn option_long() { assert!(m.is_present("option")); assert_eq!(m.occurrences_of("option"), 3); - assert_eq!(m.values_of("option").unwrap().collect::>(), ["val1", "val2", "val3"]); + assert_eq!( + m.values_of("option").unwrap().collect::>(), + ["val1", "val2", "val3"] + ); } #[test] fn option_short() { let m = App::new("multiple_values") - .arg(Arg::with_name("option") - .short("o") - .help("multiple options") - .takes_value(true) - .multiple(true)) - .get_matches_from_safe(vec![ - "", - "-o", "val1", - "-o", "val2", - "-o", "val3", - ]); + .arg( + Arg::with_name("option") + .short("o") + .help("multiple options") + .takes_value(true) + .multiple(true), + ) + .get_matches_from_safe(vec!["", "-o", "val1", "-o", "val2", "-o", "val3"]); assert!(m.is_ok()); let m = m.unwrap(); assert!(m.is_present("option")); assert_eq!(m.occurrences_of("option"), 3); - assert_eq!(m.values_of("option").unwrap().collect::>(), ["val1", "val2", "val3"]); + assert_eq!( + m.values_of("option").unwrap().collect::>(), + ["val1", "val2", "val3"] + ); } #[test] fn option_mixed() { let m = App::new("multiple_values") - .arg(Arg::with_name("option") - .long("option") - .short("o") - .help("multiple options") - .takes_value(true) - .multiple(true)) + .arg( + Arg::with_name("option") + .long("option") + .short("o") + .help("multiple options") + .takes_value(true) + .multiple(true), + ) .get_matches_from_safe(vec![ - "", - "-o", "val1", - "--option", "val2", - "--option", "val3", - "-o", "val4", + "", "-o", "val1", "--option", "val2", "--option", "val3", "-o", "val4", ]); assert!(m.is_ok()); @@ -70,67 +70,72 @@ fn option_mixed() { assert!(m.is_present("option")); assert_eq!(m.occurrences_of("option"), 4); - assert_eq!(m.values_of("option").unwrap().collect::>(), ["val1", "val2", "val3", "val4"]); + assert_eq!( + m.values_of("option").unwrap().collect::>(), + ["val1", "val2", "val3", "val4"] + ); } #[test] fn option_exact_exact() { let m = App::new("multiple_values") - .arg(Arg::with_name("option") - .short("o") - .help("multiple options") - .takes_value(true) - .multiple(true) - .number_of_values(3)) - .get_matches_from_safe(vec![ - "", - "-o", "val1", - "-o", "val2", - "-o", "val3", - ]); + .arg( + Arg::with_name("option") + .short("o") + .help("multiple options") + .takes_value(true) + .multiple(true) + .number_of_values(3), + ) + .get_matches_from_safe(vec!["", "-o", "val1", "-o", "val2", "-o", "val3"]); assert!(m.is_ok()); let m = m.unwrap(); assert!(m.is_present("option")); assert_eq!(m.occurrences_of("option"), 3); - assert_eq!(m.values_of("option").unwrap().collect::>(), ["val1", "val2", "val3"]); + assert_eq!( + m.values_of("option").unwrap().collect::>(), + ["val1", "val2", "val3"] + ); } #[test] fn option_exact_exact_not_mult() { let m = App::new("multiple_values") - .arg(Arg::with_name("option") - .short("o") - .help("multiple options") - .takes_value(true) - .number_of_values(3)) - .get_matches_from_safe(vec![ - "", - "-o", "val1", "val2", "val3", - ]); + .arg( + Arg::with_name("option") + .short("o") + .help("multiple options") + .takes_value(true) + .number_of_values(3), + ) + .get_matches_from_safe(vec!["", "-o", "val1", "val2", "val3"]); assert!(m.is_ok()); let m = m.unwrap(); assert!(m.is_present("option")); assert_eq!(m.occurrences_of("option"), 1); - assert_eq!(m.values_of("option").unwrap().collect::>(), ["val1", "val2", "val3"]); + assert_eq!( + m.values_of("option").unwrap().collect::>(), + ["val1", "val2", "val3"] + ); } #[test] fn option_exact_exact_mult() { let m = App::new("multiple_values") - .arg(Arg::with_name("option") - .short("o") - .help("multiple options") - .takes_value(true) - .multiple(true) - .number_of_values(3)) + .arg( + Arg::with_name("option") + .short("o") + .help("multiple options") + .takes_value(true) + .multiple(true) + .number_of_values(3), + ) .get_matches_from_safe(vec![ - "", - "-o", "val1", "val2", "val3", - "-o", "val4", "val5", "val6", + "", "-o", "val1", "val2", "val3", "-o", "val4", "val5", "val6", ]); assert!(m.is_ok()); @@ -138,23 +143,24 @@ fn option_exact_exact_mult() { assert!(m.is_present("option")); assert_eq!(m.occurrences_of("option"), 2); - assert_eq!(m.values_of("option").unwrap().collect::>(), ["val1", "val2", "val3", "val4", "val5", "val6"]); + assert_eq!( + m.values_of("option").unwrap().collect::>(), + ["val1", "val2", "val3", "val4", "val5", "val6"] + ); } #[test] fn option_exact_less() { let m = App::new("multiple_values") - .arg(Arg::with_name("option") - .short("o") - .help("multiple options") - .takes_value(true) - .multiple(true) - .number_of_values(3)) - .get_matches_from_safe(vec![ - "", - "-o", "val1", - "-o", "val2", - ]); + .arg( + Arg::with_name("option") + .short("o") + .help("multiple options") + .takes_value(true) + .multiple(true) + .number_of_values(3), + ) + .get_matches_from_safe(vec!["", "-o", "val1", "-o", "val2"]); assert!(m.is_err()); assert_eq!(m.unwrap_err().kind, ErrorKind::WrongNumberOfValues); @@ -163,18 +169,16 @@ fn option_exact_less() { #[test] fn option_exact_more() { let m = App::new("multiple_values") - .arg(Arg::with_name("option") - .short("o") - .help("multiple options") - .takes_value(true) - .multiple(true) - .number_of_values(3)) + .arg( + Arg::with_name("option") + .short("o") + .help("multiple options") + .takes_value(true) + .multiple(true) + .number_of_values(3), + ) .get_matches_from_safe(vec![ - "", - "-o", "val1", - "-o", "val2", - "-o", "val3", - "-o", "val4", + "", "-o", "val1", "-o", "val2", "-o", "val3", "-o", "val4", ]); assert!(m.is_err()); @@ -184,41 +188,39 @@ fn option_exact_more() { #[test] fn option_min_exact() { let m = App::new("multiple_values") - .arg(Arg::with_name("option") - .short("o") - .help("multiple options") - .takes_value(true) - .multiple(true) - .min_values(3)) - .get_matches_from_safe(vec![ - "", - "-o", "val1", - "-o", "val2", - "-o", "val3", - ]); + .arg( + Arg::with_name("option") + .short("o") + .help("multiple options") + .takes_value(true) + .multiple(true) + .min_values(3), + ) + .get_matches_from_safe(vec!["", "-o", "val1", "-o", "val2", "-o", "val3"]); assert!(m.is_ok()); let m = m.unwrap(); assert!(m.is_present("option")); assert_eq!(m.occurrences_of("option"), 3); - assert_eq!(m.values_of("option").unwrap().collect::>(), ["val1", "val2", "val3"]); + assert_eq!( + m.values_of("option").unwrap().collect::>(), + ["val1", "val2", "val3"] + ); } #[test] fn option_min_less() { let m = App::new("multiple_values") - .arg(Arg::with_name("option") - .short("o") - .help("multiple options") - .takes_value(true) - .multiple(true) - .min_values(3)) - .get_matches_from_safe(vec![ - "", - "-o", "val1", - "-o", "val2", - ]); + .arg( + Arg::with_name("option") + .short("o") + .help("multiple options") + .takes_value(true) + .multiple(true) + .min_values(3), + ) + .get_matches_from_safe(vec!["", "-o", "val1", "-o", "val2"]); assert!(m.is_err()); assert_eq!(m.unwrap_err().kind, ErrorKind::TooFewValues); @@ -227,123 +229,122 @@ fn option_min_less() { #[test] fn option_short_min_more_mult_occurs() { let m = App::new("multiple_values") - .arg(Arg::with_name("arg") - .required(true)) - .arg(Arg::with_name("option") - .short("o") - .help("multiple options") - .takes_value(true) - .multiple(true) - .min_values(3)) + .arg(Arg::with_name("arg").required(true)) + .arg( + Arg::with_name("option") + .short("o") + .help("multiple options") + .takes_value(true) + .multiple(true) + .min_values(3), + ) .get_matches_from_safe(vec![ - "", - "pos", - "-o", "val1", - "-o", "val2", - "-o", "val3", - "-o", "val4", + "", "pos", "-o", "val1", "-o", "val2", "-o", "val3", "-o", "val4", ]); - let m = m.map_err(|e| println!("failed to unwrap err with error kind {:?}", e.kind)).unwrap(); + let m = m + .map_err(|e| println!("failed to unwrap err with error kind {:?}", e.kind)) + .unwrap(); assert!(m.is_present("option")); assert!(m.is_present("arg")); assert_eq!(m.occurrences_of("option"), 4); - assert_eq!(m.values_of("option").unwrap().collect::>(), ["val1", "val2", "val3", "val4"]); + assert_eq!( + m.values_of("option").unwrap().collect::>(), + ["val1", "val2", "val3", "val4"] + ); assert_eq!(m.value_of("arg"), Some("pos")); } #[test] fn option_short_min_more_single_occur() { let m = App::new("multiple_values") - .arg(Arg::with_name("arg") - .required(true)) - .arg(Arg::with_name("option") - .short("o") - .help("multiple options") - .takes_value(true) - .multiple(true) - .min_values(3)) - .get_matches_from_safe(vec![ - "", - "pos", - "-o", "val1", - "val2", - "val3", - "val4", - ]); - - let m = m.map_err(|e| println!("failed to unwrap err with error kind {:#?}", e)).unwrap(); + .arg(Arg::with_name("arg").required(true)) + .arg( + Arg::with_name("option") + .short("o") + .help("multiple options") + .takes_value(true) + .multiple(true) + .min_values(3), + ) + .get_matches_from_safe(vec!["", "pos", "-o", "val1", "val2", "val3", "val4"]); + + let m = m + .map_err(|e| println!("failed to unwrap err with error kind {:#?}", e)) + .unwrap(); assert!(m.is_present("option")); assert!(m.is_present("arg")); assert_eq!(m.occurrences_of("option"), 1); - assert_eq!(m.values_of("option").unwrap().collect::>(), ["val1", "val2", "val3", "val4"]); + assert_eq!( + m.values_of("option").unwrap().collect::>(), + ["val1", "val2", "val3", "val4"] + ); assert_eq!(m.value_of("arg"), Some("pos")); } #[test] fn option_max_exact() { let m = App::new("multiple_values") - .arg(Arg::with_name("option") - .short("o") - .help("multiple options") - .takes_value(true) - .multiple(true) - .max_values(3)) - .get_matches_from_safe(vec![ - "", - "-o", "val1", - "-o", "val2", - "-o", "val3", - ]); + .arg( + Arg::with_name("option") + .short("o") + .help("multiple options") + .takes_value(true) + .multiple(true) + .max_values(3), + ) + .get_matches_from_safe(vec!["", "-o", "val1", "-o", "val2", "-o", "val3"]); assert!(m.is_ok()); let m = m.unwrap(); assert!(m.is_present("option")); assert_eq!(m.occurrences_of("option"), 3); - assert_eq!(m.values_of("option").unwrap().collect::>(), ["val1", "val2", "val3"]); + assert_eq!( + m.values_of("option").unwrap().collect::>(), + ["val1", "val2", "val3"] + ); } #[test] fn option_max_less() { let m = App::new("multiple_values") - .arg(Arg::with_name("option") - .short("o") - .help("multiple options") - .takes_value(true) - .multiple(true) - .max_values(3)) - .get_matches_from_safe(vec![ - "", - "-o", "val1", - "-o", "val2", - ]); + .arg( + Arg::with_name("option") + .short("o") + .help("multiple options") + .takes_value(true) + .multiple(true) + .max_values(3), + ) + .get_matches_from_safe(vec!["", "-o", "val1", "-o", "val2"]); assert!(m.is_ok()); let m = m.unwrap(); assert!(m.is_present("option")); assert_eq!(m.occurrences_of("option"), 2); - assert_eq!(m.values_of("option").unwrap().collect::>(), ["val1", "val2"]); + assert_eq!( + m.values_of("option").unwrap().collect::>(), + ["val1", "val2"] + ); } #[test] fn option_max_more() { let m = App::new("multiple_values") - .arg(Arg::with_name("option") - .short("o") - .help("multiple options") - .takes_value(true) - .multiple(true) - .max_values(3)) + .arg( + Arg::with_name("option") + .short("o") + .help("multiple options") + .takes_value(true) + .multiple(true) + .max_values(3), + ) .get_matches_from_safe(vec![ - "", - "-o", "val1", - "-o", "val2", - "-o", "val3", - "-o", "val4", + "", "-o", "val1", "-o", "val2", "-o", "val3", "-o", "val4", ]); assert!(m.is_err()); @@ -353,9 +354,11 @@ fn option_max_more() { #[test] fn positional() { let m = App::new("multiple_values") - .arg(Arg::with_name("pos") - .help("multiple positionals") - .multiple(true)) + .arg( + Arg::with_name("pos") + .help("multiple positionals") + .multiple(true), + ) .get_matches_from_safe(vec!["myprog", "val1", "val2", "val3"]); assert!(m.is_ok()); @@ -363,15 +366,20 @@ fn positional() { assert!(m.is_present("pos")); assert_eq!(m.occurrences_of("pos"), 3); - assert_eq!(m.values_of("pos").unwrap().collect::>(), ["val1", "val2", "val3"]); + assert_eq!( + m.values_of("pos").unwrap().collect::>(), + ["val1", "val2", "val3"] + ); } #[test] fn positional_exact_exact() { let m = App::new("multiple_values") - .arg(Arg::with_name("pos") - .help("multiple positionals") - .number_of_values(3)) + .arg( + Arg::with_name("pos") + .help("multiple positionals") + .number_of_values(3), + ) .get_matches_from_safe(vec!["myprog", "val1", "val2", "val3"]); assert!(m.is_ok()); @@ -379,15 +387,20 @@ fn positional_exact_exact() { assert!(m.is_present("pos")); assert_eq!(m.occurrences_of("pos"), 3); - assert_eq!(m.values_of("pos").unwrap().collect::>(), ["val1", "val2", "val3"]); + assert_eq!( + m.values_of("pos").unwrap().collect::>(), + ["val1", "val2", "val3"] + ); } #[test] fn positional_exact_less() { let m = App::new("multiple_values") - .arg(Arg::with_name("pos") - .help("multiple positionals") - .number_of_values(3)) + .arg( + Arg::with_name("pos") + .help("multiple positionals") + .number_of_values(3), + ) .get_matches_from_safe(vec!["myprog", "val1", "val2"]); assert!(m.is_err()); @@ -397,9 +410,11 @@ fn positional_exact_less() { #[test] fn positional_exact_more() { let m = App::new("multiple_values") - .arg(Arg::with_name("pos") - .help("multiple positionals") - .number_of_values(3)) + .arg( + Arg::with_name("pos") + .help("multiple positionals") + .number_of_values(3), + ) .get_matches_from_safe(vec!["myprog", "val1", "val2", "val3", "val4"]); assert!(m.is_err()); @@ -409,9 +424,11 @@ fn positional_exact_more() { #[test] fn positional_min_exact() { let m = App::new("multiple_values") - .arg(Arg::with_name("pos") - .help("multiple positionals") - .min_values(3)) + .arg( + Arg::with_name("pos") + .help("multiple positionals") + .min_values(3), + ) .get_matches_from_safe(vec!["myprog", "val1", "val2", "val3"]); assert!(m.is_ok()); @@ -419,15 +436,20 @@ fn positional_min_exact() { assert!(m.is_present("pos")); assert_eq!(m.occurrences_of("pos"), 3); - assert_eq!(m.values_of("pos").unwrap().collect::>(), ["val1", "val2", "val3"]); + assert_eq!( + m.values_of("pos").unwrap().collect::>(), + ["val1", "val2", "val3"] + ); } #[test] fn positional_min_less() { let m = App::new("multiple_values") - .arg(Arg::with_name("pos") - .help("multiple positionals") - .min_values(3)) + .arg( + Arg::with_name("pos") + .help("multiple positionals") + .min_values(3), + ) .get_matches_from_safe(vec!["myprog", "val1", "val2"]); assert!(m.is_err()); @@ -437,9 +459,11 @@ fn positional_min_less() { #[test] fn positional_min_more() { let m = App::new("multiple_values") - .arg(Arg::with_name("pos") - .help("multiple positionals") - .min_values(3)) + .arg( + Arg::with_name("pos") + .help("multiple positionals") + .min_values(3), + ) .get_matches_from_safe(vec!["myprog", "val1", "val2", "val3", "val4"]); assert!(m.is_ok()); @@ -447,15 +471,20 @@ fn positional_min_more() { assert!(m.is_present("pos")); assert_eq!(m.occurrences_of("pos"), 4); - assert_eq!(m.values_of("pos").unwrap().collect::>(), ["val1", "val2", "val3", "val4"]); + assert_eq!( + m.values_of("pos").unwrap().collect::>(), + ["val1", "val2", "val3", "val4"] + ); } #[test] fn positional_max_exact() { let m = App::new("multiple_values") - .arg(Arg::with_name("pos") - .help("multiple positionals") - .max_values(3)) + .arg( + Arg::with_name("pos") + .help("multiple positionals") + .max_values(3), + ) .get_matches_from_safe(vec!["myprog", "val1", "val2", "val3"]); assert!(m.is_ok()); @@ -463,15 +492,20 @@ fn positional_max_exact() { assert!(m.is_present("pos")); assert_eq!(m.occurrences_of("pos"), 3); - assert_eq!(m.values_of("pos").unwrap().collect::>(), ["val1", "val2", "val3"]); + assert_eq!( + m.values_of("pos").unwrap().collect::>(), + ["val1", "val2", "val3"] + ); } #[test] fn positional_max_less() { let m = App::new("multiple_values") - .arg(Arg::with_name("pos") - .help("multiple positionals") - .max_values(3)) + .arg( + Arg::with_name("pos") + .help("multiple positionals") + .max_values(3), + ) .get_matches_from_safe(vec!["myprog", "val1", "val2"]); assert!(m.is_ok()); @@ -479,15 +513,20 @@ fn positional_max_less() { assert!(m.is_present("pos")); assert_eq!(m.occurrences_of("pos"), 2); - assert_eq!(m.values_of("pos").unwrap().collect::>(), ["val1", "val2"]); + assert_eq!( + m.values_of("pos").unwrap().collect::>(), + ["val1", "val2"] + ); } #[test] fn positional_max_more() { let m = App::new("multiple_values") - .arg(Arg::with_name("pos") - .help("multiple positionals") - .max_values(3)) + .arg( + Arg::with_name("pos") + .help("multiple positionals") + .max_values(3), + ) .get_matches_from_safe(vec!["myprog", "val1", "val2", "val3", "val4"]); assert!(m.is_err()); @@ -497,187 +536,200 @@ fn positional_max_more() { #[test] fn sep_long_equals() { let m = App::new("multiple_values") - .arg(Arg::with_name("option") - .long("option") - .use_delimiter(true) - .help("multiple options") - .takes_value(true) - .multiple(true)) - .get_matches_from_safe(vec![ - "", - "--option=val1,val2,val3", - ]); + .arg( + Arg::with_name("option") + .long("option") + .use_delimiter(true) + .help("multiple options") + .takes_value(true) + .multiple(true), + ) + .get_matches_from_safe(vec!["", "--option=val1,val2,val3"]); assert!(m.is_ok()); let m = m.unwrap(); assert!(m.is_present("option")); assert_eq!(m.occurrences_of("option"), 1); - assert_eq!(m.values_of("option").unwrap().collect::>(), ["val1", "val2", "val3"]); + assert_eq!( + m.values_of("option").unwrap().collect::>(), + ["val1", "val2", "val3"] + ); } #[test] fn sep_long_space() { let m = App::new("multiple_values") - .arg(Arg::with_name("option") - .long("option") - .use_delimiter(true) - .help("multiple options") - .takes_value(true) - .multiple(true)) - .get_matches_from_safe(vec![ - "", - "--option", - "val1,val2,val3", - ]); + .arg( + Arg::with_name("option") + .long("option") + .use_delimiter(true) + .help("multiple options") + .takes_value(true) + .multiple(true), + ) + .get_matches_from_safe(vec!["", "--option", "val1,val2,val3"]); assert!(m.is_ok()); let m = m.unwrap(); assert!(m.is_present("option")); assert_eq!(m.occurrences_of("option"), 1); - assert_eq!(m.values_of("option").unwrap().collect::>(), ["val1", "val2", "val3"]); + assert_eq!( + m.values_of("option").unwrap().collect::>(), + ["val1", "val2", "val3"] + ); } #[test] fn sep_short_equals() { let m = App::new("multiple_values") - .arg(Arg::with_name("option") - .short("o") - .help("multiple options") - .use_delimiter(true) - .takes_value(true) - .multiple(true)) - .get_matches_from_safe(vec![ - "", - "-o=val1,val2,val3", - ]); + .arg( + Arg::with_name("option") + .short("o") + .help("multiple options") + .use_delimiter(true) + .takes_value(true) + .multiple(true), + ) + .get_matches_from_safe(vec!["", "-o=val1,val2,val3"]); assert!(m.is_ok()); let m = m.unwrap(); assert!(m.is_present("option")); assert_eq!(m.occurrences_of("option"), 1); - assert_eq!(m.values_of("option").unwrap().collect::>(), ["val1", "val2", "val3"]); + assert_eq!( + m.values_of("option").unwrap().collect::>(), + ["val1", "val2", "val3"] + ); } #[test] fn sep_short_space() { let m = App::new("multiple_values") - .arg(Arg::with_name("option") - .short("o") - .help("multiple options") - .use_delimiter(true) - .takes_value(true) - .multiple(true)) - .get_matches_from_safe(vec![ - "", - "-o", - "val1,val2,val3", - ]); + .arg( + Arg::with_name("option") + .short("o") + .help("multiple options") + .use_delimiter(true) + .takes_value(true) + .multiple(true), + ) + .get_matches_from_safe(vec!["", "-o", "val1,val2,val3"]); assert!(m.is_ok()); let m = m.unwrap(); assert!(m.is_present("option")); assert_eq!(m.occurrences_of("option"), 1); - assert_eq!(m.values_of("option").unwrap().collect::>(), ["val1", "val2", "val3"]); + assert_eq!( + m.values_of("option").unwrap().collect::>(), + ["val1", "val2", "val3"] + ); } #[test] fn sep_short_no_space() { let m = App::new("multiple_values") - .arg(Arg::with_name("option") - .short("o") - .help("multiple options") - .use_delimiter(true) - .takes_value(true) - .multiple(true)) - .get_matches_from_safe(vec![ - "", - "-oval1,val2,val3", - ]); + .arg( + Arg::with_name("option") + .short("o") + .help("multiple options") + .use_delimiter(true) + .takes_value(true) + .multiple(true), + ) + .get_matches_from_safe(vec!["", "-oval1,val2,val3"]); assert!(m.is_ok()); let m = m.unwrap(); assert!(m.is_present("option")); assert_eq!(m.occurrences_of("option"), 1); - assert_eq!(m.values_of("option").unwrap().collect::>(), ["val1", "val2", "val3"]); + assert_eq!( + m.values_of("option").unwrap().collect::>(), + ["val1", "val2", "val3"] + ); } #[test] fn sep_positional() { let m = App::new("multiple_values") - .arg(Arg::with_name("option") - .help("multiple options") - .use_delimiter(true) - .multiple(true)) - .get_matches_from_safe(vec![ - "", - "val1,val2,val3", - ]); + .arg( + Arg::with_name("option") + .help("multiple options") + .use_delimiter(true) + .multiple(true), + ) + .get_matches_from_safe(vec!["", "val1,val2,val3"]); assert!(m.is_ok()); let m = m.unwrap(); assert!(m.is_present("option")); assert_eq!(m.occurrences_of("option"), 1); - assert_eq!(m.values_of("option").unwrap().collect::>(), ["val1", "val2", "val3"]); + assert_eq!( + m.values_of("option").unwrap().collect::>(), + ["val1", "val2", "val3"] + ); } #[test] fn different_sep() { let m = App::new("multiple_values") - .arg(Arg::with_name("option") - .long("option") - .help("multiple options") - .takes_value(true) - .value_delimiter(";")) - .get_matches_from_safe(vec![ - "", - "--option=val1;val2;val3", - ]); + .arg( + Arg::with_name("option") + .long("option") + .help("multiple options") + .takes_value(true) + .value_delimiter(";"), + ) + .get_matches_from_safe(vec!["", "--option=val1;val2;val3"]); assert!(m.is_ok()); let m = m.unwrap(); assert!(m.is_present("option")); assert_eq!(m.occurrences_of("option"), 1); - assert_eq!(m.values_of("option").unwrap().collect::>(), ["val1", "val2", "val3"]); + assert_eq!( + m.values_of("option").unwrap().collect::>(), + ["val1", "val2", "val3"] + ); } #[test] fn different_sep_positional() { let m = App::new("multiple_values") - .arg(Arg::with_name("option") - .help("multiple options") - .value_delimiter(";")) - .get_matches_from_safe(vec![ - "", - "val1;val2;val3", - ]); + .arg( + Arg::with_name("option") + .help("multiple options") + .value_delimiter(";"), + ) + .get_matches_from_safe(vec!["", "val1;val2;val3"]); assert!(m.is_ok()); let m = m.unwrap(); assert!(m.is_present("option")); assert_eq!(m.occurrences_of("option"), 1); - assert_eq!(m.values_of("option").unwrap().collect::>(), ["val1", "val2", "val3"]); + assert_eq!( + m.values_of("option").unwrap().collect::>(), + ["val1", "val2", "val3"] + ); } #[test] fn no_sep() { let m = App::new("multiple_values") - .arg(Arg::with_name("option") - .long("option") - .help("multiple options") - .takes_value(true) - .use_delimiter(false)) - .get_matches_from_safe(vec![ - "", - "--option=val1,val2,val3", - ]); + .arg( + Arg::with_name("option") + .long("option") + .help("multiple options") + .takes_value(true) + .use_delimiter(false), + ) + .get_matches_from_safe(vec!["", "--option=val1,val2,val3"]); assert!(m.is_ok()); let m = m.unwrap(); @@ -690,13 +742,12 @@ fn no_sep() { #[test] fn no_sep_positional() { let m = App::new("multiple_values") - .arg(Arg::with_name("option") - .help("multiple options") - .use_delimiter(false)) - .get_matches_from_safe(vec![ - "", - "val1,val2,val3", - ]); + .arg( + Arg::with_name("option") + .help("multiple options") + .use_delimiter(false), + ) + .get_matches_from_safe(vec!["", "val1,val2,val3"]); assert!(m.is_ok()); let m = m.unwrap(); @@ -709,159 +760,188 @@ fn no_sep_positional() { #[test] fn req_delimiter_long() { let m = App::new("multiple_values") - .arg(Arg::with_name("option") - .long("option") - .multiple(true) - .use_delimiter(true) - .require_delimiter(true) - .takes_value(true)) - .arg(Arg::with_name("args") - .multiple(true) - .index(1)) - .get_matches_from_safe(vec![ - "", - "--option", "val1", "val2", "val3", - ]); + .arg( + Arg::with_name("option") + .long("option") + .multiple(true) + .use_delimiter(true) + .require_delimiter(true) + .takes_value(true), + ) + .arg(Arg::with_name("args").multiple(true).index(1)) + .get_matches_from_safe(vec!["", "--option", "val1", "val2", "val3"]); assert!(m.is_ok()); let m = m.unwrap(); assert!(m.is_present("option")); assert_eq!(m.occurrences_of("option"), 1); - assert_eq!(m.values_of("option").unwrap().collect::>(), &["val1"]); - assert_eq!(m.values_of("args").unwrap().collect::>(), &["val2", "val3"]); + assert_eq!( + m.values_of("option").unwrap().collect::>(), + &["val1"] + ); + assert_eq!( + m.values_of("args").unwrap().collect::>(), + &["val2", "val3"] + ); } #[test] fn req_delimiter_long_with_equal() { let m = App::new("multiple_values") - .arg(Arg::with_name("option") - .long("option") - .multiple(true) - .use_delimiter(true) - .require_delimiter(true) - .takes_value(true)) - .arg(Arg::with_name("args") - .multiple(true) - .index(1)) - .get_matches_from_safe(vec![ - "", - "--option=val1", "val2", "val3", - ]); + .arg( + Arg::with_name("option") + .long("option") + .multiple(true) + .use_delimiter(true) + .require_delimiter(true) + .takes_value(true), + ) + .arg(Arg::with_name("args").multiple(true).index(1)) + .get_matches_from_safe(vec!["", "--option=val1", "val2", "val3"]); assert!(m.is_ok()); let m = m.unwrap(); assert!(m.is_present("option")); assert_eq!(m.occurrences_of("option"), 1); - assert_eq!(m.values_of("option").unwrap().collect::>(), &["val1"]); - assert_eq!(m.values_of("args").unwrap().collect::>(), &["val2", "val3"]); + assert_eq!( + m.values_of("option").unwrap().collect::>(), + &["val1"] + ); + assert_eq!( + m.values_of("args").unwrap().collect::>(), + &["val2", "val3"] + ); } #[test] fn req_delimiter_short_with_space() { let m = App::new("multiple_values") - .arg(Arg::with_name("option") - .short("o") - .multiple(true) - .use_delimiter(true) - .require_delimiter(true) - .takes_value(true)) - .arg(Arg::with_name("args") - .multiple(true) - .index(1)) - .get_matches_from_safe(vec![ - "", - "-o", "val1", "val2", "val3", - ]); + .arg( + Arg::with_name("option") + .short("o") + .multiple(true) + .use_delimiter(true) + .require_delimiter(true) + .takes_value(true), + ) + .arg(Arg::with_name("args").multiple(true).index(1)) + .get_matches_from_safe(vec!["", "-o", "val1", "val2", "val3"]); assert!(m.is_ok()); let m = m.unwrap(); assert!(m.is_present("option")); assert_eq!(m.occurrences_of("option"), 1); - assert_eq!(m.values_of("option").unwrap().collect::>(), &["val1"]); - assert_eq!(m.values_of("args").unwrap().collect::>(), &["val2", "val3"]); + assert_eq!( + m.values_of("option").unwrap().collect::>(), + &["val1"] + ); + assert_eq!( + m.values_of("args").unwrap().collect::>(), + &["val2", "val3"] + ); } #[test] fn req_delimiter_short_with_no_space() { let m = App::new("multiple_values") - .arg(Arg::with_name("option") - .short("o") - .multiple(true) - .use_delimiter(true) - .require_delimiter(true) - .takes_value(true)) - .arg(Arg::with_name("args") - .multiple(true) - .index(1)) - .get_matches_from_safe(vec![ - "", - "-oval1", "val2", "val3", - ]); + .arg( + Arg::with_name("option") + .short("o") + .multiple(true) + .use_delimiter(true) + .require_delimiter(true) + .takes_value(true), + ) + .arg(Arg::with_name("args").multiple(true).index(1)) + .get_matches_from_safe(vec!["", "-oval1", "val2", "val3"]); assert!(m.is_ok()); let m = m.unwrap(); assert!(m.is_present("option")); assert_eq!(m.occurrences_of("option"), 1); - assert_eq!(m.values_of("option").unwrap().collect::>(), &["val1"]); - assert_eq!(m.values_of("args").unwrap().collect::>(), &["val2", "val3"]); + assert_eq!( + m.values_of("option").unwrap().collect::>(), + &["val1"] + ); + assert_eq!( + m.values_of("args").unwrap().collect::>(), + &["val2", "val3"] + ); } #[test] fn req_delimiter_short_with_equal() { let m = App::new("multiple_values") - .arg(Arg::with_name("option") - .short("option") - .multiple(true) - .use_delimiter(true) - .require_delimiter(true) - .takes_value(true)) - .arg(Arg::with_name("args") - .multiple(true) - .index(1)) - .get_matches_from_safe(vec![ - "", - "-o=val1", "val2", "val3", - ]); + .arg( + Arg::with_name("option") + .short("option") + .multiple(true) + .use_delimiter(true) + .require_delimiter(true) + .takes_value(true), + ) + .arg(Arg::with_name("args").multiple(true).index(1)) + .get_matches_from_safe(vec!["", "-o=val1", "val2", "val3"]); assert!(m.is_ok()); let m = m.unwrap(); assert!(m.is_present("option")); assert_eq!(m.occurrences_of("option"), 1); - assert_eq!(m.values_of("option").unwrap().collect::>(), &["val1"]); - assert_eq!(m.values_of("args").unwrap().collect::>(), &["val2", "val3"]); + assert_eq!( + m.values_of("option").unwrap().collect::>(), + &["val1"] + ); + assert_eq!( + m.values_of("args").unwrap().collect::>(), + &["val2", "val3"] + ); } #[test] fn req_delimiter_complex() { let m = App::new("multiple_values") - .arg(Arg::with_name("option") - .long("option") - .short("o") - .multiple(true) - .use_delimiter(true) - .require_delimiter(true) - .takes_value(true)) - .arg(Arg::with_name("args") - .multiple(true) - .index(1)) + .arg( + Arg::with_name("option") + .long("option") + .short("o") + .multiple(true) + .use_delimiter(true) + .require_delimiter(true) + .takes_value(true), + ) + .arg(Arg::with_name("args").multiple(true).index(1)) .get_matches_from_safe(vec![ "", "val1", - "-oval2", "val3", - "-o", "val4", "val5", - "-o=val6", "val7", - "--option=val8", "val9", - "--option", "val10", "val11", - "-oval12,val13", "val14", - "-o", "val15,val16", "val17", - "-o=val18,val19", "val20", - "--option=val21,val22", "val23", - "--option", "val24,val25", "val26" + "-oval2", + "val3", + "-o", + "val4", + "val5", + "-o=val6", + "val7", + "--option=val8", + "val9", + "--option", + "val10", + "val11", + "-oval12,val13", + "val14", + "-o", + "val15,val16", + "val17", + "-o=val18,val19", + "val20", + "--option=val21,val22", + "val23", + "--option", + "val24,val25", + "val26", ]); assert!(m.is_ok()); @@ -869,86 +949,81 @@ fn req_delimiter_complex() { assert!(m.is_present("option")); assert_eq!(m.occurrences_of("option"), 10); - assert_eq!(m.values_of("option").unwrap().collect::>(), - &["val2", "val4", "val6", "val8", "val10", "val12", "val13", "val15", - "val16", "val18", "val19", "val21", "val22", "val24", "val25"]); - assert_eq!(m.values_of("args").unwrap().collect::>(), - &["val1", "val3", "val5", "val7", "val9", "val11", "val14", "val17", - "val20", "val23", "val26"]); + assert_eq!( + m.values_of("option").unwrap().collect::>(), + &[ + "val2", "val4", "val6", "val8", "val10", "val12", "val13", "val15", "val16", "val18", + "val19", "val21", "val22", "val24", "val25" + ] + ); + assert_eq!( + m.values_of("args").unwrap().collect::>(), + &[ + "val1", "val3", "val5", "val7", "val9", "val11", "val14", "val17", "val20", "val23", + "val26" + ] + ); } #[test] #[should_panic] fn low_index_positional_not_required() { let _ = App::new("lip") - .arg(Arg::with_name("files") - .index(1) - .required(true) - .multiple(true)) - .arg(Arg::with_name("target") - .index(2)) - .get_matches_from_safe(vec![ - "lip", - "file1", "file2", - "file3", "target", - ]); + .arg( + Arg::with_name("files") + .index(1) + .required(true) + .multiple(true), + ) + .arg(Arg::with_name("target").index(2)) + .get_matches_from_safe(vec!["lip", "file1", "file2", "file3", "target"]); } #[test] #[should_panic] fn low_index_positional_last_multiple_too() { let _ = App::new("lip") - .arg(Arg::with_name("files") - .index(1) - .required(true) - .multiple(true)) - .arg(Arg::with_name("target") - .index(2) - .required(true) - .multiple(true)) - .get_matches_from_safe(vec![ - "lip", - "file1", "file2", - "file3", "target", - ]); + .arg( + Arg::with_name("files") + .index(1) + .required(true) + .multiple(true), + ) + .arg( + Arg::with_name("target") + .index(2) + .required(true) + .multiple(true), + ) + .get_matches_from_safe(vec!["lip", "file1", "file2", "file3", "target"]); } #[test] #[should_panic] fn low_index_positional_too_far_back() { let _ = App::new("lip") - .arg(Arg::with_name("files") - .index(1) - .required(true) - .multiple(true)) - .arg(Arg::with_name("target") - .required(true) - .index(2)) - .arg(Arg::with_name("target2") - .required(true) - .index(3)) - .get_matches_from_safe(vec![ - "lip", - "file1", "file2", - "file3", "target", - ]); + .arg( + Arg::with_name("files") + .index(1) + .required(true) + .multiple(true), + ) + .arg(Arg::with_name("target").required(true).index(2)) + .arg(Arg::with_name("target2").required(true).index(3)) + .get_matches_from_safe(vec!["lip", "file1", "file2", "file3", "target"]); } #[test] fn low_index_positional() { let m = App::new("lip") - .arg(Arg::with_name("files") - .index(1) - .required(true) - .multiple(true)) - .arg(Arg::with_name("target") - .index(2) - .required(true)) - .get_matches_from_safe(vec![ - "lip", - "file1", "file2", - "file3", "target", - ]); + .arg( + Arg::with_name("files") + .index(1) + .required(true) + .multiple(true), + ) + .arg(Arg::with_name("target").index(2).required(true)) + .get_matches_from_safe(vec!["lip", "file1", "file2", "file3", "target"]); assert!(m.is_ok(), "{:?}", m.unwrap_err().kind); let m = m.unwrap(); @@ -957,57 +1032,56 @@ fn low_index_positional() { assert_eq!(m.occurrences_of("files"), 3); assert!(m.is_present("target")); assert_eq!(m.occurrences_of("target"), 1); - assert_eq!(m.values_of("files").unwrap().collect::>(), ["file1", "file2", "file3"]); + assert_eq!( + m.values_of("files").unwrap().collect::>(), + ["file1", "file2", "file3"] + ); assert_eq!(m.value_of("target").unwrap(), "target"); } #[test] fn low_index_positional_in_subcmd() { let m = App::new("lip") - .subcommand(SubCommand::with_name("test") - .arg(Arg::with_name("files") - .index(1) - .required(true) - .multiple(true)) - .arg(Arg::with_name("target") - .index(2) - .required(true))) - .get_matches_from_safe(vec![ - "lip", "test", - "file1", "file2", - "file3", "target" - ]); + .subcommand( + SubCommand::with_name("test") + .arg( + Arg::with_name("files") + .index(1) + .required(true) + .multiple(true), + ) + .arg(Arg::with_name("target").index(2).required(true)), + ) + .get_matches_from_safe(vec!["lip", "test", "file1", "file2", "file3", "target"]); assert!(m.is_ok(), "{:?}", m.unwrap_err().kind); let m = m.unwrap(); - let sm = m.subcommand_matches("test").unwrap(); + let sm = m.subcommand_matches("test").unwrap(); assert!(sm.is_present("files")); assert_eq!(sm.occurrences_of("files"), 3); assert!(sm.is_present("target")); assert_eq!(sm.occurrences_of("target"), 1); - assert_eq!(sm.values_of("files").unwrap().collect::>(), ["file1", "file2", "file3"]); + assert_eq!( + sm.values_of("files").unwrap().collect::>(), + ["file1", "file2", "file3"] + ); assert_eq!(sm.value_of("target").unwrap(), "target"); } #[test] fn low_index_positional_with_option() { let m = App::new("lip") - .arg(Arg::with_name("files") - .required(true) - .index(1) - .multiple(true)) - .arg(Arg::with_name("target") - .index(2) - .required(true)) - .arg(Arg::with_name("opt") - .long("option") - .takes_value(true)) + .arg( + Arg::with_name("files") + .required(true) + .index(1) + .multiple(true), + ) + .arg(Arg::with_name("target").index(2).required(true)) + .arg(Arg::with_name("opt").long("option").takes_value(true)) .get_matches_from_safe(vec![ - "lip", - "file1", "file2", - "file3", "target", - "--option", "test" + "lip", "file1", "file2", "file3", "target", "--option", "test", ]); assert!(m.is_ok(), "{:?}", m.unwrap_err().kind); @@ -1017,7 +1091,10 @@ fn low_index_positional_with_option() { assert_eq!(m.occurrences_of("files"), 3); assert!(m.is_present("target")); assert_eq!(m.occurrences_of("target"), 1); - assert_eq!(m.values_of("files").unwrap().collect::>(), ["file1", "file2", "file3"]); + assert_eq!( + m.values_of("files").unwrap().collect::>(), + ["file1", "file2", "file3"] + ); assert_eq!(m.value_of("target").unwrap(), "target"); assert_eq!(m.value_of("opt").unwrap(), "test"); } @@ -1025,21 +1102,15 @@ fn low_index_positional_with_option() { #[test] fn low_index_positional_with_flag() { let m = App::new("lip") - .arg(Arg::with_name("files") - .index(1) - .required(true) - .multiple(true)) - .arg(Arg::with_name("target") - .index(2) - .required(true)) - .arg(Arg::with_name("flg") - .long("flag")) - .get_matches_from_safe(vec![ - "lip", - "file1", "file2", - "file3", "target", - "--flag" - ]); + .arg( + Arg::with_name("files") + .index(1) + .required(true) + .multiple(true), + ) + .arg(Arg::with_name("target").index(2).required(true)) + .arg(Arg::with_name("flg").long("flag")) + .get_matches_from_safe(vec!["lip", "file1", "file2", "file3", "target", "--flag"]); assert!(m.is_ok(), "{:?}", m.unwrap_err().kind); let m = m.unwrap(); @@ -1048,7 +1119,10 @@ fn low_index_positional_with_flag() { assert_eq!(m.occurrences_of("files"), 3); assert!(m.is_present("target")); assert_eq!(m.occurrences_of("target"), 1); - assert_eq!(m.values_of("files").unwrap().collect::>(), ["file1", "file2", "file3"]); + assert_eq!( + m.values_of("files").unwrap().collect::>(), + ["file1", "file2", "file3"] + ); assert_eq!(m.value_of("target").unwrap(), "target"); assert!(m.is_present("flg")); } @@ -1056,16 +1130,14 @@ fn low_index_positional_with_flag() { #[test] fn multiple_value_terminator_option() { let m = App::new("lip") - .arg(Arg::with_name("files") - .short("f") - .value_terminator(";") - .multiple(true)) + .arg( + Arg::with_name("files") + .short("f") + .value_terminator(";") + .multiple(true), + ) .arg(Arg::with_name("other")) - .get_matches_from_safe(vec![ - "lip", - "-f", "val1", "val2", ";", - "otherval" - ]); + .get_matches_from_safe(vec!["lip", "-f", "val1", "val2", ";", "otherval"]); assert!(m.is_ok(), "{:?}", m.unwrap_err().kind); let m = m.unwrap(); @@ -1073,33 +1145,35 @@ fn multiple_value_terminator_option() { assert!(m.is_present("other")); assert_eq!(m.occurrences_of("other"), 1); assert!(m.is_present("files")); - assert_eq!(m.values_of("files").unwrap().collect::>(), ["val1", "val2"]); + assert_eq!( + m.values_of("files").unwrap().collect::>(), + ["val1", "val2"] + ); assert_eq!(m.value_of("other"), Some("otherval")); } #[test] fn multiple_value_terminator_option_other_arg() { let m = App::new("lip") - .arg(Arg::with_name("files") - .short("f") - .value_terminator(";") - .multiple(true)) + .arg( + Arg::with_name("files") + .short("f") + .value_terminator(";") + .multiple(true), + ) .arg(Arg::with_name("other")) - .arg(Arg::with_name("flag") - .short("-F")) - .get_matches_from_safe(vec![ - "lip", - "-f", "val1", "val2", - "-F", - "otherval" - ]); + .arg(Arg::with_name("flag").short("-F")) + .get_matches_from_safe(vec!["lip", "-f", "val1", "val2", "-F", "otherval"]); assert!(m.is_ok(), "{:?}", m.unwrap_err().kind); let m = m.unwrap(); assert!(m.is_present("other")); assert!(m.is_present("files")); - assert_eq!(m.values_of("files").unwrap().collect::>(), ["val1", "val2"]); + assert_eq!( + m.values_of("files").unwrap().collect::>(), + ["val1", "val2"] + ); assert_eq!(m.value_of("other"), Some("otherval")); assert!(m.is_present("flag")); } @@ -1107,12 +1181,23 @@ fn multiple_value_terminator_option_other_arg() { #[test] fn multiple_vals_with_hyphen() { let res = App::new("do") - .arg(Arg::with_name("cmds") - .multiple(true) - .allow_hyphen_values(true) - .value_terminator(";")) + .arg( + Arg::with_name("cmds") + .multiple(true) + .allow_hyphen_values(true) + .value_terminator(";"), + ) .arg(Arg::with_name("location")) - .get_matches_from_safe(vec!["do", "find", "-type", "f", "-name", "special", ";", "/home/clap"]); + .get_matches_from_safe(vec![ + "do", + "find", + "-type", + "f", + "-name", + "special", + ";", + "/home/clap", + ]); assert!(res.is_ok(), "{:?}", res.unwrap_err().kind); let m = res.unwrap(); diff --git a/tests/opts.rs b/tests/opts.rs index a9029ac928c..df64ee74dab 100644 --- a/tests/opts.rs +++ b/tests/opts.rs @@ -3,10 +3,11 @@ extern crate regex; include!("../clap-test.rs"); -use clap::{App, ArgMatches, Arg, ErrorKind}; +use clap::{App, Arg, ArgMatches, ErrorKind}; #[cfg(feature = "suggestions")] -static DYM: &'static str = "error: Found argument '--optio' which wasn't expected, or isn't valid in this context +static DYM: &'static str = + "error: Found argument '--optio' which wasn't expected, or isn't valid in this context \tDid you mean --option? USAGE: @@ -17,13 +18,13 @@ For more information try --help"; #[test] fn require_equals_fail() { let res = App::new("prog") - .arg(Arg::with_name("cfg") - .require_equals(true) - .takes_value(true) - .long("config")) - .get_matches_from_safe(vec![ - "prog", "--config", "file.conf" - ]); + .arg( + Arg::with_name("cfg") + .require_equals(true) + .takes_value(true) + .long("config"), + ) + .get_matches_from_safe(vec!["prog", "--config", "file.conf"]); assert!(res.is_err()); assert_eq!(res.unwrap_err().kind, ErrorKind::EmptyValue); } @@ -31,15 +32,15 @@ fn require_equals_fail() { #[test] fn require_equals_min_values_zero() { let res = App::new("prog") - .arg(Arg::with_name("cfg") - .require_equals(true) - .takes_value(true) - .min_values(0) - .long("config")) + .arg( + Arg::with_name("cfg") + .require_equals(true) + .takes_value(true) + .min_values(0) + .long("config"), + ) .arg(Arg::with_name("cmd")) - .get_matches_from_safe(vec![ - "prog", "--config", "cmd" - ]); + .get_matches_from_safe(vec!["prog", "--config", "cmd"]); assert!(res.is_ok()); let m = res.unwrap(); assert!(m.is_present("cfg")); @@ -49,13 +50,13 @@ fn require_equals_min_values_zero() { #[test] fn double_hyphen_as_value() { let res = App::new("prog") - .arg(Arg::with_name("cfg") - .takes_value(true) - .allow_hyphen_values(true) - .long("config")) - .get_matches_from_safe(vec![ - "prog", "--config", "--" - ]); + .arg( + Arg::with_name("cfg") + .takes_value(true) + .allow_hyphen_values(true) + .long("config"), + ) + .get_matches_from_safe(vec!["prog", "--config", "--"]); assert!(res.is_ok(), "{:?}", res); assert_eq!(res.unwrap().value_of("cfg"), Some("--")); } @@ -63,14 +64,14 @@ fn double_hyphen_as_value() { #[test] fn require_equals_no_empty_values_fail() { let res = App::new("prog") - .arg(Arg::with_name("cfg") - .require_equals(true) - .takes_value(true) - .long("config")) + .arg( + Arg::with_name("cfg") + .require_equals(true) + .takes_value(true) + .long("config"), + ) .arg(Arg::with_name("some")) - .get_matches_from_safe(vec![ - "prog", "--config=", "file.conf" - ]); + .get_matches_from_safe(vec!["prog", "--config=", "file.conf"]); assert!(res.is_err()); assert_eq!(res.unwrap_err().kind, ErrorKind::EmptyValue); } @@ -78,27 +79,27 @@ fn require_equals_no_empty_values_fail() { #[test] fn require_equals_empty_vals_pass() { let res = App::new("prog") - .arg(Arg::with_name("cfg") - .require_equals(true) - .takes_value(true) - .empty_values(true) - .long("config")) - .get_matches_from_safe(vec![ - "prog", "--config=" - ]); + .arg( + Arg::with_name("cfg") + .require_equals(true) + .takes_value(true) + .empty_values(true) + .long("config"), + ) + .get_matches_from_safe(vec!["prog", "--config="]); assert!(res.is_ok()); } #[test] fn require_equals_pass() { let res = App::new("prog") - .arg(Arg::with_name("cfg") - .require_equals(true) - .takes_value(true) - .long("config")) - .get_matches_from_safe(vec![ - "prog", "--config=file.conf" - ]); + .arg( + Arg::with_name("cfg") + .require_equals(true) + .takes_value(true) + .long("config"), + ) + .get_matches_from_safe(vec!["prog", "--config=file.conf"]); assert!(res.is_ok()); } @@ -116,8 +117,10 @@ fn stdin_char() { #[test] fn opts_using_short() { let r = App::new("opts") - .args(&[Arg::from_usage("-f [flag] 'some flag'"), - Arg::from_usage("-c [color] 'some other flag'")]) + .args(&[ + Arg::from_usage("-f [flag] 'some flag'"), + Arg::from_usage("-c [color] 'some other flag'"), + ]) .get_matches_from_safe(vec!["", "-f", "some", "-c", "other"]); assert!(r.is_ok()); let m = r.unwrap(); @@ -131,49 +134,36 @@ fn opts_using_short() { fn lots_o_vals() { let r = App::new("opts") .arg(Arg::from_usage("-o [opt]... 'some opt'")) - .get_matches_from_safe(vec!["", "-o", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some"]); + .get_matches_from_safe(vec![ + "", "-o", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", + "some", "some", + ]); assert!(r.is_ok()); let m = r.unwrap(); assert!(m.is_present("o")); @@ -183,8 +173,10 @@ fn lots_o_vals() { #[test] fn opts_using_long_space() { let r = App::new("opts") - .args(&[Arg::from_usage("--flag [flag] 'some flag'"), - Arg::from_usage("--color [color] 'some other flag'")]) + .args(&[ + Arg::from_usage("--flag [flag] 'some flag'"), + Arg::from_usage("--color [color] 'some other flag'"), + ]) .get_matches_from_safe(vec!["", "--flag", "some", "--color", "other"]); assert!(r.is_ok()); let m = r.unwrap(); @@ -197,8 +189,10 @@ fn opts_using_long_space() { #[test] fn opts_using_long_equals() { let r = App::new("opts") - .args(&[Arg::from_usage("--flag [flag] 'some flag'"), - Arg::from_usage("--color [color] 'some other flag'")]) + .args(&[ + Arg::from_usage("--flag [flag] 'some flag'"), + Arg::from_usage("--color [color] 'some other flag'"), + ]) .get_matches_from_safe(vec!["", "--flag=some", "--color=other"]); assert!(r.is_ok()); let m = r.unwrap(); @@ -211,8 +205,10 @@ fn opts_using_long_equals() { #[test] fn opts_using_mixed() { let r = App::new("opts") - .args(&[Arg::from_usage("-f, --flag [flag] 'some flag'"), - Arg::from_usage("-c, --color [color] 'some other flag'")]) + .args(&[ + Arg::from_usage("-f, --flag [flag] 'some flag'"), + Arg::from_usage("-c, --color [color] 'some other flag'"), + ]) .get_matches_from_safe(vec!["", "-f", "some", "--color", "other"]); assert!(r.is_ok()); let m = r.unwrap(); @@ -225,8 +221,10 @@ fn opts_using_mixed() { #[test] fn opts_using_mixed2() { let r = App::new("opts") - .args(&[Arg::from_usage("-f, --flag [flag] 'some flag'"), - Arg::from_usage("-c, --color [color] 'some other flag'")]) + .args(&[ + Arg::from_usage("-f, --flag [flag] 'some flag'"), + Arg::from_usage("-c, --color [color] 'some other flag'"), + ]) .get_matches_from_safe(vec!["", "--flag=some", "-c", "other"]); assert!(r.is_ok()); let m = r.unwrap(); @@ -350,7 +348,11 @@ fn leading_hyphen_with_flag_before() { #[test] fn leading_hyphen_with_only_pos_follows() { let r = App::new("mvae") - .arg(Arg::from_usage("-o [opt]... 'some opt'").number_of_values(1).allow_hyphen_values(true)) + .arg( + Arg::from_usage("-o [opt]... 'some opt'") + .number_of_values(1) + .allow_hyphen_values(true), + ) .arg_from_usage("[arg] 'some arg'") .get_matches_from_safe(vec!["", "-o", "-2", "--", "val"]); assert!(r.is_ok(), "{:?}", r); @@ -361,12 +363,14 @@ fn leading_hyphen_with_only_pos_follows() { } #[test] -#[cfg(feature="suggestions")] +#[cfg(feature = "suggestions")] fn did_you_mean() { - assert!(test::compare_output(test::complex_app(), - "clap-test --optio=foo", - DYM, - true)); + assert!(test::compare_output( + test::complex_app(), + "clap-test --optio=foo", + DYM, + true + )); } #[test] @@ -408,7 +412,7 @@ fn issue_1105_setup(argv: Vec<&'static str>) -> Result, clap #[test] fn issue_1105_empty_value_long_fail() { - let r = issue_1105_setup(vec!["app", "--option", "--flag"]); + let r = issue_1105_setup(vec!["app", "--option", "--flag"]); assert!(r.is_err()); assert_eq!(r.unwrap_err().kind, ErrorKind::EmptyValue); } @@ -423,7 +427,7 @@ fn issue_1105_empty_value_long_explicit() { #[test] fn issue_1105_empty_value_long_equals() { - let r = issue_1105_setup(vec!["app", "--option="]); + let r = issue_1105_setup(vec!["app", "--option="]); assert!(r.is_ok()); let m = r.unwrap(); assert_eq!(m.value_of("option"), Some("")); diff --git a/tests/positionals.rs b/tests/positionals.rs index bf0f79fa6a2..4fee1b7b848 100644 --- a/tests/positionals.rs +++ b/tests/positionals.rs @@ -5,8 +5,10 @@ use clap::{App, Arg, ErrorKind}; #[test] fn only_pos_follow() { let r = App::new("onlypos") - .args(&[Arg::from_usage("-f [flag] 'some opt'"), - Arg::from_usage("[arg] 'some arg'")]) + .args(&[ + Arg::from_usage("-f [flag] 'some opt'"), + Arg::from_usage("[arg] 'some arg'"), + ]) .get_matches_from_safe(vec!["", "--", "-f"]); assert!(r.is_ok()); let m = r.unwrap(); @@ -20,11 +22,13 @@ fn issue_946() { let r = App::new("compiletest") .setting(clap::AppSettings::AllowLeadingHyphen) .args_from_usage("--exact 'filters match exactly'") - .arg(clap::Arg::with_name("filter") - .index(1) - .takes_value(true) - .help("filters to apply to output")) - .get_matches_from_safe(vec!["compiletest", "--exact"]); + .arg( + clap::Arg::with_name("filter") + .index(1) + .takes_value(true) + .help("filters to apply to output"), + ) + .get_matches_from_safe(vec!["compiletest", "--exact"]); assert!(r.is_ok(), "{:#?}", r); let matches = r.unwrap(); @@ -37,9 +41,8 @@ fn positional() { let r = App::new("positional") .args(&[ Arg::from_usage("-f, --flag 'some flag'"), - Arg::with_name("positional") - .index(1) - ]) + Arg::with_name("positional").index(1), + ]) .get_matches_from_safe(vec!["", "-f", "test"]); assert!(r.is_ok(), "{:#?}", r); let m = r.unwrap(); @@ -50,9 +53,8 @@ fn positional() { let m = App::new("positional") .args(&[ Arg::from_usage("-f, --flag 'some flag'"), - Arg::with_name("positional") - .index(1) - ]) + Arg::with_name("positional").index(1), + ]) .get_matches_from(vec!["", "test", "--flag"]); assert!(m.is_present("positional")); assert!(m.is_present("flag")); @@ -62,10 +64,9 @@ fn positional() { #[test] fn lots_o_vals() { let r = App::new("opts") - .arg( - Arg::from_usage("[opt]... 'some pos'"), - ) - .get_matches_from_safe(vec!["", + .arg(Arg::from_usage("[opt]... 'some pos'")) + .get_matches_from_safe(vec![ + "", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", @@ -92,8 +93,8 @@ fn lots_o_vals() { "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", - "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", "some", - ]); + "some", + ]); assert!(r.is_ok()); let m = r.unwrap(); assert!(m.is_present("opt")); @@ -105,16 +106,17 @@ fn positional_multiple() { let r = App::new("positional_multiple") .args(&[ Arg::from_usage("-f, --flag 'some flag'"), - Arg::with_name("positional") - .index(1) - .multiple(true) - ]) + Arg::with_name("positional").index(1).multiple(true), + ]) .get_matches_from_safe(vec!["", "-f", "test1", "test2", "test3"]); assert!(r.is_ok(), "{:#?}", r); let m = r.unwrap(); assert!(m.is_present("positional")); assert!(m.is_present("flag")); - assert_eq!(&*m.values_of("positional").unwrap().collect::>(), &["test1", "test2", "test3"]); + assert_eq!( + &*m.values_of("positional").unwrap().collect::>(), + &["test1", "test2", "test3"] + ); } #[test] @@ -122,16 +124,17 @@ fn positional_multiple_3() { let r = App::new("positional_multiple") .args(&[ Arg::from_usage("-f, --flag 'some flag'"), - Arg::with_name("positional") - .index(1) - .multiple(true) - ]) + Arg::with_name("positional").index(1).multiple(true), + ]) .get_matches_from_safe(vec!["", "test1", "test2", "test3", "--flag"]); assert!(r.is_ok(), "{:#?}", r); let m = r.unwrap(); assert!(m.is_present("positional")); assert!(m.is_present("flag")); - assert_eq!(&*m.values_of("positional").unwrap().collect::>(), &["test1", "test2", "test3"]); + assert_eq!( + &*m.values_of("positional").unwrap().collect::>(), + &["test1", "test2", "test3"] + ); } #[test] @@ -139,9 +142,8 @@ fn positional_multiple_2() { let result = App::new("positional_multiple") .args(&[ Arg::from_usage("-f, --flag 'some flag'"), - Arg::with_name("positional") - .index(1) - ]) + Arg::with_name("positional").index(1), + ]) .get_matches_from_safe(vec!["", "-f", "test1", "test2", "test3"]); assert!(result.is_err()); let err = result.err().unwrap(); @@ -155,23 +157,24 @@ fn positional_possible_values() { Arg::from_usage("-f, --flag 'some flag'"), Arg::with_name("positional") .index(1) - .possible_value("test123") - ]) + .possible_value("test123"), + ]) .get_matches_from_safe(vec!["", "-f", "test123"]); assert!(r.is_ok(), "{:#?}", r); let m = r.unwrap(); assert!(m.is_present("positional")); assert!(m.is_present("flag")); - assert_eq!(&*m.values_of("positional").unwrap().collect::>(), &["test123"]); + assert_eq!( + &*m.values_of("positional").unwrap().collect::>(), + &["test123"] + ); } #[test] fn create_positional() { let _ = App::new("test") - .arg(Arg::with_name("test") - .index(1) - .help("testing testing")) - .get_matches_from(vec![""]); + .arg(Arg::with_name("test").index(1).help("testing testing")) + .get_matches_from(vec![""]); } #[test] @@ -183,13 +186,17 @@ fn positional_hyphen_does_not_panic() { #[test] fn single_positional_usage_string() { - let m = App::new("test").arg_from_usage("[FILE] 'some file'").get_matches_from(vec!["test"]); + let m = App::new("test") + .arg_from_usage("[FILE] 'some file'") + .get_matches_from(vec!["test"]); assert_eq!(m.usage(), "USAGE:\n test [FILE]"); } #[test] fn single_positional_multiple_usage_string() { - let m = App::new("test").arg_from_usage("[FILE]... 'some file'").get_matches_from(vec!["test"]); + let m = App::new("test") + .arg_from_usage("[FILE]... 'some file'") + .get_matches_from(vec!["test"]); assert_eq!(m.usage(), "USAGE:\n test [FILE]..."); } diff --git a/tests/posix_compatible.rs b/tests/posix_compatible.rs index 26d9f71f39e..ab94aae31e8 100644 --- a/tests/posix_compatible.rs +++ b/tests/posix_compatible.rs @@ -5,8 +5,8 @@ use clap::{App, Arg, ErrorKind}; #[test] fn flag_overrides_itself() { let res = App::new("posix") - .arg(Arg::from_usage("--flag 'some flag'").overrides_with("flag")) - .get_matches_from_safe(vec!["", "--flag", "--flag"]); + .arg(Arg::from_usage("--flag 'some flag'").overrides_with("flag")) + .get_matches_from_safe(vec!["", "--flag", "--flag"]); assert!(res.is_ok()); let m = res.unwrap(); assert!(m.is_present("flag")); @@ -16,8 +16,8 @@ fn flag_overrides_itself() { #[test] fn mult_flag_overrides_itself() { let res = App::new("posix") - .arg(Arg::from_usage("--flag... 'some flag'").overrides_with("flag")) - .get_matches_from_safe(vec!["", "--flag", "--flag", "--flag", "--flag"]); + .arg(Arg::from_usage("--flag... 'some flag'").overrides_with("flag")) + .get_matches_from_safe(vec!["", "--flag", "--flag", "--flag", "--flag"]); assert!(res.is_ok()); let m = res.unwrap(); assert!(m.is_present("flag")); @@ -27,8 +27,8 @@ fn mult_flag_overrides_itself() { #[test] fn option_overrides_itself() { let res = App::new("posix") - .arg(Arg::from_usage("--opt [val] 'some option'").overrides_with("opt")) - .get_matches_from_safe(vec!["", "--opt=some", "--opt=other"]); + .arg(Arg::from_usage("--opt [val] 'some option'").overrides_with("opt")) + .get_matches_from_safe(vec!["", "--opt=some", "--opt=other"]); assert!(res.is_ok()); let m = res.unwrap(); assert!(m.is_present("opt")); @@ -39,70 +39,86 @@ fn option_overrides_itself() { #[test] fn mult_option_require_delim_overrides_itself() { let res = App::new("posix") - .arg(Arg::from_usage("--opt [val]... 'some option'") - .overrides_with("opt") - .number_of_values(1) - .require_delimiter(true)) - .get_matches_from_safe(vec!["", "--opt=some", "--opt=other", "--opt=one,two"]); + .arg( + Arg::from_usage("--opt [val]... 'some option'") + .overrides_with("opt") + .number_of_values(1) + .require_delimiter(true), + ) + .get_matches_from_safe(vec!["", "--opt=some", "--opt=other", "--opt=one,two"]); assert!(res.is_ok()); let m = res.unwrap(); assert!(m.is_present("opt")); assert_eq!(m.occurrences_of("opt"), 3); - assert_eq!(m.values_of("opt").unwrap().collect::>(), &["some", "other", "one", "two"]); + assert_eq!( + m.values_of("opt").unwrap().collect::>(), + &["some", "other", "one", "two"] + ); } #[test] fn mult_option_overrides_itself() { let res = App::new("posix") - .arg(Arg::from_usage("--opt [val]... 'some option'") - .overrides_with("opt")) - .get_matches_from_safe(vec!["", "--opt", "first", "overides", "--opt", "some", "other", "val"]); + .arg(Arg::from_usage("--opt [val]... 'some option'").overrides_with("opt")) + .get_matches_from_safe(vec![ + "", "--opt", "first", "overides", "--opt", "some", "other", "val", + ]); assert!(res.is_ok()); let m = res.unwrap(); assert!(m.is_present("opt")); assert_eq!(m.occurrences_of("opt"), 2); - assert_eq!(m.values_of("opt").unwrap().collect::>(), &["first", "overides", "some", "other", "val"]); + assert_eq!( + m.values_of("opt").unwrap().collect::>(), + &["first", "overides", "some", "other", "val"] + ); } #[test] fn option_use_delim_false_override_itself() { - let m = App::new("posix") - .arg(Arg::from_usage("--opt [val] 'some option'") - .overrides_with("opt") - .use_delimiter(false)) - .get_matches_from(vec!["", "--opt=some,other", "--opt=one,two"]); + .arg( + Arg::from_usage("--opt [val] 'some option'") + .overrides_with("opt") + .use_delimiter(false), + ) + .get_matches_from(vec!["", "--opt=some,other", "--opt=one,two"]); assert!(m.is_present("opt")); assert_eq!(m.occurrences_of("opt"), 1); - assert_eq!(m.values_of("opt").unwrap().collect::>(), &["one,two"]); + assert_eq!( + m.values_of("opt").unwrap().collect::>(), + &["one,two"] + ); } #[test] fn pos_mult_overrides_itself() { // opts with multiple let res = App::new("posix") - .arg(Arg::from_usage("[val]... 'some pos'").overrides_with("val")) - .get_matches_from_safe(vec!["", "some", "other", "value"]); + .arg(Arg::from_usage("[val]... 'some pos'").overrides_with("val")) + .get_matches_from_safe(vec!["", "some", "other", "value"]); assert!(res.is_ok()); let m = res.unwrap(); assert!(m.is_present("val")); assert_eq!(m.occurrences_of("val"), 3); - assert_eq!(m.values_of("val").unwrap().collect::>(), &["some", "other", "value"]); + assert_eq!( + m.values_of("val").unwrap().collect::>(), + &["some", "other", "value"] + ); } #[test] fn posix_compatible_flags_long() { let m = App::new("posix") - .arg(Arg::from_usage("--flag 'some flag'").overrides_with("color")) - .arg(Arg::from_usage("--color 'some other flag'")) - .get_matches_from(vec!["", "--flag", "--color"]); + .arg(Arg::from_usage("--flag 'some flag'").overrides_with("color")) + .arg(Arg::from_usage("--color 'some other flag'")) + .get_matches_from(vec!["", "--flag", "--color"]); assert!(m.is_present("color")); assert!(!m.is_present("flag")); let m = App::new("posix") - .arg(Arg::from_usage("--flag 'some flag'").overrides_with("color")) - .arg(Arg::from_usage("--color 'some other flag'")) - .get_matches_from(vec!["", "--color", "--flag"]); + .arg(Arg::from_usage("--flag 'some flag'").overrides_with("color")) + .arg(Arg::from_usage("--color 'some other flag'")) + .get_matches_from(vec!["", "--color", "--flag"]); assert!(!m.is_present("color")); assert!(m.is_present("flag")); } @@ -110,16 +126,16 @@ fn posix_compatible_flags_long() { #[test] fn posix_compatible_flags_short() { let m = App::new("posix") - .arg(Arg::from_usage("-f, --flag 'some flag'").overrides_with("color")) - .arg(Arg::from_usage("-c, --color 'some other flag'")) - .get_matches_from(vec!["", "-f", "-c"]); + .arg(Arg::from_usage("-f, --flag 'some flag'").overrides_with("color")) + .arg(Arg::from_usage("-c, --color 'some other flag'")) + .get_matches_from(vec!["", "-f", "-c"]); assert!(m.is_present("color")); assert!(!m.is_present("flag")); let m = App::new("posix") - .arg(Arg::from_usage("-f, --flag 'some flag'").overrides_with("color")) - .arg(Arg::from_usage("-c, --color 'some other flag'")) - .get_matches_from(vec!["", "-c", "-f"]); + .arg(Arg::from_usage("-f, --flag 'some flag'").overrides_with("color")) + .arg(Arg::from_usage("-c, --color 'some other flag'")) + .get_matches_from(vec!["", "-c", "-f"]); assert!(!m.is_present("color")); assert!(m.is_present("flag")); } @@ -127,17 +143,17 @@ fn posix_compatible_flags_short() { #[test] fn posix_compatible_opts_long() { let m = App::new("posix") - .arg(Arg::from_usage("--flag [flag] 'some flag'").overrides_with("color")) - .arg(Arg::from_usage("--color [color] 'some other flag'")) - .get_matches_from(vec!["", "--flag", "some" ,"--color", "other"]); + .arg(Arg::from_usage("--flag [flag] 'some flag'").overrides_with("color")) + .arg(Arg::from_usage("--color [color] 'some other flag'")) + .get_matches_from(vec!["", "--flag", "some", "--color", "other"]); assert!(m.is_present("color")); assert_eq!(m.value_of("color").unwrap(), "other"); assert!(!m.is_present("flag")); let m = App::new("posix") - .arg(Arg::from_usage("--flag [flag] 'some flag'").overrides_with("color")) - .arg(Arg::from_usage("--color [color] 'some other flag'")) - .get_matches_from(vec!["", "--color", "some" ,"--flag", "other"]); + .arg(Arg::from_usage("--flag [flag] 'some flag'").overrides_with("color")) + .arg(Arg::from_usage("--color [color] 'some other flag'")) + .get_matches_from(vec!["", "--color", "some", "--flag", "other"]); assert!(!m.is_present("color")); assert!(m.is_present("flag")); assert_eq!(m.value_of("flag").unwrap(), "other"); @@ -146,17 +162,17 @@ fn posix_compatible_opts_long() { #[test] fn posix_compatible_opts_long_equals() { let m = App::new("posix") - .arg(Arg::from_usage("--flag [flag] 'some flag'").overrides_with("color")) - .arg(Arg::from_usage("--color [color] 'some other flag'")) - .get_matches_from(vec!["", "--flag=some" ,"--color=other"]); + .arg(Arg::from_usage("--flag [flag] 'some flag'").overrides_with("color")) + .arg(Arg::from_usage("--color [color] 'some other flag'")) + .get_matches_from(vec!["", "--flag=some", "--color=other"]); assert!(m.is_present("color")); assert_eq!(m.value_of("color").unwrap(), "other"); assert!(!m.is_present("flag")); let m = App::new("posix") - .arg(Arg::from_usage("--flag [flag] 'some flag'").overrides_with("color")) - .arg(Arg::from_usage("--color [color] 'some other flag'")) - .get_matches_from(vec!["", "--color=some" ,"--flag=other"]); + .arg(Arg::from_usage("--flag [flag] 'some flag'").overrides_with("color")) + .arg(Arg::from_usage("--color [color] 'some other flag'")) + .get_matches_from(vec!["", "--color=some", "--flag=other"]); assert!(!m.is_present("color")); assert!(m.is_present("flag")); assert_eq!(m.value_of("flag").unwrap(), "other"); @@ -165,17 +181,17 @@ fn posix_compatible_opts_long_equals() { #[test] fn posix_compatible_opts_short() { let m = App::new("posix") - .arg(Arg::from_usage("-f [flag] 'some flag'").overrides_with("c")) - .arg(Arg::from_usage("-c [color] 'some other flag'")) - .get_matches_from(vec!["", "-f", "some", "-c", "other"]); + .arg(Arg::from_usage("-f [flag] 'some flag'").overrides_with("c")) + .arg(Arg::from_usage("-c [color] 'some other flag'")) + .get_matches_from(vec!["", "-f", "some", "-c", "other"]); assert!(m.is_present("c")); assert_eq!(m.value_of("c").unwrap(), "other"); assert!(!m.is_present("f")); let m = App::new("posix") - .arg(Arg::from_usage("-f [flag] 'some flag'").overrides_with("c")) - .arg(Arg::from_usage("-c [color] 'some other flag'")) - .get_matches_from(vec!["", "-c", "some", "-f", "other"]); + .arg(Arg::from_usage("-f [flag] 'some flag'").overrides_with("c")) + .arg(Arg::from_usage("-c [color] 'some other flag'")) + .get_matches_from(vec!["", "-c", "some", "-f", "other"]); assert!(!m.is_present("c")); assert!(m.is_present("f")); assert_eq!(m.value_of("f").unwrap(), "other"); @@ -184,11 +200,9 @@ fn posix_compatible_opts_short() { #[test] fn conflict_overriden() { let m = App::new("conflict_overriden") - .arg(Arg::from_usage("-f, --flag 'some flag'") - .conflicts_with("debug")) + .arg(Arg::from_usage("-f, --flag 'some flag'").conflicts_with("debug")) .arg(Arg::from_usage("-d, --debug 'other flag'")) - .arg(Arg::from_usage("-c, --color 'third flag'") - .overrides_with("flag")) + .arg(Arg::from_usage("-c, --color 'third flag'").overrides_with("flag")) .get_matches_from(vec!["", "-f", "-c", "-d"]); assert!(m.is_present("color")); assert!(!m.is_present("flag")); @@ -198,11 +212,9 @@ fn conflict_overriden() { #[test] fn conflict_overriden_2() { let result = App::new("conflict_overriden") - .arg(Arg::from_usage("-f, --flag 'some flag'") - .conflicts_with("debug")) + .arg(Arg::from_usage("-f, --flag 'some flag'").conflicts_with("debug")) .arg(Arg::from_usage("-d, --debug 'other flag'")) - .arg(Arg::from_usage("-c, --color 'third flag'") - .overrides_with("flag")) + .arg(Arg::from_usage("-c, --color 'third flag'").overrides_with("flag")) .get_matches_from_safe(vec!["", "-f", "-d", "-c"]); assert!(result.is_ok()); let m = result.unwrap(); @@ -214,11 +226,9 @@ fn conflict_overriden_2() { #[test] fn conflict_overriden_3() { let result = App::new("conflict_overriden") - .arg(Arg::from_usage("-f, --flag 'some flag'") - .conflicts_with("debug")) + .arg(Arg::from_usage("-f, --flag 'some flag'").conflicts_with("debug")) .arg(Arg::from_usage("-d, --debug 'other flag'")) - .arg(Arg::from_usage("-c, --color 'third flag'") - .overrides_with("flag")) + .arg(Arg::from_usage("-c, --color 'third flag'").overrides_with("flag")) .get_matches_from_safe(vec!["", "-d", "-c", "-f"]); assert!(result.is_err()); let err = result.err().unwrap(); @@ -228,11 +238,9 @@ fn conflict_overriden_3() { #[test] fn conflict_overriden_4() { let m = App::new("conflict_overriden") - .arg(Arg::from_usage("-f, --flag 'some flag'") - .conflicts_with("debug")) + .arg(Arg::from_usage("-f, --flag 'some flag'").conflicts_with("debug")) .arg(Arg::from_usage("-d, --debug 'other flag'")) - .arg(Arg::from_usage("-c, --color 'third flag'") - .overrides_with("flag")) + .arg(Arg::from_usage("-c, --color 'third flag'").overrides_with("flag")) .get_matches_from(vec!["", "-d", "-f", "-c"]); assert!(m.is_present("color")); assert!(!m.is_present("flag")); @@ -242,11 +250,8 @@ fn conflict_overriden_4() { #[test] fn pos_required_overridden_by_flag() { let result = App::new("require_overriden") - .arg(Arg::with_name("pos") - .index(1) - .required(true)) - .arg(Arg::from_usage("-c, --color 'some flag'") - .overrides_with("pos")) + .arg(Arg::with_name("pos").index(1).required(true)) + .arg(Arg::from_usage("-c, --color 'some flag'").overrides_with("pos")) .get_matches_from_safe(vec!["", "test", "-c"]); assert!(result.is_ok(), "{:?}", result.unwrap_err()); } @@ -254,10 +259,8 @@ fn pos_required_overridden_by_flag() { #[test] fn require_overriden_2() { let m = App::new("require_overriden") - .arg(Arg::with_name("req_pos") - .required(true)) - .arg(Arg::from_usage("-c, --color 'other flag'") - .overrides_with("req_pos")) + .arg(Arg::with_name("req_pos").required(true)) + .arg(Arg::from_usage("-c, --color 'other flag'").overrides_with("req_pos")) .get_matches_from(vec!["", "-c", "req_pos"]); assert!(!m.is_present("color")); assert!(m.is_present("req_pos")); @@ -266,11 +269,9 @@ fn require_overriden_2() { #[test] fn require_overriden_3() { let m = App::new("require_overriden") - .arg(Arg::from_usage("-f, --flag 'some flag'") - .requires("debug")) + .arg(Arg::from_usage("-f, --flag 'some flag'").requires("debug")) .arg(Arg::from_usage("-d, --debug 'other flag'")) - .arg(Arg::from_usage("-c, --color 'third flag'") - .overrides_with("flag")) + .arg(Arg::from_usage("-c, --color 'third flag'").overrides_with("flag")) .get_matches_from(vec!["", "-f", "-c"]); assert!(m.is_present("color")); assert!(!m.is_present("flag")); @@ -280,11 +281,9 @@ fn require_overriden_3() { #[test] fn require_overriden_4() { let result = App::new("require_overriden") - .arg(Arg::from_usage("-f, --flag 'some flag'") - .requires("debug")) + .arg(Arg::from_usage("-f, --flag 'some flag'").requires("debug")) .arg(Arg::from_usage("-d, --debug 'other flag'")) - .arg(Arg::from_usage("-c, --color 'third flag'") - .overrides_with("flag")) + .arg(Arg::from_usage("-c, --color 'third flag'").overrides_with("flag")) .get_matches_from_safe(vec!["", "-c", "-f"]); assert!(result.is_err()); let err = result.err().unwrap(); diff --git a/tests/possible_values.rs b/tests/possible_values.rs index 80772bd244d..c930820d72c 100644 --- a/tests/possible_values.rs +++ b/tests/possible_values.rs @@ -200,12 +200,11 @@ fn case_insensitive() { .get_matches_from_safe(vec!["pv", "--option", "TeSt123"]); assert!(m.is_ok()); - assert!( - m.unwrap() - .value_of("option") - .unwrap() - .eq_ignore_ascii_case("test123") - ); + assert!(m + .unwrap() + .value_of("option") + .unwrap() + .eq_ignore_ascii_case("test123")); } #[test] diff --git a/tests/propagate_globals.rs b/tests/propagate_globals.rs index ee77ce0a862..ff39050b839 100644 --- a/tests/propagate_globals.rs +++ b/tests/propagate_globals.rs @@ -4,27 +4,26 @@ extern crate regex; #[cfg(test)] mod tests { include!("../clap-test.rs"); - use clap::{App, Arg, SubCommand, ArgMatches}; + use clap::{App, Arg, ArgMatches, SubCommand}; fn get_app() -> App<'static, 'static> { App::new("myprog") - .arg(Arg::with_name("GLOBAL_ARG") - .long("global-arg") - .help( - "Specifies something needed by the subcommands", - ) - .global(true) - .takes_value(true) - .default_value("default_value")) - .arg(Arg::with_name("GLOBAL_FLAG") - .long("global-flag") - .help( - "Specifies something needed by the subcommands", - ) - .multiple(true) - .global(true)) - .subcommand(SubCommand::with_name("outer") - .subcommand(SubCommand::with_name("inner"))) + .arg( + Arg::with_name("GLOBAL_ARG") + .long("global-arg") + .help("Specifies something needed by the subcommands") + .global(true) + .takes_value(true) + .default_value("default_value"), + ) + .arg( + Arg::with_name("GLOBAL_FLAG") + .long("global-flag") + .help("Specifies something needed by the subcommands") + .multiple(true) + .global(true), + ) + .subcommand(SubCommand::with_name("outer").subcommand(SubCommand::with_name("inner"))) } fn get_matches(app: App<'static, 'static>, argv: &'static str) -> ArgMatches<'static> { @@ -32,22 +31,31 @@ mod tests { } fn get_outer_matches<'a>(m: &'a ArgMatches<'static>) -> &'a ArgMatches<'static> { - m.subcommand_matches("outer").expect("could not access outer subcommand") + m.subcommand_matches("outer") + .expect("could not access outer subcommand") } fn get_inner_matches<'a>(m: &'a ArgMatches<'static>) -> &'a ArgMatches<'static> { - get_outer_matches(m).subcommand_matches("inner").expect("could not access inner subcommand") + get_outer_matches(m) + .subcommand_matches("inner") + .expect("could not access inner subcommand") } fn top_can_access_arg>>(m: &ArgMatches<'static>, val: T) -> bool { m.value_of("GLOBAL_ARG") == val.into() } - fn inner_can_access_arg>>(m: &ArgMatches<'static>, val: T) -> bool { + fn inner_can_access_arg>>( + m: &ArgMatches<'static>, + val: T, + ) -> bool { get_inner_matches(m).value_of("GLOBAL_ARG") == val.into() } - fn outer_can_access_arg>>(m: &ArgMatches<'static>, val: T) -> bool { + fn outer_can_access_arg>>( + m: &ArgMatches<'static>, + val: T, + ) -> bool { get_outer_matches(m).value_of("GLOBAL_ARG") == val.into() } @@ -127,7 +135,7 @@ mod tests { assert!(inner_can_access_flag(&m, true, 1)); assert!(outer_can_access_flag(&m, true, 1)); } - + #[test] fn global_flag_2x_used_top_level() { let m = get_matches(get_app(), "myprog --global-flag --global-flag outer inner"); diff --git a/tests/require.rs b/tests/require.rs index 7121aa5e176..844b52ab2fe 100644 --- a/tests/require.rs +++ b/tests/require.rs @@ -3,7 +3,7 @@ extern crate regex; include!("../clap-test.rs"); -use clap::{App, Arg, ErrorKind, ArgGroup}; +use clap::{App, Arg, ArgGroup, ErrorKind}; static REQUIRE_EQUALS: &'static str = "error: The following required arguments were not provided: --opt= @@ -22,7 +22,8 @@ USAGE: For more information try --help"; -static COND_REQ_IN_USAGE: &'static str = "error: The following required arguments were not provided: +static COND_REQ_IN_USAGE: &'static str = + "error: The following required arguments were not provided: --output USAGE: @@ -43,13 +44,17 @@ For more information try --help"; #[test] fn issue_1158_conflicting_requirements() { let app = App::new("example") - .arg(Arg::from_usage("-c, --config [FILE] 'Custom config file.'") - .required_unless("ID") - .conflicts_with("ID")) - .arg(Arg::from_usage("[ID] 'ID'") - .required_unless("config") - .conflicts_with("config") - .requires_all(&["x", "y", "z"])) + .arg( + Arg::from_usage("-c, --config [FILE] 'Custom config file.'") + .required_unless("ID") + .conflicts_with("ID"), + ) + .arg( + Arg::from_usage("[ID] 'ID'") + .required_unless("config") + .conflicts_with("config") + .requires_all(&["x", "y", "z"]), + ) .arg(Arg::from_usage("-x [X] 'X'")) .arg(Arg::from_usage("-y [Y] 'Y'")) .arg(Arg::from_usage("-z [Z] 'Z'")); @@ -60,13 +65,17 @@ fn issue_1158_conflicting_requirements() { #[test] fn issue_1158_conflicting_requirements_rev() { let res = App::new("example") - .arg(Arg::from_usage("-c, --config [FILE] 'Custom config file.'") - .required_unless("ID") - .conflicts_with("ID")) - .arg(Arg::from_usage("[ID] 'ID'") - .required_unless("config") - .conflicts_with("config") - .requires_all(&["x", "y", "z"])) + .arg( + Arg::from_usage("-c, --config [FILE] 'Custom config file.'") + .required_unless("ID") + .conflicts_with("ID"), + ) + .arg( + Arg::from_usage("[ID] 'ID'") + .required_unless("config") + .conflicts_with("config") + .requires_all(&["x", "y", "z"]), + ) .arg(Arg::from_usage("-x [X] 'X'")) .arg(Arg::from_usage("-y [Y] 'Y'")) .arg(Arg::from_usage("-z [Z] 'Z'")) @@ -122,9 +131,7 @@ fn option_required_2() { #[test] fn positional_required() { let result = App::new("positional_required") - .arg(Arg::with_name("flag") - .index(1) - .required(true)) + .arg(Arg::with_name("flag").index(1).required(true)) .get_matches_from_safe(vec![""]); assert!(result.is_err()); let err = result.err().unwrap(); @@ -134,9 +141,7 @@ fn positional_required() { #[test] fn positional_required_2() { let m = App::new("positional_required") - .arg(Arg::with_name("flag") - .index(1) - .required(true)) + .arg(Arg::with_name("flag").index(1).required(true)) .get_matches_from(vec!["", "someval"]); assert!(m.is_present("flag")); assert_eq!(m.value_of("flag").unwrap(), "someval"); @@ -146,10 +151,12 @@ fn positional_required_2() { fn group_required() { let result = App::new("group_required") .arg(Arg::from_usage("-f, --flag 'some flag'")) - .group(ArgGroup::with_name("gr") - .required(true) - .arg("some") - .arg("other")) + .group( + ArgGroup::with_name("gr") + .required(true) + .arg("some") + .arg("other"), + ) .arg(Arg::from_usage("--some 'some arg'")) .arg(Arg::from_usage("--other 'other arg'")) .get_matches_from_safe(vec!["", "-f"]); @@ -162,10 +169,12 @@ fn group_required() { fn group_required_2() { let m = App::new("group_required") .arg(Arg::from_usage("-f, --flag 'some flag'")) - .group(ArgGroup::with_name("gr") - .required(true) - .arg("some") - .arg("other")) + .group( + ArgGroup::with_name("gr") + .required(true) + .arg("some") + .arg("other"), + ) .arg(Arg::from_usage("--some 'some arg'")) .arg(Arg::from_usage("--other 'other arg'")) .get_matches_from(vec!["", "-f", "--some"]); @@ -178,10 +187,12 @@ fn group_required_2() { fn group_required_3() { let m = App::new("group_required") .arg(Arg::from_usage("-f, --flag 'some flag'")) - .group(ArgGroup::with_name("gr") - .required(true) - .arg("some") - .arg("other")) + .group( + ArgGroup::with_name("gr") + .required(true) + .arg("some") + .arg("other"), + ) .arg(Arg::from_usage("--some 'some arg'")) .arg(Arg::from_usage("--other 'other arg'")) .get_matches_from(vec!["", "-f", "--other"]); @@ -194,9 +205,7 @@ fn group_required_3() { fn arg_require_group() { let result = App::new("arg_require_group") .arg(Arg::from_usage("-f, --flag 'some flag'").requires("gr")) - .group(ArgGroup::with_name("gr") - .arg("some") - .arg("other")) + .group(ArgGroup::with_name("gr").arg("some").arg("other")) .arg(Arg::from_usage("--some 'some arg'")) .arg(Arg::from_usage("--other 'other arg'")) .get_matches_from_safe(vec!["", "-f"]); @@ -209,9 +218,7 @@ fn arg_require_group() { fn arg_require_group_2() { let m = App::new("arg_require_group") .arg(Arg::from_usage("-f, --flag 'some flag'").requires("gr")) - .group(ArgGroup::with_name("gr") - .arg("some") - .arg("other")) + .group(ArgGroup::with_name("gr").arg("some").arg("other")) .arg(Arg::from_usage("--some 'some arg'")) .arg(Arg::from_usage("--other 'other arg'")) .get_matches_from(vec!["", "-f", "--some"]); @@ -224,9 +231,7 @@ fn arg_require_group_2() { fn arg_require_group_3() { let m = App::new("arg_require_group") .arg(Arg::from_usage("-f, --flag 'some flag'").requires("gr")) - .group(ArgGroup::with_name("gr") - .arg("some") - .arg("other")) + .group(ArgGroup::with_name("gr").arg("some").arg("other")) .arg(Arg::from_usage("--some 'some arg'")) .arg(Arg::from_usage("--other 'other arg'")) .get_matches_from(vec!["", "-f", "--other"]); @@ -240,16 +245,25 @@ fn arg_require_group_3() { #[test] fn issue_753() { let m = App::new("test") - .arg(Arg::from_usage("-l, --list 'List available interfaces (and stop there)'")) - .arg(Arg::from_usage("-i, --iface=[INTERFACE] 'Ethernet interface for fetching NTP packets'") - .required_unless("list")) - .arg(Arg::from_usage("-f, --file=[TESTFILE] 'Fetch NTP packets from pcap file'") - .conflicts_with("iface") - .required_unless("list")) - .arg(Arg::from_usage("-s, --server=[SERVER_IP] 'NTP server IP address'") - .required_unless("list")) - .arg(Arg::from_usage("-p, --port=[SERVER_PORT] 'NTP server port'") - .default_value("123")) + .arg(Arg::from_usage( + "-l, --list 'List available interfaces (and stop there)'", + )) + .arg( + Arg::from_usage( + "-i, --iface=[INTERFACE] 'Ethernet interface for fetching NTP packets'", + ) + .required_unless("list"), + ) + .arg( + Arg::from_usage("-f, --file=[TESTFILE] 'Fetch NTP packets from pcap file'") + .conflicts_with("iface") + .required_unless("list"), + ) + .arg( + Arg::from_usage("-s, --server=[SERVER_IP] 'NTP server IP address'") + .required_unless("list"), + ) + .arg(Arg::from_usage("-p, --port=[SERVER_PORT] 'NTP server port'").default_value("123")) .get_matches_from_safe(vec!["test", "--list"]); assert!(m.is_ok()); } @@ -257,10 +271,12 @@ fn issue_753() { #[test] fn required_unless() { let res = App::new("unlesstest") - .arg(Arg::with_name("cfg") - .required_unless("dbg") - .takes_value(true) - .long("config")) + .arg( + Arg::with_name("cfg") + .required_unless("dbg") + .takes_value(true) + .long("config"), + ) .arg(Arg::with_name("dbg").long("debug")) .get_matches_from_safe(vec!["unlesstest", "--debug"]); @@ -273,10 +289,12 @@ fn required_unless() { #[test] fn required_unless_err() { let res = App::new("unlesstest") - .arg(Arg::with_name("cfg") - .required_unless("dbg") - .takes_value(true) - .long("config")) + .arg( + Arg::with_name("cfg") + .required_unless("dbg") + .takes_value(true) + .long("config"), + ) .arg(Arg::with_name("dbg").long("debug")) .get_matches_from_safe(vec!["unlesstest"]); @@ -289,14 +307,14 @@ fn required_unless_err() { #[test] fn required_unless_all() { let res = App::new("unlessall") - .arg(Arg::with_name("cfg") - .required_unless_all(&["dbg", "infile"]) - .takes_value(true) - .long("config")) + .arg( + Arg::with_name("cfg") + .required_unless_all(&["dbg", "infile"]) + .takes_value(true) + .long("config"), + ) .arg(Arg::with_name("dbg").long("debug")) - .arg(Arg::with_name("infile") - .short("i") - .takes_value(true)) + .arg(Arg::with_name("infile").short("i").takes_value(true)) .get_matches_from_safe(vec!["unlessall", "--debug", "-i", "file"]); assert!(res.is_ok()); @@ -309,14 +327,14 @@ fn required_unless_all() { #[test] fn required_unless_all_err() { let res = App::new("unlessall") - .arg(Arg::with_name("cfg") - .required_unless_all(&["dbg", "infile"]) - .takes_value(true) - .long("config")) + .arg( + Arg::with_name("cfg") + .required_unless_all(&["dbg", "infile"]) + .takes_value(true) + .long("config"), + ) .arg(Arg::with_name("dbg").long("debug")) - .arg(Arg::with_name("infile") - .short("i") - .takes_value(true)) + .arg(Arg::with_name("infile").short("i").takes_value(true)) .get_matches_from_safe(vec!["unlessall", "--debug"]); assert!(res.is_err()); @@ -328,14 +346,14 @@ fn required_unless_all_err() { #[test] fn required_unless_one() { let res = App::new("unlessone") - .arg(Arg::with_name("cfg") - .required_unless_one(&["dbg", "infile"]) - .takes_value(true) - .long("config")) + .arg( + Arg::with_name("cfg") + .required_unless_one(&["dbg", "infile"]) + .takes_value(true) + .long("config"), + ) .arg(Arg::with_name("dbg").long("debug")) - .arg(Arg::with_name("infile") - .short("i") - .takes_value(true)) + .arg(Arg::with_name("infile").short("i").takes_value(true)) .get_matches_from_safe(vec!["unlessone", "--debug"]); assert!(res.is_ok()); @@ -349,14 +367,14 @@ fn required_unless_one_2() { // This tests that the required_unless_one works when the second arg in the array is used // instead of the first. let res = App::new("unlessone") - .arg(Arg::with_name("cfg") - .required_unless_one(&["dbg", "infile"]) - .takes_value(true) - .long("config")) + .arg( + Arg::with_name("cfg") + .required_unless_one(&["dbg", "infile"]) + .takes_value(true) + .long("config"), + ) .arg(Arg::with_name("dbg").long("debug")) - .arg(Arg::with_name("infile") - .short("i") - .takes_value(true)) + .arg(Arg::with_name("infile").short("i").takes_value(true)) .get_matches_from_safe(vec!["unlessone", "-i", "file"]); assert!(res.is_ok()); @@ -374,8 +392,9 @@ fn required_unless_one_works_with_short() { .arg( Arg::with_name("x") .short("x") - .required_unless_one(&["a", "b"]) - ).get_matches_from_safe(vec!["unlessone", "-a"]); + .required_unless_one(&["a", "b"]), + ) + .get_matches_from_safe(vec!["unlessone", "-a"]); assert!(res.is_ok()); } @@ -388,8 +407,9 @@ fn required_unless_one_works_with_short_err() { .arg( Arg::with_name("x") .short("x") - .required_unless_one(&["a", "b"]) - ).get_matches_from_safe(vec!["unlessone"]); + .required_unless_one(&["a", "b"]), + ) + .get_matches_from_safe(vec!["unlessone"]); assert!(!res.is_ok()); } @@ -399,10 +419,8 @@ fn required_unless_one_works_without() { let res = App::new("unlessone") .arg(Arg::with_name("a").conflicts_with("b").short("a")) .arg(Arg::with_name("b").short("b")) - .arg( - Arg::with_name("x") - .required_unless_one(&["a", "b"]) - ).get_matches_from_safe(vec!["unlessone", "-a"]); + .arg(Arg::with_name("x").required_unless_one(&["a", "b"])) + .get_matches_from_safe(vec!["unlessone", "-a"]); assert!(res.is_ok()); } @@ -415,8 +433,9 @@ fn required_unless_one_works_with_long() { .arg( Arg::with_name("x") .long("x_is_the_option") - .required_unless_one(&["a", "b"]) - ).get_matches_from_safe(vec!["unlessone", "-a"]); + .required_unless_one(&["a", "b"]), + ) + .get_matches_from_safe(vec!["unlessone", "-a"]); assert!(res.is_ok()); } @@ -424,14 +443,14 @@ fn required_unless_one_works_with_long() { #[test] fn required_unless_one_1() { let res = App::new("unlessone") - .arg(Arg::with_name("cfg") - .required_unless_one(&["dbg", "infile"]) - .takes_value(true) - .long("config")) + .arg( + Arg::with_name("cfg") + .required_unless_one(&["dbg", "infile"]) + .takes_value(true) + .long("config"), + ) .arg(Arg::with_name("dbg").long("debug")) - .arg(Arg::with_name("infile") - .short("i") - .takes_value(true)) + .arg(Arg::with_name("infile").short("i").takes_value(true)) .get_matches_from_safe(vec!["unlessone", "--debug"]); assert!(res.is_ok()); @@ -444,14 +463,14 @@ fn required_unless_one_1() { #[test] fn required_unless_one_err() { let res = App::new("unlessone") - .arg(Arg::with_name("cfg") - .required_unless_one(&["dbg", "infile"]) - .takes_value(true) - .long("config")) + .arg( + Arg::with_name("cfg") + .required_unless_one(&["dbg", "infile"]) + .takes_value(true) + .long("config"), + ) .arg(Arg::with_name("dbg").long("debug")) - .arg(Arg::with_name("infile") - .short("i") - .takes_value(true)) + .arg(Arg::with_name("infile").short("i").takes_value(true)) .get_matches_from_safe(vec!["unlessone"]); assert!(res.is_err()); @@ -460,7 +479,12 @@ fn required_unless_one_err() { #[test] fn missing_required_output() { - assert!(test::compare_output(test::complex_app(), "clap-test -F", MISSING_REQ, true)); + assert!(test::compare_output( + test::complex_app(), + "clap-test -F", + MISSING_REQ, + true + )); } // Conditional external requirements @@ -468,10 +492,12 @@ fn missing_required_output() { #[test] fn requires_if_present_val() { let res = App::new("unlessone") - .arg(Arg::with_name("cfg") - .requires_if("my.cfg", "extra") - .takes_value(true) - .long("config")) + .arg( + Arg::with_name("cfg") + .requires_if("my.cfg", "extra") + .takes_value(true) + .long("config"), + ) .arg(Arg::with_name("extra").long("extra")) .get_matches_from_safe(vec!["unlessone", "--config=my.cfg"]); @@ -482,10 +508,12 @@ fn requires_if_present_val() { #[test] fn requires_if_present_mult() { let res = App::new("unlessone") - .arg(Arg::with_name("cfg") - .requires_ifs(&[("my.cfg", "extra"), ("other.cfg", "other")]) - .takes_value(true) - .long("config")) + .arg( + Arg::with_name("cfg") + .requires_ifs(&[("my.cfg", "extra"), ("other.cfg", "other")]) + .takes_value(true) + .long("config"), + ) .arg(Arg::with_name("extra").long("extra")) .arg(Arg::with_name("other").long("other")) .get_matches_from_safe(vec!["unlessone", "--config=other.cfg"]); @@ -497,10 +525,12 @@ fn requires_if_present_mult() { #[test] fn requires_if_present_mult_pass() { let res = App::new("unlessone") - .arg(Arg::with_name("cfg") - .requires_ifs(&[("my.cfg", "extra"), ("other.cfg", "other")]) - .takes_value(true) - .long("config")) + .arg( + Arg::with_name("cfg") + .requires_ifs(&[("my.cfg", "extra"), ("other.cfg", "other")]) + .takes_value(true) + .long("config"), + ) .arg(Arg::with_name("extra").long("extra")) .arg(Arg::with_name("other").long("other")) .get_matches_from_safe(vec!["unlessone", "--config=some.cfg"]); @@ -512,10 +542,12 @@ fn requires_if_present_mult_pass() { #[test] fn requires_if_present_val_no_present_pass() { let res = App::new("unlessone") - .arg(Arg::with_name("cfg") - .requires_if("my.cfg", "extra") - .takes_value(true) - .long("config")) + .arg( + Arg::with_name("cfg") + .requires_if("my.cfg", "extra") + .takes_value(true) + .long("config"), + ) .arg(Arg::with_name("extra").long("extra")) .get_matches_from_safe(vec!["unlessone"]); @@ -527,13 +559,13 @@ fn requires_if_present_val_no_present_pass() { #[test] fn required_if_val_present_pass() { let res = App::new("ri") - .arg(Arg::with_name("cfg") - .required_if("extra", "val") - .takes_value(true) - .long("config")) - .arg(Arg::with_name("extra") - .takes_value(true) - .long("extra")) + .arg( + Arg::with_name("cfg") + .required_if("extra", "val") + .takes_value(true) + .long("config"), + ) + .arg(Arg::with_name("extra").takes_value(true).long("extra")) .get_matches_from_safe(vec!["ri", "--extra", "val", "--config", "my.cfg"]); assert!(res.is_ok()); @@ -542,13 +574,13 @@ fn required_if_val_present_pass() { #[test] fn required_if_val_present_fail() { let res = App::new("ri") - .arg(Arg::with_name("cfg") - .required_if("extra", "val") - .takes_value(true) - .long("config")) - .arg(Arg::with_name("extra") - .takes_value(true) - .long("extra")) + .arg( + Arg::with_name("cfg") + .required_if("extra", "val") + .takes_value(true) + .long("config"), + ) + .arg(Arg::with_name("extra").takes_value(true).long("extra")) .get_matches_from_safe(vec!["ri", "--extra", "val"]); assert!(res.is_err()); @@ -561,36 +593,44 @@ fn required_if_val_present_fail_error_output() { .version("1.0") .author("F0x06") .about("Arg test") - .arg(Arg::with_name("target") - .takes_value(true) - .required(true) - .possible_values(&["file", "stdout"]) - .long("target")) - .arg(Arg::with_name("input") - .takes_value(true) - .required(true) - .long("input")) - .arg(Arg::with_name("output") - .takes_value(true) - .required_if("target", "file") - .long("output")); + .arg( + Arg::with_name("target") + .takes_value(true) + .required(true) + .possible_values(&["file", "stdout"]) + .long("target"), + ) + .arg( + Arg::with_name("input") + .takes_value(true) + .required(true) + .long("input"), + ) + .arg( + Arg::with_name("output") + .takes_value(true) + .required_if("target", "file") + .long("output"), + ); - assert!(test::compare_output(app, - "test --input somepath --target file", - COND_REQ_IN_USAGE, - true)); + assert!(test::compare_output( + app, + "test --input somepath --target file", + COND_REQ_IN_USAGE, + true + )); } #[test] fn required_if_wrong_val() { let res = App::new("ri") - .arg(Arg::with_name("cfg") - .required_if("extra", "val") - .takes_value(true) - .long("config")) - .arg(Arg::with_name("extra") - .takes_value(true) - .long("extra")) + .arg( + Arg::with_name("cfg") + .required_if("extra", "val") + .takes_value(true) + .long("config"), + ) + .arg(Arg::with_name("extra").takes_value(true).long("extra")) .get_matches_from_safe(vec!["ri", "--extra", "other"]); assert!(res.is_ok()); @@ -599,16 +639,14 @@ fn required_if_wrong_val() { #[test] fn required_ifs_val_present_pass() { let res = App::new("ri") - .arg(Arg::with_name("cfg") - .required_ifs(&[("extra", "val"), ("option", "spec")]) - .takes_value(true) - .long("config")) - .arg(Arg::with_name("option") - .takes_value(true) - .long("option")) - .arg(Arg::with_name("extra") - .takes_value(true) - .long("extra")) + .arg( + Arg::with_name("cfg") + .required_ifs(&[("extra", "val"), ("option", "spec")]) + .takes_value(true) + .long("config"), + ) + .arg(Arg::with_name("option").takes_value(true).long("option")) + .arg(Arg::with_name("extra").takes_value(true).long("extra")) .get_matches_from_safe(vec!["ri", "--option", "spec", "--config", "my.cfg"]); assert!(res.is_ok()); @@ -618,16 +656,14 @@ fn required_ifs_val_present_pass() { #[test] fn required_ifs_val_present_fail() { let res = App::new("ri") - .arg(Arg::with_name("cfg") - .required_ifs(&[("extra", "val"), ("option", "spec")]) - .takes_value(true) - .long("config")) - .arg(Arg::with_name("extra") - .takes_value(true) - .long("extra")) - .arg(Arg::with_name("option") - .takes_value(true) - .long("option")) + .arg( + Arg::with_name("cfg") + .required_ifs(&[("extra", "val"), ("option", "spec")]) + .takes_value(true) + .long("config"), + ) + .arg(Arg::with_name("extra").takes_value(true).long("extra")) + .arg(Arg::with_name("option").takes_value(true).long("option")) .get_matches_from_safe(vec!["ri", "--option", "spec"]); assert!(res.is_err()); @@ -637,16 +673,14 @@ fn required_ifs_val_present_fail() { #[test] fn required_ifs_wrong_val() { let res = App::new("ri") - .arg(Arg::with_name("cfg") - .required_ifs(&[("extra", "val"), ("option", "spec")]) - .takes_value(true) - .long("config")) - .arg(Arg::with_name("extra") - .takes_value(true) - .long("extra")) - .arg(Arg::with_name("option") - .takes_value(true) - .long("option")) + .arg( + Arg::with_name("cfg") + .required_ifs(&[("extra", "val"), ("option", "spec")]) + .takes_value(true) + .long("config"), + ) + .arg(Arg::with_name("extra").takes_value(true).long("extra")) + .arg(Arg::with_name("option").takes_value(true).long("option")) .get_matches_from_safe(vec!["ri", "--option", "other"]); assert!(res.is_ok()); @@ -655,16 +689,14 @@ fn required_ifs_wrong_val() { #[test] fn required_ifs_wrong_val_mult_fail() { let res = App::new("ri") - .arg(Arg::with_name("cfg") - .required_ifs(&[("extra", "val"), ("option", "spec")]) - .takes_value(true) - .long("config")) - .arg(Arg::with_name("extra") - .takes_value(true) - .long("extra")) - .arg(Arg::with_name("option") - .takes_value(true) - .long("option")) + .arg( + Arg::with_name("cfg") + .required_ifs(&[("extra", "val"), ("option", "spec")]) + .takes_value(true) + .long("config"), + ) + .arg(Arg::with_name("extra").takes_value(true).long("extra")) + .arg(Arg::with_name("option").takes_value(true).long("option")) .get_matches_from_safe(vec!["ri", "--extra", "other", "--option", "spec"]); assert!(res.is_err()); @@ -673,16 +705,14 @@ fn required_ifs_wrong_val_mult_fail() { #[test] fn require_eq() { - let app = App::new("clap-test") - .version("v1.4.8") - .arg( - Arg::with_name("opt") + let app = App::new("clap-test").version("v1.4.8").arg( + Arg::with_name("opt") .long("opt") .short("o") .required(true) .require_equals(true) .value_name("FILE") - .help("some") - ); + .help("some"), + ); assert!(test::compare_output(app, "clap-test", REQUIRE_EQUALS, true)); } diff --git a/tests/subcommands.rs b/tests/subcommands.rs index 6257aaf0734..92ea8e81e2d 100644 --- a/tests/subcommands.rs +++ b/tests/subcommands.rs @@ -3,7 +3,7 @@ extern crate regex; include!("../clap-test.rs"); -use clap::{App, Arg, SubCommand, ErrorKind}; +use clap::{App, Arg, ErrorKind, SubCommand}; static VISIBLE_ALIAS_HELP: &'static str = "clap-test 2.6 @@ -45,12 +45,15 @@ For more information try --help"; #[test] fn subcommand() { let m = App::new("test") - .subcommand(SubCommand::with_name("some") - .arg(Arg::with_name("test") - .short("t") - .long("test") - .takes_value(true) - .help("testing testing"))) + .subcommand( + SubCommand::with_name("some").arg( + Arg::with_name("test") + .short("t") + .long("test") + .takes_value(true) + .help("testing testing"), + ), + ) .arg(Arg::with_name("other").long("other")) .get_matches_from(vec!["myprog", "some", "--test", "testing"]); @@ -63,12 +66,15 @@ fn subcommand() { #[test] fn subcommand_none_given() { let m = App::new("test") - .subcommand(SubCommand::with_name("some") - .arg(Arg::with_name("test") - .short("t") - .long("test") - .takes_value(true) - .help("testing testing"))) + .subcommand( + SubCommand::with_name("some").arg( + Arg::with_name("test") + .short("t") + .long("test") + .takes_value(true) + .help("testing testing"), + ), + ) .arg(Arg::with_name("other").long("other")) .get_matches_from(vec![""]); @@ -79,14 +85,14 @@ fn subcommand_none_given() { fn subcommand_multiple() { let m = App::new("test") .subcommands(vec![ - SubCommand::with_name("some") - .arg(Arg::with_name("test") + SubCommand::with_name("some").arg( + Arg::with_name("test") .short("t") .long("test") .takes_value(true) - .help("testing testing")), - SubCommand::with_name("add") - .arg(Arg::with_name("roster").short("r")) + .help("testing testing"), + ), + SubCommand::with_name("add").arg(Arg::with_name("roster").short("r")), ]) .arg(Arg::with_name("other").long("other")) .get_matches_from(vec!["myprog", "some", "--test", "testing"]); @@ -102,33 +108,31 @@ fn subcommand_multiple() { #[test] fn single_alias() { let m = App::new("myprog") - .subcommand(SubCommand::with_name("test") - .alias("do-stuff")) - .get_matches_from(vec!["myprog", "do-stuff"]); + .subcommand(SubCommand::with_name("test").alias("do-stuff")) + .get_matches_from(vec!["myprog", "do-stuff"]); assert_eq!(m.subcommand_name(), Some("test")); } #[test] fn multiple_aliases() { let m = App::new("myprog") - .subcommand(SubCommand::with_name("test") - .aliases(&["do-stuff", "test-stuff"])) - .get_matches_from(vec!["myprog", "test-stuff"]); + .subcommand(SubCommand::with_name("test").aliases(&["do-stuff", "test-stuff"])) + .get_matches_from(vec!["myprog", "test-stuff"]); assert_eq!(m.subcommand_name(), Some("test")); } #[test] -#[cfg(feature="suggestions")] +#[cfg(feature = "suggestions")] fn subcmd_did_you_mean_output() { - let app = App::new("dym") - .subcommand(SubCommand::with_name("subcmd")); + let app = App::new("dym").subcommand(SubCommand::with_name("subcmd")); assert!(test::compare_output(app, "dym subcm", DYM_SUBCMD, true)); } #[test] -#[cfg(feature="suggestions")] +#[cfg(feature = "suggestions")] fn subcmd_did_you_mean_output_arg() { - static EXPECTED: &'static str = "error: Found argument '--subcmarg' which wasn't expected, or isn't valid in this context + static EXPECTED: &'static str = + "error: Found argument '--subcmarg' which wasn't expected, or isn't valid in this context \tDid you mean to put '--subcmdarg' after the subcommand 'subcmd'? USAGE: @@ -136,58 +140,78 @@ USAGE: For more information try --help"; - let app = App::new("dym") - .subcommand(SubCommand::with_name("subcmd") - .arg_from_usage("-s --subcmdarg [subcmdarg] 'tests'") ); - assert!(test::compare_output(app, "dym --subcmarg subcmd", EXPECTED, true)); + let app = App::new("dym").subcommand( + SubCommand::with_name("subcmd").arg_from_usage("-s --subcmdarg [subcmdarg] 'tests'"), + ); + assert!(test::compare_output( + app, + "dym --subcmarg subcmd", + EXPECTED, + true + )); } #[test] -#[cfg(feature="suggestions")] +#[cfg(feature = "suggestions")] fn subcmd_did_you_mean_output_arg_false_positives() { - static EXPECTED: &'static str = "error: Found argument '--subcmarg' which wasn't expected, or isn't valid in this context + static EXPECTED: &'static str = + "error: Found argument '--subcmarg' which wasn't expected, or isn't valid in this context USAGE: dym [SUBCOMMAND] For more information try --help"; - let app = App::new("dym") - .subcommand(SubCommand::with_name("subcmd") - .arg_from_usage("-s --subcmdarg [subcmdarg] 'tests'") ); - assert!(test::compare_output(app, "dym --subcmarg foo", EXPECTED, true)); + let app = App::new("dym").subcommand( + SubCommand::with_name("subcmd").arg_from_usage("-s --subcmdarg [subcmdarg] 'tests'"), + ); + assert!(test::compare_output( + app, + "dym --subcmarg foo", + EXPECTED, + true + )); } #[test] fn alias_help() { let m = App::new("myprog") - .subcommand(SubCommand::with_name("test") - .alias("do-stuff")) - .get_matches_from_safe(vec!["myprog", "help", "do-stuff"]); + .subcommand(SubCommand::with_name("test").alias("do-stuff")) + .get_matches_from_safe(vec!["myprog", "help", "do-stuff"]); assert!(m.is_err()); assert_eq!(m.unwrap_err().kind, ErrorKind::HelpDisplayed); } #[test] fn visible_aliases_help_output() { - let app = App::new("clap-test") - .version("2.6") - .subcommand(SubCommand::with_name("test") + let app = App::new("clap-test").version("2.6").subcommand( + SubCommand::with_name("test") .about("Some help") .alias("invisible") .visible_alias("dongle") - .visible_alias("done")); - assert!(test::compare_output(app, "clap-test --help", VISIBLE_ALIAS_HELP, false)); + .visible_alias("done"), + ); + assert!(test::compare_output( + app, + "clap-test --help", + VISIBLE_ALIAS_HELP, + false + )); } #[test] fn invisible_aliases_help_output() { - let app = App::new("clap-test") - .version("2.6") - .subcommand(SubCommand::with_name("test") + let app = App::new("clap-test").version("2.6").subcommand( + SubCommand::with_name("test") .about("Some help") - .alias("invisible")); - assert!(test::compare_output(app, "clap-test --help", INVISIBLE_ALIAS_HELP, false)); + .alias("invisible"), + ); + assert!(test::compare_output( + app, + "clap-test --help", + INVISIBLE_ALIAS_HELP, + false + )); } #[test] diff --git a/tests/template_help.rs b/tests/template_help.rs index b1a546a91ef..adcf495d597 100644 --- a/tests/template_help.rs +++ b/tests/template_help.rs @@ -5,8 +5,8 @@ use clap::{App, SubCommand}; include!("../clap-test.rs"); -static EXAMPLE1_TMPL_S : &'static str = include_str!("example1_tmpl_simple.txt"); -static EXAMPLE1_TMPS_F : &'static str = include_str!("example1_tmpl_full.txt"); +static EXAMPLE1_TMPL_S: &'static str = include_str!("example1_tmpl_simple.txt"); +static EXAMPLE1_TMPS_F: &'static str = include_str!("example1_tmpl_full.txt"); static CUSTOM_TEMPL_HELP: &'static str = "MyApp 1.0 Kevin K. @@ -52,53 +52,78 @@ SUBCOMMANDS: #[test] fn with_template() { let app = app_example1().template(EXAMPLE1_TMPL_S); - assert!(test::compare_output(app, "MyApp --help", SIMPLE_TEMPLATE, false)); + assert!(test::compare_output( + app, + "MyApp --help", + SIMPLE_TEMPLATE, + false + )); } #[test] fn custom_template() { let app = app_example1().template(EXAMPLE1_TMPS_F); - assert!(test::compare_output(app, "MyApp --help", CUSTOM_TEMPL_HELP, false)); + assert!(test::compare_output( + app, + "MyApp --help", + CUSTOM_TEMPL_HELP, + false + )); } #[test] fn template_empty() { let app = App::new("MyApp") - .version("1.0") - .author("Kevin K. ") - .about("Does awesome things") - .template(""); + .version("1.0") + .author("Kevin K. ") + .about("Does awesome things") + .template(""); assert!(test::compare_output(app, "MyApp --help", "", false)); } #[test] fn template_notag() { let app = App::new("MyApp") - .version("1.0") - .author("Kevin K. ") - .about("Does awesome things") - .template("test no tag test"); - assert!(test::compare_output(app, "MyApp --help", "test no tag test", false)); + .version("1.0") + .author("Kevin K. ") + .about("Does awesome things") + .template("test no tag test"); + assert!(test::compare_output( + app, + "MyApp --help", + "test no tag test", + false + )); } #[test] fn template_unknowntag() { let app = App::new("MyApp") - .version("1.0") - .author("Kevin K. ") - .about("Does awesome things") - .template("test {unknown_tag} test"); - assert!(test::compare_output(app, "MyApp --help", "test {unknown_tag} test", false)); + .version("1.0") + .author("Kevin K. ") + .about("Does awesome things") + .template("test {unknown_tag} test"); + assert!(test::compare_output( + app, + "MyApp --help", + "test {unknown_tag} test", + false + )); } #[test] fn template_author_version() { let app = App::new("MyApp") - .version("1.0") - .author("Kevin K. ") - .about("Does awesome things") - .template("{author}\n{version}\n{about}\n{bin}"); - assert!(test::compare_output(app, "MyApp --help", "Kevin K. \n1.0\nDoes awesome things\nMyApp", false)); + .version("1.0") + .author("Kevin K. ") + .about("Does awesome things") + .template("{author}\n{version}\n{about}\n{bin}"); + assert!(test::compare_output( + app, + "MyApp --help", + "Kevin K. \n1.0\nDoes awesome things\nMyApp", + false + )); } // ---------- @@ -108,10 +133,14 @@ fn app_example1<'b, 'c>() -> App<'b, 'c> { .version("1.0") .author("Kevin K. ") .about("Does awesome things") - .args_from_usage("-c, --config=[FILE] 'Sets a custom config file' + .args_from_usage( + "-c, --config=[FILE] 'Sets a custom config file' 'Sets an optional output file' - -d... 'Turn debugging information on'") - .subcommand(SubCommand::with_name("test") - .about("does testing things") - .arg_from_usage("-l, --list 'lists test values'")) + -d... 'Turn debugging information on'", + ) + .subcommand( + SubCommand::with_name("test") + .about("does testing things") + .arg_from_usage("-l, --list 'lists test values'"), + ) } diff --git a/tests/tests.rs b/tests/tests.rs index 0ad825a5547..0059998a321 100644 --- a/tests/tests.rs +++ b/tests/tests.rs @@ -101,7 +101,13 @@ pub fn check_complex_output(args: &str, out: &str) { if matches.is_present("option") { if let Some(v) = matches.value_of("option") { - writeln!(w, "option present {} times with value: {}",matches.occurrences_of("option"), v).unwrap(); + writeln!( + w, + "option present {} times with value: {}", + matches.occurrences_of("option"), + v + ) + .unwrap(); } if let Some(ov) = matches.values_of("option") { for o in ov { @@ -120,29 +126,55 @@ pub fn check_complex_output(args: &str, out: &str) { if matches.is_present("flag2") { writeln!(w, "flag2 present").unwrap(); - writeln!(w, "option2 present with value of: {}", matches.value_of("long-option-2").unwrap()).unwrap(); - writeln!(w, "positional2 present with value of: {}", matches.value_of("positional2").unwrap()).unwrap(); + writeln!( + w, + "option2 present with value of: {}", + matches.value_of("long-option-2").unwrap() + ) + .unwrap(); + writeln!( + w, + "positional2 present with value of: {}", + matches.value_of("positional2").unwrap() + ) + .unwrap(); } else { writeln!(w, "flag2 NOT present").unwrap(); - writeln!(w, "option2 maybe present with value of: {}", matches.value_of("long-option-2").unwrap_or("Nothing")).unwrap(); - writeln!(w, "positional2 maybe present with value of: {}", matches.value_of("positional2").unwrap_or("Nothing")).unwrap(); + writeln!( + w, + "option2 maybe present with value of: {}", + matches.value_of("long-option-2").unwrap_or("Nothing") + ) + .unwrap(); + writeln!( + w, + "positional2 maybe present with value of: {}", + matches.value_of("positional2").unwrap_or("Nothing") + ) + .unwrap(); } let _ = match matches.value_of("Option3").unwrap_or("") { "fast" => writeln!(w, "option3 present quickly"), "slow" => writeln!(w, "option3 present slowly"), - _ => writeln!(w, "option3 NOT present") + _ => writeln!(w, "option3 NOT present"), }; let _ = match matches.value_of("positional3").unwrap_or("") { "vi" => writeln!(w, "positional3 present in vi mode"), "emacs" => writeln!(w, "positional3 present in emacs mode"), - _ => writeln!(w, "positional3 NOT present") + _ => writeln!(w, "positional3 NOT present"), }; if matches.is_present("option") { if let Some(v) = matches.value_of("option") { - writeln!(w, "option present {} times with value: {}",matches.occurrences_of("option"), v).unwrap(); + writeln!( + w, + "option present {} times with value: {}", + matches.occurrences_of("option"), + v + ) + .unwrap(); } if let Some(ov) = matches.values_of("option") { for o in ov { @@ -192,27 +224,27 @@ pub fn check_complex_output(args: &str, out: &str) { assert_eq!(res, out); } -arg_enum!{ +arg_enum! { #[derive(Debug)] enum Val1 { ValOne, ValTwo } } -arg_enum!{ +arg_enum! { #[derive(Debug)] pub enum Val2 { ValOne, ValTwo } } -arg_enum!{ +arg_enum! { enum Val3 { ValOne, ValTwo } } -arg_enum!{ +arg_enum! { pub enum Val4 { ValOne, ValTwo @@ -268,22 +300,27 @@ fn test_enums() { #[test] fn create_app() { - let _ = - App::new("test").version("1.0").author("kevin").about("does awesome things").get_matches_from(vec![""]); + let _ = App::new("test") + .version("1.0") + .author("kevin") + .about("does awesome things") + .get_matches_from(vec![""]); } #[test] fn add_multiple_arg() { let _ = App::new("test") - .args(&[ - Arg::with_name("test").short("s"), - Arg::with_name("test2").short("l")]) - .get_matches_from(vec![""]); + .args(&[ + Arg::with_name("test").short("s"), + Arg::with_name("test2").short("l"), + ]) + .get_matches_from(vec![""]); } #[test] fn flag_x2_opt() { - check_complex_output("clap-test value -f -f -o some", -"flag present 2 times + check_complex_output( + "clap-test value -f -f -o some", + "flag present 2 times option present 1 times with value: some An option: some positional present with value: value @@ -296,7 +333,8 @@ option present 1 times with value: some An option: some positional present with value: value subcmd NOT present -"); +", + ); } #[test] diff --git a/tests/unique_args.rs b/tests/unique_args.rs index 871024872c3..e80aec1a772 100644 --- a/tests/unique_args.rs +++ b/tests/unique_args.rs @@ -5,18 +5,26 @@ use clap::{App, Arg}; #[test] #[should_panic] fn unique_arg_names() { - App::new("some").args(&[Arg::with_name("arg").short("a"), Arg::with_name("arg").short("b")]); + App::new("some").args(&[ + Arg::with_name("arg").short("a"), + Arg::with_name("arg").short("b"), + ]); } #[test] #[should_panic] fn unique_arg_shorts() { - App::new("some").args(&[Arg::with_name("arg1").short("a"), Arg::with_name("arg2").short("a")]); + App::new("some").args(&[ + Arg::with_name("arg1").short("a"), + Arg::with_name("arg2").short("a"), + ]); } #[test] #[should_panic] fn unique_arg_longs() { - App::new("some") - .args(&[Arg::with_name("arg1").long("long"), Arg::with_name("arg2").long("long")]); + App::new("some").args(&[ + Arg::with_name("arg1").long("long"), + Arg::with_name("arg2").long("long"), + ]); } diff --git a/tests/utf8.rs b/tests/utf8.rs index dfa382e9f0b..f5467d09369 100644 --- a/tests/utf8.rs +++ b/tests/utf8.rs @@ -2,17 +2,16 @@ extern crate clap; +use clap::{App, AppSettings, Arg, ErrorKind}; use std::ffi::OsString; use std::os::unix::ffi::OsStringExt; -use clap::{App, Arg, AppSettings, ErrorKind}; #[test] fn invalid_utf8_strict_positional() { let m = App::new("bad_utf8") .arg(Arg::from_usage(" 'some arg'")) .setting(AppSettings::StrictUtf8) - .get_matches_from_safe(vec![OsString::from(""), - OsString::from_vec(vec![0xe9])]); + .get_matches_from_safe(vec![OsString::from(""), OsString::from_vec(vec![0xe9])]); assert!(m.is_err()); assert_eq!(m.unwrap_err().kind, ErrorKind::InvalidUtf8); } @@ -22,9 +21,11 @@ fn invalid_utf8_strict_option_short_space() { let m = App::new("bad_utf8") .arg(Arg::from_usage("-a, --arg 'some arg'")) .setting(AppSettings::StrictUtf8) - .get_matches_from_safe(vec![OsString::from(""), - OsString::from("-a"), - OsString::from_vec(vec![0xe9])]); + .get_matches_from_safe(vec![ + OsString::from(""), + OsString::from("-a"), + OsString::from_vec(vec![0xe9]), + ]); assert!(m.is_err()); assert_eq!(m.unwrap_err().kind, ErrorKind::InvalidUtf8); } @@ -34,8 +35,10 @@ fn invalid_utf8_strict_option_short_equals() { let m = App::new("bad_utf8") .arg(Arg::from_usage("-a, --arg 'some arg'")) .setting(AppSettings::StrictUtf8) - .get_matches_from_safe(vec![OsString::from(""), - OsString::from_vec(vec![0x2d, 0x61, 0x3d, 0xe9])]); + .get_matches_from_safe(vec![ + OsString::from(""), + OsString::from_vec(vec![0x2d, 0x61, 0x3d, 0xe9]), + ]); assert!(m.is_err()); assert_eq!(m.unwrap_err().kind, ErrorKind::InvalidUtf8); } @@ -45,8 +48,10 @@ fn invalid_utf8_strict_option_short_no_space() { let m = App::new("bad_utf8") .arg(Arg::from_usage("-a, --arg 'some arg'")) .setting(AppSettings::StrictUtf8) - .get_matches_from_safe(vec![OsString::from(""), - OsString::from_vec(vec![0x2d, 0x61, 0xe9])]); + .get_matches_from_safe(vec![ + OsString::from(""), + OsString::from_vec(vec![0x2d, 0x61, 0xe9]), + ]); assert!(m.is_err()); assert_eq!(m.unwrap_err().kind, ErrorKind::InvalidUtf8); } @@ -56,9 +61,11 @@ fn invalid_utf8_strict_option_long_space() { let m = App::new("bad_utf8") .arg(Arg::from_usage("-a, --arg 'some arg'")) .setting(AppSettings::StrictUtf8) - .get_matches_from_safe(vec![OsString::from(""), - OsString::from("--arg"), - OsString::from_vec(vec![0xe9])]); + .get_matches_from_safe(vec![ + OsString::from(""), + OsString::from("--arg"), + OsString::from_vec(vec![0xe9]), + ]); assert!(m.is_err()); assert_eq!(m.unwrap_err().kind, ErrorKind::InvalidUtf8); } @@ -68,8 +75,10 @@ fn invalid_utf8_strict_option_long_equals() { let m = App::new("bad_utf8") .arg(Arg::from_usage("-a, --arg 'some arg'")) .setting(AppSettings::StrictUtf8) - .get_matches_from_safe(vec![OsString::from(""), - OsString::from_vec(vec![0x2d, 0x2d, 0x61, 0x72, 0x67, 0x3d, 0xe9])]); + .get_matches_from_safe(vec![ + OsString::from(""), + OsString::from_vec(vec![0x2d, 0x2d, 0x61, 0x72, 0x67, 0x3d, 0xe9]), + ]); assert!(m.is_err()); assert_eq!(m.unwrap_err().kind, ErrorKind::InvalidUtf8); } @@ -78,8 +87,7 @@ fn invalid_utf8_strict_option_long_equals() { fn invalid_utf8_lossy_positional() { let r = App::new("bad_utf8") .arg(Arg::from_usage(" 'some arg'")) - .get_matches_from_safe(vec![OsString::from(""), - OsString::from_vec(vec![0xe9])]); + .get_matches_from_safe(vec![OsString::from(""), OsString::from_vec(vec![0xe9])]); assert!(r.is_ok()); let m = r.unwrap(); assert!(m.is_present("arg")); @@ -90,9 +98,11 @@ fn invalid_utf8_lossy_positional() { fn invalid_utf8_lossy_option_short_space() { let r = App::new("bad_utf8") .arg(Arg::from_usage("-a, --arg 'some arg'")) - .get_matches_from_safe(vec![OsString::from(""), - OsString::from("-a"), - OsString::from_vec(vec![0xe9])]); + .get_matches_from_safe(vec![ + OsString::from(""), + OsString::from("-a"), + OsString::from_vec(vec![0xe9]), + ]); assert!(r.is_ok()); let m = r.unwrap(); assert!(m.is_present("arg")); @@ -103,8 +113,10 @@ fn invalid_utf8_lossy_option_short_space() { fn invalid_utf8_lossy_option_short_equals() { let r = App::new("bad_utf8") .arg(Arg::from_usage("-a, --arg 'some arg'")) - .get_matches_from_safe(vec![OsString::from(""), - OsString::from_vec(vec![0x2d, 0x61, 0x3d, 0xe9])]); + .get_matches_from_safe(vec![ + OsString::from(""), + OsString::from_vec(vec![0x2d, 0x61, 0x3d, 0xe9]), + ]); assert!(r.is_ok()); let m = r.unwrap(); assert!(m.is_present("arg")); @@ -115,8 +127,10 @@ fn invalid_utf8_lossy_option_short_equals() { fn invalid_utf8_lossy_option_short_no_space() { let r = App::new("bad_utf8") .arg(Arg::from_usage("-a, --arg 'some arg'")) - .get_matches_from_safe(vec![OsString::from(""), - OsString::from_vec(vec![0x2d, 0x61, 0xe9])]); + .get_matches_from_safe(vec![ + OsString::from(""), + OsString::from_vec(vec![0x2d, 0x61, 0xe9]), + ]); assert!(r.is_ok()); let m = r.unwrap(); assert!(m.is_present("arg")); @@ -127,9 +141,11 @@ fn invalid_utf8_lossy_option_short_no_space() { fn invalid_utf8_lossy_option_long_space() { let r = App::new("bad_utf8") .arg(Arg::from_usage("-a, --arg 'some arg'")) - .get_matches_from_safe(vec![OsString::from(""), - OsString::from("--arg"), - OsString::from_vec(vec![0xe9])]); + .get_matches_from_safe(vec![ + OsString::from(""), + OsString::from("--arg"), + OsString::from_vec(vec![0xe9]), + ]); assert!(r.is_ok()); let m = r.unwrap(); assert!(m.is_present("arg")); @@ -140,8 +156,10 @@ fn invalid_utf8_lossy_option_long_space() { fn invalid_utf8_lossy_option_long_equals() { let r = App::new("bad_utf8") .arg(Arg::from_usage("-a, --arg 'some arg'")) - .get_matches_from_safe(vec![OsString::from(""), - OsString::from_vec(vec![0x2d, 0x2d, 0x61, 0x72, 0x67, 0x3d, 0xe9])]); + .get_matches_from_safe(vec![ + OsString::from(""), + OsString::from_vec(vec![0x2d, 0x2d, 0x61, 0x72, 0x67, 0x3d, 0xe9]), + ]); assert!(r.is_ok()); let m = r.unwrap(); assert!(m.is_present("arg")); @@ -152,72 +170,99 @@ fn invalid_utf8_lossy_option_long_equals() { fn invalid_utf8_positional() { let r = App::new("bad_utf8") .arg(Arg::from_usage(" 'some arg'")) - .get_matches_from_safe(vec![OsString::from(""), - OsString::from_vec(vec![0xe9])]); + .get_matches_from_safe(vec![OsString::from(""), OsString::from_vec(vec![0xe9])]); assert!(r.is_ok()); let m = r.unwrap(); assert!(m.is_present("arg")); - assert_eq!(&*m.value_of_os("arg").unwrap(), &*OsString::from_vec(vec![0xe9])); + assert_eq!( + &*m.value_of_os("arg").unwrap(), + &*OsString::from_vec(vec![0xe9]) + ); } #[test] fn invalid_utf8_option_short_space() { let r = App::new("bad_utf8") .arg(Arg::from_usage("-a, --arg 'some arg'")) - .get_matches_from_safe(vec![OsString::from(""), - OsString::from("-a"), - OsString::from_vec(vec![0xe9])]); + .get_matches_from_safe(vec![ + OsString::from(""), + OsString::from("-a"), + OsString::from_vec(vec![0xe9]), + ]); assert!(r.is_ok()); let m = r.unwrap(); assert!(m.is_present("arg")); - assert_eq!(&*m.value_of_os("arg").unwrap(), &*OsString::from_vec(vec![0xe9])); + assert_eq!( + &*m.value_of_os("arg").unwrap(), + &*OsString::from_vec(vec![0xe9]) + ); } #[test] fn invalid_utf8_option_short_equals() { let r = App::new("bad_utf8") .arg(Arg::from_usage("-a, --arg 'some arg'")) - .get_matches_from_safe(vec![OsString::from(""), - OsString::from_vec(vec![0x2d, 0x61, 0x3d, 0xe9])]); + .get_matches_from_safe(vec![ + OsString::from(""), + OsString::from_vec(vec![0x2d, 0x61, 0x3d, 0xe9]), + ]); assert!(r.is_ok()); let m = r.unwrap(); assert!(m.is_present("arg")); - assert_eq!(&*m.value_of_os("arg").unwrap(), &*OsString::from_vec(vec![0xe9])); + assert_eq!( + &*m.value_of_os("arg").unwrap(), + &*OsString::from_vec(vec![0xe9]) + ); } #[test] fn invalid_utf8_option_short_no_space() { let r = App::new("bad_utf8") .arg(Arg::from_usage("-a, --arg 'some arg'")) - .get_matches_from_safe(vec![OsString::from(""), - OsString::from_vec(vec![0x2d, 0x61, 0xe9])]); + .get_matches_from_safe(vec![ + OsString::from(""), + OsString::from_vec(vec![0x2d, 0x61, 0xe9]), + ]); assert!(r.is_ok()); let m = r.unwrap(); assert!(m.is_present("arg")); - assert_eq!(&*m.value_of_os("arg").unwrap(), &*OsString::from_vec(vec![0xe9])); + assert_eq!( + &*m.value_of_os("arg").unwrap(), + &*OsString::from_vec(vec![0xe9]) + ); } #[test] fn invalid_utf8_option_long_space() { let r = App::new("bad_utf8") .arg(Arg::from_usage("-a, --arg 'some arg'")) - .get_matches_from_safe(vec![OsString::from(""), - OsString::from("--arg"), - OsString::from_vec(vec![0xe9])]); + .get_matches_from_safe(vec![ + OsString::from(""), + OsString::from("--arg"), + OsString::from_vec(vec![0xe9]), + ]); assert!(r.is_ok()); let m = r.unwrap(); assert!(m.is_present("arg")); - assert_eq!(&*m.value_of_os("arg").unwrap(), &*OsString::from_vec(vec![0xe9])); + assert_eq!( + &*m.value_of_os("arg").unwrap(), + &*OsString::from_vec(vec![0xe9]) + ); } #[test] fn invalid_utf8_option_long_equals() { let r = App::new("bad_utf8") .arg(Arg::from_usage("-a, --arg 'some arg'")) - .get_matches_from_safe(vec![OsString::from(""), - OsString::from_vec(vec![0x2d, 0x2d, 0x61, 0x72, 0x67, 0x3d, 0xe9])]); + .get_matches_from_safe(vec![ + OsString::from(""), + OsString::from_vec(vec![0x2d, 0x2d, 0x61, 0x72, 0x67, 0x3d, 0xe9]), + ]); assert!(r.is_ok()); let m = r.unwrap(); assert!(m.is_present("arg")); - assert_eq!(&*m.value_of_os("arg").unwrap(), &*OsString::from_vec(vec![0xe9])); + assert_eq!( + &*m.value_of_os("arg").unwrap(), + &*OsString::from_vec(vec![0xe9]) + ); } diff --git a/tests/version.rs b/tests/version.rs index 8bbd47454ac..931d3639a6e 100644 --- a/tests/version.rs +++ b/tests/version.rs @@ -38,10 +38,10 @@ fn complex_version_output() { let mut a = App::new("clap-test").version("v1.4.8"); let _ = a.get_matches_from_safe_borrow(vec![""]); - // Now we check the output of print_version() - let mut ver = vec![]; - a.write_version(&mut ver).unwrap(); - assert_eq!(str::from_utf8(&ver).unwrap(), VERSION); + // Now we check the output of print_version() + let mut ver = vec![]; + a.write_version(&mut ver).unwrap(); + assert_eq!(str::from_utf8(&ver).unwrap(), VERSION); } #[test] diff --git a/tests/yaml.rs b/tests/yaml.rs index 279b9876493..fcd035141a4 100644 --- a/tests/yaml.rs +++ b/tests/yaml.rs @@ -1,4 +1,4 @@ -#![cfg(feature="yaml")] +#![cfg(feature = "yaml")] #[macro_use] extern crate clap; @@ -21,8 +21,9 @@ fn help_message() { let mut help_buffer = Vec::new(); app.write_help(&mut help_buffer).unwrap(); let help_string = String::from_utf8(help_buffer).unwrap(); - assert!(help_string.contains( - "-h, --help prints help with a nonstandard description\n")); + assert!( + help_string.contains("-h, --help prints help with a nonstandard description\n") + ); } #[test] @@ -35,6 +36,5 @@ fn author() { let mut help_buffer = Vec::new(); app.write_help(&mut help_buffer).unwrap(); let help_string = String::from_utf8(help_buffer).unwrap(); - assert!(help_string.contains( - "Kevin K. ")); + assert!(help_string.contains("Kevin K. ")); }