Merge "Upgrade rust/crates/clap to 2.33.3" am: 465a48ac99 am: 645aa5106c am: d9963fb433 am: 9c12039932
Original change: https://android-review.googlesource.com/c/platform/external/rust/crates/clap/+/1474961
Change-Id: I425f362be894a7e58e3018bd8e1c8c2f5369cf07
diff --git a/.appveyor.yml b/.appveyor.yml
deleted file mode 100644
index 247a550..0000000
--- 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 0000000..464b792
--- /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/.cargo_vcs_info.json b/.cargo_vcs_info.json
index 69d9675..ff4eb04 100644
--- a/.cargo_vcs_info.json
+++ b/.cargo_vcs_info.json
@@ -1,5 +1,5 @@
{
"git": {
- "sha1": "784524f7eb193e35f81082cc69454c8c21b948f7"
+ "sha1": "33bebeda52b52c6f643b4ed6fa880671ba0ab80a"
}
}
diff --git a/.mention-bot b/.mention-bot
deleted file mode 100644
index f339f59..0000000
--- 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 9eb4044..f3cf7b7 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,59 +1,66 @@
-sudo: true
+os: linux
language: rust
cache: cargo
-rust:
- - nightly
- - beta
- - stable
- - 1.31.0
-matrix:
- allow_failures:
- - rust: nightly
-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
+before_cache:
+ - 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 d1fdd40..a2400b5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,3 +1,38 @@
+<a name="v2.33.3"></a>
+### v2.33.3 (2020-08-13)
+
+#### Improvements
+
+* Suppress deprecation warnings when using `crate_*` macros.
+
+<a name="v2.33.2"></a>
+### v2.33.2 (2020-08-5)
+
+#### Documentation
+
+* Fixed links to `2.x` examples. Now they point to the right place.
+
+<a name="v2.33.1"></a>
+### v2.33.1 (2020-05-11)
+
+#### Bug Fixes
+
+* Windows: Prevent some panics when parsing invalid Unicode on Windows ([922c645](https://github.com/clap-rs/clap/commit/922c64508389170c9c77f1c8a4e597d14d3ed2f0), closes [#1905](https://github.com/clap-rs/clap/issues/1905))
+
+#### Documentation
+
+* fixes versions referenced in the README ([d307466a](https://github.com/kbknapp/clap-rs/commit/d307466af1013f172b8ec0252f01a473e2192d6b))
+* **README.md:**
+ * cuts down the number of examples to reduce confusion ([6e508ee0](https://github.com/kbknapp/clap-rs/commit/6e508ee09e7153de4adf4e88b0aa6418a537dadd))
+
+#### Improvements
+
+* **Deps:** doesnt compile ansi_term on Windows since its not used ([b57ee946](https://github.com/kbknapp/clap-rs/commit/b57ee94609da3ddc897286cfba968f26ff961491), closes [#1155](https://github.com/kbknapp/clap-rs/issues/1155))
+
+#### Minimum Required Rust
+
+* As of this release, `clap` requires `rustc 1.36.0` or greater.
+
<a name="v2.33.0"></a>
## v2.33.0 (2019-04-06)
diff --git a/Cargo.toml b/Cargo.toml
index c76ceb4..683a040 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -3,7 +3,7 @@
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
-# to registry (e.g. crates.io) dependencies
+# to registry (e.g., crates.io) dependencies
#
# If you believe there's an error in this file please file an
# issue against the rust-lang/cargo repository. If you're
@@ -12,7 +12,7 @@
[package]
name = "clap"
-version = "2.33.0"
+version = "2.33.3"
authors = ["Kevin K. <[email protected]>"]
exclude = ["examples/*", "clap-test/*", "tests/*", "benches/*", "*.png", "clap-perf/*", "*.dot"]
description = "A simple to use, efficient, and full-featured Command Line Argument Parser\n"
@@ -25,14 +25,6 @@
repository = "https://github.com/clap-rs/clap"
[package.metadata.docs.rs]
features = ["doc"]
-[profile.test]
-opt-level = 1
-lto = false
-codegen-units = 4
-debug = true
-debug-assertions = true
-rpath = false
-
[profile.bench]
opt-level = 3
lto = true
@@ -56,6 +48,14 @@
debug = false
debug-assertions = false
rpath = false
+
+[profile.test]
+opt-level = 1
+lto = false
+codegen-units = 4
+debug = true
+debug-assertions = true
+rpath = false
[dependencies.atty]
version = "0.2.2"
optional = true
diff --git a/METADATA b/METADATA
index 61b8bde..ba73a38 100644
--- a/METADATA
+++ b/METADATA
@@ -7,13 +7,13 @@
}
url {
type: ARCHIVE
- value: "https://static.crates.io/crates/clap/clap-2.33.0.crate"
+ value: "https://static.crates.io/crates/clap/clap-2.33.3.crate"
}
- version: "2.33.0"
+ version: "2.33.3"
license_type: NOTICE
last_upgrade_date {
year: 2020
- month: 5
- day: 6
+ month: 11
+ day: 3
}
}
diff --git a/README.md b/README.md
index c95f494..e3a9142 100644
--- a/README.md
+++ b/README.md
@@ -455,9 +455,9 @@
#### 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.32.0, meaning `clap` is guaranteed to compile with 1.30.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.33.0 stable release, `clap` will be guaranteed to compile with 1.31.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/rustfmt.toml b/rustfmt.toml
deleted file mode 100644
index 0136d86..0000000
--- 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 34f97ac..4751fe7 100644
--- a/src/app/help.rs
+++ b/src/app/help.rs
@@ -37,11 +37,7 @@
// 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 @@
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 @@
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 @@
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 @@
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 @@
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 c7f128f..8916101 100644
--- a/src/app/meta.rs
+++ b/src/app/meta.rs
@@ -22,7 +22,9 @@
}
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 3a1a383..3fff846 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 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 @@
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 @@
}
/// 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 @@
/// [`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<S: Into<String>>(n: S) -> Self {
let mut a = App {
p: Parser::with_name(n.into()),
@@ -149,11 +156,13 @@
/// # }
/// ```
/// [`App`]: ./struct.App.html
- /// [`examples/17_yaml.rs`]: https://github.com/clap-rs/clap/blob/master/examples/17_yaml.rs
- /// [`examples/17_yaml.yml`]: https://github.com/clap-rs/clap/blob/master/examples/17_yaml.yml
+ /// [`examples/17_yaml.rs`]: https://github.com/clap-rs/clap/blob/v2.33.1/examples/17_yaml.rs
+ /// [`examples/17_yaml.yml`]: https://github.com/clap-rs/clap/blob/v2.33.1/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`.
@@ -174,7 +183,7 @@
/// # ;
/// ```
/// [`crate_authors!`]: ./macro.crate_authors!.html
- /// [`examples/`]: https://github.com/clap-rs/clap/tree/master/examples
+ /// [`examples/`]: https://github.com/clap-rs/clap/tree/v2.33.1/examples
pub fn author<S: Into<&'b str>>(mut self, author: S) -> Self {
self.p.meta.author = Some(author.into());
self
@@ -332,7 +341,7 @@
/// # ;
/// ```
/// [`crate_version!`]: ./macro.crate_version!.html
- /// [`examples/`]: https://github.com/clap-rs/clap/tree/master/examples
+ /// [`examples/`]: https://github.com/clap-rs/clap/tree/v2.33.1/examples
/// [`App::long_version`]: ./struct.App.html#method.long_version
pub fn version<S: Into<&'b str>>(mut self, ver: S) -> Self {
self.p.meta.version = Some(ver.into());
@@ -363,7 +372,7 @@
/// # ;
/// ```
/// [`crate_version!`]: ./macro.crate_version!.html
- /// [`examples/`]: https://github.com/clap-rs/clap/tree/master/examples
+ /// [`examples/`]: https://github.com/clap-rs/clap/tree/v2.33.1/examples
/// [`App::version`]: ./struct.App.html#method.version
pub fn long_version<S: Into<&'b str>>(mut self, ver: S) -> Self {
self.p.meta.long_version = Some(ver.into());
@@ -1391,7 +1400,6 @@
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 @@
/// .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 @@
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 @@
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, '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<u64> { None }
- fn num_vals(&self) -> Option<u64> { None }
- fn possible_vals(&self) -> Option<&[&'e str]> { None }
- fn validator(&self) -> Option<&Rc<Fn(String) -> StdResult<(), String>>> { None }
- fn validator_os(&self) -> Option<&Rc<Fn(&OsStr) -> StdResult<(), OsString>>> { None }
- fn min_vals(&self) -> Option<u64> { None }
- fn short(&self) -> Option<char> { None }
- fn long(&self) -> Option<&'e str> { None }
- fn val_delim(&self) -> Option<char> { 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<u64> {
+ None
+ }
+ fn num_vals(&self) -> Option<u64> {
+ None
+ }
+ fn possible_vals(&self) -> Option<&[&'e str]> {
+ None
+ }
+ fn validator(&self) -> Option<&Rc<Fn(String) -> StdResult<(), String>>> {
+ None
+ }
+ fn validator_os(&self) -> Option<&Rc<Fn(&OsStr) -> StdResult<(), OsString>>> {
+ None
+ }
+ fn min_vals(&self) -> Option<u64> {
+ None
+ }
+ fn short(&self) -> Option<char> {
+ None
+ }
+ fn long(&self) -> Option<&'e str> {
+ None
+ }
+ fn val_delim(&self) -> Option<char> {
+ 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<map::Values<(&'n str, Option<&'e OsStr>, &'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<Vec<&'e str>> {
if let Some(ref aliases) = self.p.meta.aliases {
let vis_aliases: Vec<_> = aliases
@@ -1835,5 +1898,7 @@
}
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 decfde4..c05602e 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 args::settings::ArgSettings;
-use completions::ComplGen;
-use errors::{Error, ErrorKind};
-use errors::Result as ClapResult;
-use fmt::ColorWhen;
-use osstringext::OsStrExt2;
-use completions::Shell;
-use suggestions;
use app::settings::AppSettings as AS;
-use app::validator::Validator;
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 completions::Shell;
+use errors::Result as ClapResult;
+use errors::{Error, ErrorKind};
+use fmt::ColorWhen;
use map::{self, VecMap};
+use osstringext::OsStrExt2;
+use suggestions;
+use SubCommand;
+use INTERNAL_ERROR_MSG;
+use INVALID_UTF8;
#[derive(Debug, PartialEq, Copy, Clone)]
#[doc(hidden)]
@@ -87,7 +92,8 @@
}
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 @@
}
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 @@
);
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 @@
// }
}
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 @@
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 @@
}
}
- 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 @@
}
#[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 @@
#[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 @@
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 @@
}
}
}
- 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 @@
// 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 @@
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 @@
.unwrap()
.iter()
.filter(|&&(a, _)| starts(a, &*arg_os))
- .count() == 1)
+ .count()
+ == 1)
})
.map(|sc| &sc.p.meta.name)
.collect::<Vec<_>>();
@@ -715,7 +750,8 @@
debugln!("Parser::parse_help_subcommand;");
let cmds: Vec<OsString> = 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 @@
// 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 @@
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 @@
};
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 @@
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 @@
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 @@
} 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 @@
}
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 @@
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 @@
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 @@
}
}
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 @@
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 @@
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 @@
};
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 @@
}
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 @@
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 @@
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 @@
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 @@
Ok(())
}
- pub fn flags(&self) -> Iter<FlagBuilder<'a, 'b>> { self.flags.iter() }
+ pub fn flags(&self) -> Iter<FlagBuilder<'a, 'b>> {
+ self.flags.iter()
+ }
- pub fn opts(&self) -> Iter<OptBuilder<'a, 'b>> { self.opts.iter() }
+ pub fn opts(&self) -> Iter<OptBuilder<'a, 'b>> {
+ self.opts.iter()
+ }
- pub fn positionals(&self) -> map::Values<PosBuilder<'a, 'b>> { self.positionals.values() }
+ pub fn positionals(&self) -> map::Values<PosBuilder<'a, 'b>> {
+ self.positionals.values()
+ }
- pub fn subcommands(&self) -> Iter<App> { self.subcommands.iter() }
+ pub fn subcommands(&self) -> Iter<App> {
+ self.subcommands.iter()
+ }
// Should we color the output? None=determined by output location, true=yes, false=no
#[doc(hidden)]
@@ -2160,8 +2230,12 @@
}
#[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 ec03997..e387d9e 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 @@
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 @@
/// [`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 6090588..e8105c6 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 @@
// 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 @@
} 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 @@
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 get_args_tag(p: &Parser, incl_reqs: bool) -> Option<String> {
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 @@
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 @@
.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::<Vec<_>>()
.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 @@
.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::<Vec<_>>()
.join(""),
);
@@ -332,28 +336,40 @@
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 @@
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 @@
.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 181b831..862f0bb 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 app::parser::{ParseResult, Parser};
+use app::settings::AppSettings as AS;
+use app::usage;
+use args::settings::ArgSettings;
+use args::{AnyArg, ArgMatcher, MatchedArg};
+use errors::Result as ClapResult;
+use errors::{Error, ErrorKind};
+use fmt::{Colorizer, ColorizerOption};
use INTERNAL_ERROR_MSG;
use INVALID_UTF8;
-use args::{AnyArg, ArgMatcher, MatchedArg};
-use args::settings::ArgSettings;
-use errors::{Error, ErrorKind};
-use errors::Result as ClapResult;
-use app::settings::AppSettings as AS;
-use app::parser::{ParseResult, Parser};
-use fmt::{Colorizer, ColorizerOption};
-use app::usage;
pub struct Validator<'a, 'b, 'z>(&'z mut Parser<'a, 'b>)
where
@@ -21,7 +21,9 @@
'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 @@
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 @@
}
}
- 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 @@
));
}
}
- 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 @@
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 @@
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 @@
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 @@
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 @@
}
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 @@
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 @@
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 eee5228..46aa763 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 @@
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<Vec<&'e str>> { (*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<u64> { (*self).max_vals() }
- fn min_vals(&self) -> Option<u64> { (*self).min_vals() }
- fn num_vals(&self) -> Option<u64> { (*self).num_vals() }
- fn possible_vals(&self) -> Option<&[&'e str]> { (*self).possible_vals() }
- fn validator(&self) -> Option<&Rc<Fn(String) -> Result<(), String>>> { (*self).validator() }
- fn validator_os(&self) -> Option<&Rc<Fn(&OsStr) -> Result<(), OsString>>> { (*self).validator_os() }
- fn short(&self) -> Option<char> { (*self).short() }
- fn long(&self) -> Option<&'e str> { (*self).long() }
- fn val_delim(&self) -> Option<char> { (*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<map::Values<(&'n str, Option<&'e OsStr>, &'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<Vec<&'e str>> {
+ (*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<u64> {
+ (*self).max_vals()
+ }
+ fn min_vals(&self) -> Option<u64> {
+ (*self).min_vals()
+ }
+ fn num_vals(&self) -> Option<u64> {
+ (*self).num_vals()
+ }
+ fn possible_vals(&self) -> Option<&[&'e str]> {
+ (*self).possible_vals()
+ }
+ fn validator(&self) -> Option<&Rc<Fn(String) -> Result<(), String>>> {
+ (*self).validator()
+ }
+ fn validator_os(&self) -> Option<&Rc<Fn(&OsStr) -> Result<(), OsString>>> {
+ (*self).validator_os()
+ }
+ fn short(&self) -> Option<char> {
+ (*self).short()
+ }
+ fn long(&self) -> Option<&'e str> {
+ (*self).long()
+ }
+ fn val_delim(&self) -> Option<char> {
+ (*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<map::Values<(&'n str, Option<&'e OsStr>, &'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 50a30ab..ce578e0 100644
--- a/src/args/arg.rs
+++ b/src/args/arg.rs
@@ -1,20 +1,20 @@
-#[cfg(feature = "yaml")]
-use std::collections::BTreeMap;
-use std::rc::Rc;
-use std::ffi::{OsStr, OsString};
#[cfg(any(target_os = "windows", target_arch = "wasm32"))]
use osstringext::OsStrExt3;
+#[cfg(feature = "yaml")]
+use std::collections::BTreeMap;
+use std::env;
+use std::ffi::{OsStr, OsString};
#[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 @@
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<u64>,
- #[doc(hidden)] pub r_ifs: Option<Vec<(&'a str, &'b str)>>,
+ #[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<u64>,
+ #[doc(hidden)]
+ pub r_ifs: Option<Vec<(&'a str, &'b str)>>,
}
impl<'a, 'b> Arg<'a, 'b> {
diff --git a/src/args/arg_builder/base.rs b/src/args/arg_builder/base.rs
index fef9d8a..cc8de72 100644
--- a/src/args/arg_builder/base.rs
+++ b/src/args/arg_builder/base.rs
@@ -24,15 +24,25 @@
}
}
- 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 641e777..4b92231 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> 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<u64> { None }
- fn val_names(&self) -> Option<&VecMap<&'e str>> { None }
- fn num_vals(&self) -> Option<u64> { None }
- fn possible_vals(&self) -> Option<&[&'e str]> { None }
- fn validator(&self) -> Option<&Rc<Fn(String) -> StdResult<(), String>>> { None }
- fn validator_os(&self) -> Option<&Rc<Fn(&OsStr) -> StdResult<(), OsString>>> { None }
- fn min_vals(&self) -> Option<u64> { None }
- fn short(&self) -> Option<char> { self.s.short }
- fn long(&self) -> Option<&'e str> { self.s.long }
- fn val_delim(&self) -> Option<char> { 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<u64> {
+ None
+ }
+ fn val_names(&self) -> Option<&VecMap<&'e str>> {
+ None
+ }
+ fn num_vals(&self) -> Option<u64> {
+ None
+ }
+ fn possible_vals(&self) -> Option<&[&'e str]> {
+ None
+ }
+ fn validator(&self) -> Option<&Rc<Fn(String) -> StdResult<(), String>>> {
+ None
+ }
+ fn validator_os(&self) -> Option<&Rc<Fn(&OsStr) -> StdResult<(), OsString>>> {
+ None
+ }
+ fn min_vals(&self) -> Option<u64> {
+ None
+ }
+ fn short(&self) -> Option<char> {
+ self.s.short
+ }
+ fn long(&self) -> Option<&'e str> {
+ self.s.long
+ }
+ fn val_delim(&self) -> Option<char> {
+ 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<map::Values<(&'n str, Option<&'e OsStr>, &'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<Vec<&'e str>> {
if let Some(ref aliases) = self.s.aliases {
let vis_aliases: Vec<_> = aliases
@@ -109,17 +157,21 @@
}
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 d1a7a66..2d79208 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 flag;
-mod positional;
-mod option;
mod base;
-mod valued;
+mod flag;
+mod option;
+mod positional;
mod switched;
+mod valued;
diff --git a/src/args/arg_builder/option.rs b/src/args/arg_builder/option.rs
index 4bb147a..45d41fa 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> 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<u64> { self.v.max_vals }
- fn val_terminator(&self) -> Option<&'e str> { self.v.terminator }
- fn num_vals(&self) -> Option<u64> { 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<u64> {
+ self.v.max_vals
+ }
+ fn val_terminator(&self) -> Option<&'e str> {
+ self.v.terminator
+ }
+ fn num_vals(&self) -> Option<u64> {
+ 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<Fn(String) -> StdResult<(), String>>> {
self.v.validator.as_ref()
}
fn validator_os(&self) -> Option<&Rc<Fn(&OsStr) -> StdResult<(), OsString>>> {
self.v.validator_os.as_ref()
}
- fn min_vals(&self) -> Option<u64> { self.v.min_vals }
- fn short(&self) -> Option<char> { self.s.short }
- fn long(&self) -> Option<&'e str> { self.s.long }
- fn val_delim(&self) -> Option<char> { 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<u64> {
+ self.v.min_vals
+ }
+ fn short(&self) -> Option<char> {
+ self.s.short
+ }
+ fn long(&self) -> Option<&'e str> {
+ self.s.long
+ }
+ fn val_delim(&self) -> Option<char> {
+ 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<map::Values<(&'n str, Option<&'e OsStr>, &'e OsStr)>> {
self.v.default_vals_ifs.as_ref().map(|vm| vm.values())
}
@@ -152,7 +192,9 @@
.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<Vec<&'e str>> {
if let Some(ref aliases) = self.s.aliases {
let vis_aliases: Vec<_> = aliases
@@ -171,17 +213,21 @@
}
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 43fdca4..6d8c1fe 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 @@
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 @@
}
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 @@
}
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> 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<u64> { self.v.max_vals }
- fn val_terminator(&self) -> Option<&'e str> { self.v.terminator }
- fn num_vals(&self) -> Option<u64> { 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<u64> {
+ self.v.max_vals
+ }
+ fn val_terminator(&self) -> Option<&'e str> {
+ self.v.terminator
+ }
+ fn num_vals(&self) -> Option<u64> {
+ 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<Fn(String) -> StdResult<(), String>>> {
self.v.validator.as_ref()
}
fn validator_os(&self) -> Option<&Rc<Fn(&OsStr) -> StdResult<(), OsString>>> {
self.v.validator_os.as_ref()
}
- fn min_vals(&self) -> Option<u64> { self.v.min_vals }
- fn short(&self) -> Option<char> { None }
- fn long(&self) -> Option<&'e str> { None }
- fn val_delim(&self) -> Option<char> { 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<u64> {
+ self.v.min_vals
+ }
+ fn short(&self) -> Option<char> {
+ None
+ }
+ fn long(&self) -> Option<&'e str> {
+ None
+ }
+ fn val_delim(&self) -> Option<char> {
+ 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<map::Values<(&'n str, Option<&'e OsStr>, &'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<Vec<&'e str>> { None }
+ fn longest_filter(&self) -> bool {
+ true
+ }
+ fn aliases(&self) -> Option<Vec<&'e str>> {
+ 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 224b2f2..777ff1d 100644
--- a/src/args/arg_builder/switched.rs
+++ b/src/args/arg_builder/switched.rs
@@ -22,7 +22,9 @@
}
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 d70854d..82e1487 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 e1d8067..1a0a149 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 @@
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 @@
}
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 @@
}
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 @@
}
}
- 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 @@
}
}
- 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> Into<ArgMatches<'a>> 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 6cf70a4..f017c4e 100644
--- a/src/args/arg_matches.rs
+++ b/src/args/arg_matches.rs
@@ -6,11 +6,11 @@
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 where supplied to the program at runtime by
+/// 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
/// methods.
///
@@ -59,9 +59,12 @@
/// [`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<Box<SubCommand<'a>>>,
- #[doc(hidden)] pub usage: Option<String>,
+ #[doc(hidden)]
+ pub args: HashMap<&'a str, MatchedArg>,
+ #[doc(hidden)]
+ pub subcommand: Option<Box<SubCommand<'a>>>,
+ #[doc(hidden)]
+ pub usage: Option<String>,
}
impl<'a> Default for ArgMatches<'a> {
@@ -210,7 +213,9 @@
/// [`Iterator`]: https://doc.rust-lang.org/std/iter/trait.Iterator.html
pub fn values_of<S: AsRef<str>>(&'a self, name: S) -> Option<Values<'a>> {
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 @@
/// [`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<S: AsRef<str>>(&'a self, name: S) -> Option<OsValues<'a>> {
- 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 @@
/// [delimiter]: ./struct.Arg.html#method.value_delimiter
pub fn indices_of<S: AsRef<str>>(&'a self, name: S) -> Option<Indices<'a>> {
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 @@
/// ```
/// [`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 @@
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<usize>) { self.iter.size_hint() }
+ fn next(&mut self) -> Option<&'a str> {
+ self.iter.next()
+ }
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ 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 @@
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 @@
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<usize>) { self.iter.size_hint() }
+ fn next(&mut self) -> Option<&'a OsStr> {
+ self.iter.next()
+ }
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ 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 @@
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 @@
/// ```
/// [`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<Iter<'a, usize>, fn(&'a usize) -> usize>,
}
impl<'a> Iterator for Indices<'a> {
type Item = usize;
- fn next(&mut self) -> Option<usize> { self.iter.next() }
- fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
+ fn next(&mut self) -> Option<usize> {
+ self.iter.next()
+ }
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ self.iter.size_hint()
+ }
}
impl<'a> DoubleEndedIterator for Indices<'a> {
- fn next_back(&mut self) -> Option<usize> { self.iter.next_back() }
+ fn next_back(&mut self) -> Option<usize> {
+ self.iter.next_back()
+ }
}
impl<'a> ExactSizeIterator for Indices<'a> {}
@@ -911,7 +944,9 @@
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 f8bfb7a..8103a9c 100644
--- a/src/args/group.rs
+++ b/src/args/group.rs
@@ -79,12 +79,18 @@
/// [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<Vec<&'a str>>,
- #[doc(hidden)] pub conflicts: Option<Vec<&'a str>>,
- #[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<Vec<&'a str>>,
+ #[doc(hidden)]
+ pub conflicts: Option<Vec<&'a str>>,
+ #[doc(hidden)]
+ pub multiple: bool,
}
impl<'a> ArgGroup<'a> {
@@ -123,7 +129,9 @@
/// # }
/// ```
#[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 @@
\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 @@
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 1de12f4..ac4b1a2 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 @@
#[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 @@
#[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 eeda261..681e5d2 100644
--- a/src/args/matched_arg.rs
+++ b/src/args/matched_arg.rs
@@ -4,9 +4,12 @@
#[doc(hidden)]
#[derive(Debug, Clone)]
pub struct MatchedArg {
- #[doc(hidden)] pub occurs: u64,
- #[doc(hidden)] pub indices: Vec<usize>,
- #[doc(hidden)] pub vals: Vec<OsString>,
+ #[doc(hidden)]
+ pub occurs: u64,
+ #[doc(hidden)]
+ pub indices: Vec<usize>,
+ #[doc(hidden)]
+ pub vals: Vec<OsString>,
}
impl Default for MatchedArg {
@@ -20,5 +23,7 @@
}
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 21f9b85..8f076ea 100644
--- a/src/args/mod.rs
+++ b/src/args/mod.rs
@@ -10,12 +10,12 @@
#[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 7b0e0a2..833a1ea 100644
--- a/src/args/settings.rs
+++ b/src/args/settings.rs
@@ -33,9 +33,11 @@
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 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 @@
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 eebbf82..8b8049e 100644
--- a/src/args/subcommand.rs
+++ b/src/args/subcommand.rs
@@ -29,8 +29,10 @@
/// [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 @@
/// 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 @@
/// # }
/// ```
#[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 37dfa66..b712a68 100644
--- a/src/completions/bash.rs
+++ b/src/completions/bash.rs
@@ -14,7 +14,9 @@
}
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<W: Write>(&self, buf: &mut W) {
w!(
@@ -68,7 +70,8 @@
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 9a5f21a..12be03d 100644
--- a/src/completions/elvish.rs
+++ b/src/completions/elvish.rs
@@ -13,16 +13,18 @@
}
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<W: Write>(&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 @@
}
// Escape string inside single quotes
-fn escape_string(string: &str) -> String { string.replace("'", "''") }
+fn escape_string(string: &str) -> String {
+ string.replace("'", "''")
+}
-fn get_tooltip<T : ToString>(help: Option<&str>, data: T) -> String {
+fn get_tooltip<T: ToString>(help: Option<&str>, data: T) -> String {
match help {
Some(help) => escape_string(help),
- _ => data.to_string()
+ _ => data.to_string(),
}
}
@@ -112,13 +116,11 @@
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 c2c5a5e..a2bf888 100644
--- a/src/completions/fish.rs
+++ b/src/completions/fish.rs
@@ -12,7 +12,9 @@
}
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<W: Write>(&self, buf: &mut W) {
let command = self.p.meta.bin_name.as_ref().unwrap();
@@ -23,7 +25,9 @@
}
// 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 653c72c..3a69de5 100644
--- a/src/completions/macros.rs
+++ b/src/completions/macros.rs
@@ -24,5 +24,5 @@
} else {
String::new()
}
- }
+ };
}
diff --git a/src/completions/mod.rs b/src/completions/mod.rs
index a3306d7..99d4005 100644
--- a/src/completions/mod.rs
+++ b/src/completions/mod.rs
@@ -1,23 +1,23 @@
#[macro_use]
mod macros;
mod bash;
-mod fish;
-mod zsh;
-mod powershell;
mod elvish;
+mod fish;
+mod powershell;
mod shell;
+mod zsh;
// Std
use std::io::Write;
// Internal
-use app::parser::Parser;
use self::bash::BashGen;
-use self::fish::FishGen;
-use self::zsh::ZshGen;
-use self::powershell::PowerShellGen;
use self::elvish::ElvishGen;
+use self::fish::FishGen;
+use self::powershell::PowerShellGen;
pub use self::shell::Shell;
+use self::zsh::ZshGen;
+use app::parser::Parser;
pub struct ComplGen<'a, 'b>
where
@@ -27,7 +27,9 @@
}
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<W: Write>(&self, for_shell: Shell, buf: &mut W) {
match for_shell {
@@ -155,13 +157,13 @@
}
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 @@
}
}
}
- 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 9fc77c7..5fafd8d 100644
--- a/src/completions/powershell.rs
+++ b/src/completions/powershell.rs
@@ -13,16 +13,18 @@
}
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<W: Write>(&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 @@
}
// Escape string inside single quotes
-fn escape_string(string: &str) -> String { string.replace("'", "''") }
+fn escape_string(string: &str) -> String {
+ string.replace("'", "''")
+}
-fn get_tooltip<T : ToString>(help: Option<&str>, data: T) -> String {
+fn get_tooltip<T: ToString>(help: Option<&str>, data: T) -> String {
match help {
Some(help) => escape_string(help),
- _ => data.to_string()
+ _ => data.to_string(),
}
}
@@ -86,14 +90,24 @@
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 @@
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 @@
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 @@
'{}' {{{}
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 19aab86..80999e6 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 @@
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 @@
"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 5d23fd2..14cf2b6 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 @@
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 @@
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 @@
)
_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 @@
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 @@
// 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 @@
""
};
let pv = if let Some(pv_vec) = o.possible_vals() {
- format!(": :({})", pv_vec.iter().map(
- |v| escape_value(*v)).collect::<Vec<String>>().join(" "))
+ format!(
+ ": :({})",
+ pv_vec
+ .iter()
+ .map(|v| escape_value(*v))
+ .collect::<Vec<String>>()
+ .join(" ")
+ )
} else {
String::new()
};
@@ -451,16 +453,27 @@
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::<Vec<String>>().join(" "))
+ format!(
+ "({})",
+ values
+ .iter()
+ .map(|v| escape_value(*v))
+ .collect::<Vec<String>>()
+ .join(" ")
+ )
})
);
diff --git a/src/errors.rs b/src/errors.rs
index c6087c0..1f86720 100644
--- a/src/errors.rs
+++ b/src/errors.rs
@@ -403,7 +403,9 @@
}
#[doc(hidden)]
- pub fn write_to<W: Write>(&self, w: &mut W) -> io::Result<()> { write!(w, "{}", self.message) }
+ pub fn write_to<W: Write>(&self, w: &mut W) -> io::Result<()> {
+ write!(w, "{}", self.message)
+ }
#[doc(hidden)]
pub fn argument_conflict<O, U>(
@@ -634,7 +636,6 @@
}
}
-
#[doc(hidden)]
pub fn invalid_utf8<U>(usage: U, color: ColorWhen) -> Self
where
@@ -721,8 +722,7 @@
}
#[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 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<io::Error> 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<std_fmt::Error> for Error {
diff --git a/src/fmt.rs b/src/fmt.rs
index 108a635..fa8b633 100644
--- a/src/fmt.rs
+++ b/src/fmt.rs
@@ -6,8 +6,8 @@
#[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 @@
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 @@
ColorWhen::Auto if is_a_tty && !is_term_dumb => ColorWhen::Auto,
ColorWhen::Auto => ColorWhen::Never,
when => when,
- }
+ },
}
}
@@ -152,22 +154,25 @@
}
}
-
#[cfg(all(feature = "color", not(target_os = "windows")))]
impl<T: AsRef<str>> fmt::Display for Format<T> {
- 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<T: fmt::Display> fmt::Display for Format<T> {
- 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 0a3e1bb..17e2697 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1,4 +1,4 @@
-// Copyright ⓒ 2015-2016 Kevin B. Knapp and [`clap-rs` contributors](https://github.com/clap-rs/clap/blob/master/CONTRIBUTORS.md).
+// Copyright ⓒ 2015-2016 Kevin B. Knapp and [`clap-rs` contributors](https://github.com/clap-rs/clap/blob/v2.33.1/CONTRIBUTORS.md).
// Licensed under the MIT license
// (see LICENSE or <http://opensource.org/licenses/MIT>) All files in the project carrying such
// notice may not be copied, modified, or distributed except according to those terms.
@@ -14,7 +14,7 @@
//! arguments.
//!
//! `clap` also provides the traditional version and help switches (or flags) 'for free' meaning
-//! automatically with no configuration. It does this by checking list of valid possibilities you
+//! automatically with no configuration. It does this by checking the list of valid possibilities you
//! supplied and adding only the ones you haven't already defined. If you are using subcommands,
//! `clap` will also auto-generate a `help` subcommand for you in addition to the traditional flags.
//!
@@ -366,7 +366,7 @@
//! * **Red** Color: **NOT** included by default (must use cargo `features` to enable)
//! * **Blue** Color: Dev dependency, only used while developing.
//!
-//! 
+//! 
//!
//! ### More Information
//!
@@ -391,7 +391,7 @@
//! `clap`. You can either add it to the [examples/] directory, or file an issue and tell
//! me. I'm all about giving credit where credit is due :)
//!
-//! Please read [CONTRIBUTING.md](https://raw.githubusercontent.com/clap-rs/clap/master/.github/CONTRIBUTING.md) before you start contributing.
+//! Please read [CONTRIBUTING.md](https://github.com/clap-rs/clap/blob/v2.33.1/.github/CONTRIBUTING.md) before you start contributing.
//!
//!
//! ### Testing Code
@@ -512,18 +512,27 @@
//! `clap` is licensed under the MIT license. Please read the [LICENSE-MIT][license] file in
//! this repository for more information.
//!
-//! [examples/]: https://github.com/clap-rs/clap/tree/master/examples
+//! [examples/]: https://github.com/clap-rs/clap/tree/v2.33.1/examples
//! [video tutorials]: https://www.youtube.com/playlist?list=PLza5oFLQGTl2Z5T8g1pRkIynR3E0_pc7U
-//! [license]: https://raw.githubusercontent.com/clap-rs/clap/master/LICENSE-MIT
+//! [license]: https://github.com/clap-rs/clap/blob/v2.33.1/LICENSE-MIT
#![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)]
+#![doc(html_root_url = "https://docs.rs/clap/2.33.3")]
+#![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 @@
#[cfg(feature = "yaml")]
extern crate yaml_rust;
+pub use app::{App, AppSettings};
+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;
-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 completions::Shell;
#[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 @@
/// @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<I, T>(argv: I) -> Self
@@ -598,7 +609,6 @@
Self::try_from_argmatches(Self::into_app().get_matches_safe()?)
}
-
/// @TODO @release @docs
fn try_parse_from<I, T>(argv: I) -> Result<Self, clap::Error>
where
diff --git a/src/macros.rs b/src/macros.rs
index 969d42d..4583ea7 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 @@
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 @@
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 @@
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 @@
};
($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::<Vec<$t>>()
+ 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::<Vec<$t>>()
} else {
::clap::Error::argument_not_found_auto($v).exit()
}
@@ -426,7 +436,7 @@
#[macro_export]
macro_rules! crate_version {
() => {
- "2.33.0"
+ "2.33.3"
};
}
@@ -456,17 +466,21 @@
macro_rules! crate_authors {
($sep:expr) => {{
use std::ops::Deref;
- use std::sync::{ONCE_INIT, Once};
+ #[allow(deprecated)]
+ 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;
#[allow(unsafe_code)]
fn deref(&self) -> &'static str {
+ #[allow(deprecated)]
static ONCE: Once = ONCE_INIT;
static mut VALUE: *const String = 0 as *const String;
@@ -481,7 +495,9 @@
}
}
- &*CargoAuthors { __private_field: () }
+ &*CargoAuthors {
+ __private_field: (),
+ }
}};
() => {
["Kevin K. <[email protected]>"].join(":")
@@ -855,16 +871,16 @@
#[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 +889,12 @@
// 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 +967,23 @@
// }};
//}
-
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 +1007,59 @@
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 +1069,6 @@
}};
}
-
macro_rules! longs {
($_self:ident) => {{
_shorts_longs!($_self, long)
@@ -1063,13 +1077,18 @@
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 +1106,21 @@
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 063a860..1349783 100644
--- a/src/map.rs
+++ b/src/map.rs
@@ -6,8 +6,8 @@
#[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 @@
}
}
- 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<V> {
self.inner.insert(key, value)
}
- pub fn values(&self) -> Values<V> { self.inner.values() }
+ pub fn values(&self) -> Values<V> {
+ self.inner.values()
+ }
pub fn iter(&self) -> Iter<V> {
Iter {
@@ -38,11 +44,17 @@
}
}
- 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<V> { self.inner.entry(key) }
+ pub fn entry(&mut self, key: usize) -> Entry<V> {
+ 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 @@
impl<'a, V: 'a> Iterator for Iter<'a, V> {
type Item = (usize, &'a V);
- fn next(&mut self) -> Option<Self::Item> { self.inner.next().map(|(k, v)| (*k, v)) }
+ fn next(&mut self) -> Option<Self::Item> {
+ 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 061c01d..ee0de30 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 {
@@ -20,6 +20,73 @@
fn split(&self, b: u8) -> OsSplit;
}
+// A starts-with implementation that does not panic when the OsStr contains
+// invalid Unicode.
+//
+// A Windows OsStr is usually UTF-16. If `prefix` is valid UTF-8, we can
+// re-encode it as UTF-16, and ask whether `osstr` starts with the same series
+// of u16 code units. If `prefix` is not valid UTF-8, then this comparison
+// isn't meaningful, and we just return false.
+#[cfg(target_os = "windows")]
+fn windows_osstr_starts_with(osstr: &OsStr, prefix: &[u8]) -> bool {
+ use std::os::windows::ffi::OsStrExt;
+ let prefix_str = if let Ok(s) = std::str::from_utf8(prefix) {
+ s
+ } else {
+ return false;
+ };
+ let mut osstr_units = osstr.encode_wide();
+ let mut prefix_units = prefix_str.encode_utf16();
+ loop {
+ match (osstr_units.next(), prefix_units.next()) {
+ // These code units match. Keep looping.
+ (Some(o), Some(p)) if o == p => continue,
+ // We've reached the end of the prefix. It's a match.
+ (_, None) => return true,
+ // Otherwise, it's not a match.
+ _ => return false,
+ }
+ }
+}
+
+#[test]
+#[cfg(target_os = "windows")]
+fn test_windows_osstr_starts_with() {
+ use std::ffi::OsString;
+ use std::os::windows::ffi::OsStringExt;
+
+ fn from_ascii(ascii: &[u8]) -> OsString {
+ let u16_vec: Vec<u16> = ascii.iter().map(|&c| c as u16).collect();
+ OsString::from_wide(&u16_vec)
+ }
+
+ // Test all the basic cases.
+ assert!(windows_osstr_starts_with(&from_ascii(b"abcdef"), b"abc"));
+ assert!(windows_osstr_starts_with(&from_ascii(b"abcdef"), b"abcdef"));
+ assert!(!windows_osstr_starts_with(&from_ascii(b"abcdef"), b"def"));
+ assert!(!windows_osstr_starts_with(&from_ascii(b"abc"), b"abcd"));
+
+ // Test the case where the candidate prefix is not valid UTF-8. Note that a
+ // standalone \xff byte is valid ASCII but not valid UTF-8. Thus although
+ // these strings look identical, they do not match.
+ assert!(!windows_osstr_starts_with(&from_ascii(b"\xff"), b"\xff"));
+
+ // Test the case where the OsString is not valid UTF-16. It should still be
+ // possible to match the valid characters at the front.
+ //
+ // UTF-16 surrogate characters are only valid in pairs. Including one on
+ // the end by itself makes this invalid UTF-16.
+ let surrogate_char: u16 = 0xDC00;
+ let mut invalid_unicode =
+ OsString::from_wide(&['a' as u16, 'b' as u16, 'c' as u16, surrogate_char]);
+ assert!(
+ invalid_unicode.to_str().is_none(),
+ "This string is invalid Unicode, and conversion to &str should fail.",
+ );
+ assert!(windows_osstr_starts_with(&invalid_unicode, b"abc"));
+ assert!(!windows_osstr_starts_with(&invalid_unicode, b"abcd"));
+}
+
#[cfg(any(target_os = "windows", target_arch = "wasm32"))]
impl OsStrExt3 for OsStr {
fn from_bytes(b: &[u8]) -> &Self {
@@ -33,6 +100,20 @@
impl OsStrExt2 for OsStr {
fn starts_with(&self, s: &[u8]) -> bool {
+ #[cfg(target_os = "windows")]
+ {
+ // On Windows, the as_bytes() method will panic if the OsStr
+ // contains invalid Unicode. To avoid this, we use a
+ // Windows-specific starts-with function that doesn't rely on
+ // as_bytes(). This is necessary for Windows command line
+ // applications to handle non-Unicode arguments successfully. This
+ // allows common cases like `clap.exe [invalid]` to succeed, though
+ // cases that require string splitting will still fail, like
+ // `clap.exe --arg=[invalid]`. Note that this entire module is
+ // replaced in Clap 3.x, so this workaround is specific to the 2.x
+ // branch.
+ return windows_osstr_starts_with(self, s);
+ }
self.as_bytes().starts_with(s)
}
diff --git a/src/suggestions.rs b/src/suggestions.rs
index 06071d2..1157b26 100644
--- a/src/suggestions.rs
+++ b/src/suggestions.rs
@@ -57,7 +57,7 @@
"\n\tDid you mean {}{}?",
Format::Good("--"),
Format::Good(candidate)
- );
+ );
return (suffix, Some(candidate));
}
@@ -73,11 +73,11 @@
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 f6d5ac6..0a383eb 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 @@
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 @@
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 @@
}
#[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 @@
}
#[inline]
-fn help_start(b: u8) -> bool { b != b'\'' }
+fn help_start(b: u8) -> bool {
+ b != b'\''
+}
#[cfg(test)]
mod test {