style: cargo fmt run

This commit is contained in:
Kevin K 2018-11-14 12:05:06 -05:00
parent f6ce7d5cc2
commit 20c72525d2
50 changed files with 947 additions and 745 deletions

View file

@ -4,7 +4,7 @@
extern crate clap;
extern crate test;
use clap::{App, AppSettings, Arg, ArgSettings, };
use clap::{App, AppSettings, Arg, ArgSettings};
use test::Bencher;

View file

@ -8,7 +8,7 @@ use test::Bencher;
use std::io::Cursor;
use clap::App;
use clap::{Arg, ArgSettings, };
use clap::{Arg, ArgSettings};
fn build_help(app: &mut App) -> String {
let mut buf = Cursor::new(Vec::with_capacity(50));
@ -22,9 +22,7 @@ fn app_example1<'b, 'c>() -> App<'b, 'c> {
.version("1.0")
.author("Kevin K. <kbknapp@gmail.com>")
.about("Does awesome things")
.arg(
"-c, --config=[FILE] 'Sets a custom config file'"
)
.arg("-c, --config=[FILE] 'Sets a custom config file'")
.arg("<output> 'Sets an optional output file'")
.arg("-d... 'Turn debugging information on'")
.subcommand(

View file

@ -296,68 +296,109 @@ where
.arg(flag("help"))
.arg(flag("version").short('V'))
// First, set up primary positional/flag arguments.
.arg(arg("pattern")
.required_unless_one(&[
"file", "files", "help-short", "help", "regexp", "type-list",
"version",
]))
.arg(arg("path").setting(ArgSettings::MultipleValues).setting(ArgSettings::MultipleOccurrences))
.arg(flag("regexp").short('e')
.settings(&[
ArgSettings::AllowHyphenValues,
ArgSettings::MultipleOccurrences,
ArgSettings::TakesValue])
.value_name("pattern"))
.arg(flag("files")
// This should also conflict with `pattern`, but the first file
// path will actually be in `pattern`.
.conflicts_with_all(&["file", "regexp", "type-list"]))
.arg(flag("type-list")
.conflicts_with_all(&["file", "files", "pattern", "regexp"]))
.arg(arg("pattern").required_unless_one(&[
"file",
"files",
"help-short",
"help",
"regexp",
"type-list",
"version",
]))
.arg(
arg("path")
.setting(ArgSettings::MultipleValues)
.setting(ArgSettings::MultipleOccurrences),
)
.arg(
flag("regexp")
.short('e')
.settings(&[
ArgSettings::AllowHyphenValues,
ArgSettings::MultipleOccurrences,
ArgSettings::TakesValue,
])
.value_name("pattern"),
)
.arg(
flag("files")
// This should also conflict with `pattern`, but the first file
// path will actually be in `pattern`.
.conflicts_with_all(&["file", "regexp", "type-list"]),
)
.arg(flag("type-list").conflicts_with_all(&["file", "files", "pattern", "regexp"]))
// Second, set up common flags.
.arg(flag("text").short('a'))
.arg(flag("count").short('c'))
.arg(flag("color")
.value_name("WHEN")
.setting(ArgSettings::HidePossibleValues)
.possible_values(&["never", "auto", "always", "ansi"]))
.arg(flag("colors").value_name("SPEC")
.settings(&[ArgSettings::MultipleOccurrences, ArgSettings::TakesValue]))
.arg(
flag("color")
.value_name("WHEN")
.setting(ArgSettings::HidePossibleValues)
.possible_values(&["never", "auto", "always", "ansi"]),
)
.arg(
flag("colors")
.value_name("SPEC")
.settings(&[ArgSettings::MultipleOccurrences, ArgSettings::TakesValue]),
)
.arg(flag("fixed-strings").short('F'))
.arg(flag("glob").short('g')
.settings(&[ArgSettings::MultipleOccurrences, ArgSettings::TakesValue])
.value_name("GLOB"))
.arg(
flag("glob")
.short('g')
.settings(&[ArgSettings::MultipleOccurrences, ArgSettings::TakesValue])
.value_name("GLOB"),
)
.arg(flag("ignore-case").short('i'))
.arg(flag("line-number").short('n'))
.arg(flag("no-line-number").short('N'))
.arg(flag("quiet").short('q'))
.arg(flag("type").short('t')
.settings(&[ArgSettings::MultipleOccurrences, ArgSettings::TakesValue])
.value_name("TYPE"))
.arg(flag("type-not").short('T')
.settings(&[ArgSettings::MultipleOccurrences, ArgSettings::TakesValue])
.value_name("TYPE"))
.arg(flag("unrestricted").short('u')
.setting(ArgSettings::MultipleOccurrences))
.arg(
flag("type")
.short('t')
.settings(&[ArgSettings::MultipleOccurrences, ArgSettings::TakesValue])
.value_name("TYPE"),
)
.arg(
flag("type-not")
.short('T')
.settings(&[ArgSettings::MultipleOccurrences, ArgSettings::TakesValue])
.value_name("TYPE"),
)
.arg(
flag("unrestricted")
.short('u')
.setting(ArgSettings::MultipleOccurrences),
)
.arg(flag("invert-match").short('v'))
.arg(flag("word-regexp").short('w'))
// Third, set up less common flags.
.arg(flag("after-context").short('A')
.value_name("NUM")
.validator(validate_number))
.arg(flag("before-context").short('B')
.value_name("NUM")
.validator(validate_number))
.arg(flag("context").short('C')
.value_name("NUM")
.validator(validate_number))
.arg(
flag("after-context")
.short('A')
.value_name("NUM")
.validator(validate_number),
)
.arg(
flag("before-context")
.short('B')
.value_name("NUM")
.validator(validate_number),
)
.arg(
flag("context")
.short('C')
.value_name("NUM")
.validator(validate_number),
)
.arg(flag("column"))
.arg(flag("context-separator")
.value_name("SEPARATOR"))
.arg(flag("context-separator").value_name("SEPARATOR"))
.arg(flag("debug"))
.arg(flag("file").short('f')
.value_name("FILE")
.setting(ArgSettings::MultipleOccurrences))
.arg(
flag("file")
.short('f')
.value_name("FILE")
.setting(ArgSettings::MultipleOccurrences),
)
.arg(flag("files-with-matches").short('l'))
.arg(flag("files-without-match"))
.arg(flag("with-filename").short('H'))
@ -365,16 +406,23 @@ where
.arg(flag("heading").overrides_with("no-heading"))
.arg(flag("no-heading").overrides_with("heading"))
.arg(flag("hidden"))
.arg(flag("ignore-file")
.value_name("FILE")
.setting(ArgSettings::MultipleOccurrences))
.arg(
flag("ignore-file")
.value_name("FILE")
.setting(ArgSettings::MultipleOccurrences),
)
.arg(flag("follow").short('L'))
.arg(flag("max-count")
.short('m').value_name("NUM")
.validator(validate_number))
.arg(flag("maxdepth")
.value_name("NUM")
.validator(validate_number))
.arg(
flag("max-count")
.short('m')
.value_name("NUM")
.validator(validate_number),
)
.arg(
flag("maxdepth")
.value_name("NUM")
.validator(validate_number),
)
.arg(flag("mmap"))
.arg(flag("no-messages"))
.arg(flag("no-mmap"))
@ -388,16 +436,23 @@ where
.arg(flag("case-sensitive").short('s'))
.arg(flag("smart-case").short('S'))
.arg(flag("sort-files"))
.arg(flag("threads")
.short('j').value_name("ARG")
.validator(validate_number))
.arg(
flag("threads")
.short('j')
.value_name("ARG")
.validator(validate_number),
)
.arg(flag("vimgrep"))
.arg(flag("type-add")
.value_name("TYPE")
.setting(ArgSettings::MultipleOccurrences))
.arg(flag("type-clear")
.value_name("TYPE")
.setting(ArgSettings::MultipleOccurrences))
.arg(
flag("type-add")
.value_name("TYPE")
.setting(ArgSettings::MultipleOccurrences),
)
.arg(
flag("type-clear")
.value_name("TYPE")
.setting(ArgSettings::MultipleOccurrences),
)
}
struct Usage {

View file

@ -30,206 +30,306 @@ pub fn build_cli() -> App<'static, 'static> {
.setting(AppSettings::VersionlessSubcommands)
.setting(AppSettings::DeriveDisplayOrder)
// .setting(AppSettings::SubcommandRequiredElseHelp)
.arg(Arg::with_name("verbose")
.help("Enable verbose output")
.short('v')
.long("verbose"))
.subcommand(App::new("show")
.about("Show the active and installed toolchains")
.after_help(SHOW_HELP))
.subcommand(App::new("install")
.about("Update Rust toolchains")
.after_help(TOOLCHAIN_INSTALL_HELP)
.setting(AppSettings::Hidden) // synonym for 'toolchain install'
.arg(Arg::with_name("toolchain")
.setting(ArgSettings::Required)))
.subcommand(App::new("update")
.about("Update Rust toolchains")
.after_help(UPDATE_HELP)
.arg(Arg::with_name("toolchain").setting(ArgSettings::Required))
.arg(Arg::with_name("no-self-update")
.help("Don't perform self update when running the `rustup` command")
.long("no-self-update")
.setting(ArgSettings::Hidden)))
.subcommand(App::new("default")
.about("Set the default toolchain")
.after_help(DEFAULT_HELP)
.arg(Arg::with_name("toolchain").setting(ArgSettings::Required)))
.subcommand(App::new("toolchain")
.about("Modify or query the installed toolchains")
.after_help(TOOLCHAIN_HELP)
.setting(AppSettings::DeriveDisplayOrder)
// .setting(AppSettings::SubcommandRequiredElseHelp)
.subcommand(App::new("list").about("List installed toolchains"))
.subcommand(App::new("install")
.about("Install or update a given toolchain")
.arg(Arg::with_name("toolchain").setting(ArgSettings::Required)))
.subcommand(App::new("uninstall")
.about("Uninstall a toolchain")
.arg(Arg::with_name("toolchain").setting(ArgSettings::Required)))
.subcommand(App::new("link")
.about("Create a custom toolchain by symlinking to a directory")
.arg(
Arg::with_name("verbose")
.help("Enable verbose output")
.short('v')
.long("verbose"),
)
.subcommand(
App::new("show")
.about("Show the active and installed toolchains")
.after_help(SHOW_HELP),
)
.subcommand(
App::new("install")
.about("Update Rust toolchains")
.after_help(TOOLCHAIN_INSTALL_HELP)
.setting(AppSettings::Hidden) // synonym for 'toolchain install'
.arg(Arg::with_name("toolchain").setting(ArgSettings::Required)),
)
.subcommand(
App::new("update")
.about("Update Rust toolchains")
.after_help(UPDATE_HELP)
.arg(Arg::with_name("toolchain").setting(ArgSettings::Required))
.arg(Arg::with_name("path").setting(ArgSettings::Required)))
.subcommand(App::new("update")
.setting(AppSettings::Hidden) // synonym for 'install'
.arg(Arg::with_name("toolchain")
.setting(ArgSettings::Required)))
.subcommand(App::new("add")
.setting(AppSettings::Hidden) // synonym for 'install'
.arg(Arg::with_name("toolchain")
.setting(ArgSettings::Required)))
.subcommand(App::new("remove")
.setting(AppSettings::Hidden) // synonym for 'uninstall'
.arg(Arg::with_name("toolchain")
.setting(ArgSettings::Required))))
.subcommand(App::new("target")
.about("Modify a toolchain's supported targets")
.setting(AppSettings::VersionlessSubcommands)
.setting(AppSettings::DeriveDisplayOrder)
// .setting(AppSettings::SubcommandRequiredElseHelp)
.subcommand(App::new("list")
.about("List installed and available targets")
.arg(Arg::with_name("toolchain")
.long("toolchain")
.setting(ArgSettings::TakesValue)))
.subcommand(App::new("add")
.about("Add a target to a Rust toolchain")
.arg(Arg::with_name("target").setting(ArgSettings::Required))
.arg(Arg::with_name("toolchain")
.long("toolchain")
.setting(ArgSettings::TakesValue)))
.subcommand(App::new("remove")
.about("Remove a target from a Rust toolchain")
.arg(Arg::with_name("target").setting(ArgSettings::Required))
.arg(Arg::with_name("toolchain")
.long("toolchain")
.setting(ArgSettings::TakesValue)))
.subcommand(App::new("install")
.setting(AppSettings::Hidden) // synonym for 'add'
.arg(Arg::with_name("target")
.setting(ArgSettings::Required))
.arg(Arg::with_name("toolchain")
.long("toolchain")
.setting(ArgSettings::TakesValue)))
.subcommand(App::new("uninstall")
.setting(AppSettings::Hidden) // synonym for 'remove'
.arg(Arg::with_name("target")
.setting(ArgSettings::Required))
.arg(Arg::with_name("toolchain")
.long("toolchain")
.setting(ArgSettings::TakesValue))))
.subcommand(App::new("component")
.about("Modify a toolchain's installed components")
.setting(AppSettings::VersionlessSubcommands)
.setting(AppSettings::DeriveDisplayOrder)
// .setting(AppSettings::SubcommandRequiredElseHelp)
.subcommand(App::new("list")
.about("List installed and available components")
.arg(Arg::with_name("toolchain")
.long("toolchain")
.setting(ArgSettings::TakesValue)))
.subcommand(App::new("add")
.about("Add a component to a Rust toolchain")
.arg(Arg::with_name("component").setting(ArgSettings::Required))
.arg(Arg::with_name("toolchain")
.long("toolchain")
.setting(ArgSettings::TakesValue))
.arg(Arg::with_name("target")
.long("target")
.setting(ArgSettings::TakesValue)))
.subcommand(App::new("remove")
.about("Remove a component from a Rust toolchain")
.arg(Arg::with_name("component").setting(ArgSettings::Required))
.arg(Arg::with_name("toolchain")
.long("toolchain")
.setting(ArgSettings::TakesValue))
.arg(Arg::with_name("target")
.long("target")
.setting(ArgSettings::TakesValue))))
.subcommand(App::new("override")
.about("Modify directory toolchain overrides")
.after_help(OVERRIDE_HELP)
.setting(AppSettings::VersionlessSubcommands)
.setting(AppSettings::DeriveDisplayOrder)
// .setting(AppSettings::SubcommandRequiredElseHelp)
.subcommand(App::new("list").about("List directory toolchain overrides"))
.subcommand(App::new("set")
.about("Set the override toolchain for a directory")
.arg(Arg::with_name("toolchain").setting(ArgSettings::Required)))
.subcommand(App::new("unset")
.about("Remove the override toolchain for a directory")
.after_help(OVERRIDE_UNSET_HELP)
.arg(Arg::with_name("path")
.long("path")
.setting(ArgSettings::TakesValue)
.help("Path to the directory"))
.arg(Arg::with_name("nonexistent")
.long("nonexistent")
.help("Remove override toolchain for all nonexistent directories")))
.subcommand(App::new("add")
.setting(AppSettings::Hidden) // synonym for 'set'
.arg(Arg::with_name("toolchain")
.setting(ArgSettings::Required)))
.subcommand(App::new("remove")
.setting(AppSettings::Hidden) // synonym for 'unset'
.about("Remove the override toolchain for a directory")
.arg(Arg::with_name("path")
.long("path")
.setting(ArgSettings::TakesValue))
.arg(Arg::with_name("nonexistent")
.long("nonexistent")
.help("Remove override toolchain for all nonexistent directories"))))
.subcommand(App::new("run")
.about("Run a command with an environment configured for a given toolchain")
.after_help(RUN_HELP)
.setting(AppSettings::TrailingVarArg)
.arg(Arg::with_name("toolchain").setting(ArgSettings::Required))
.arg(Arg::with_name("command")
.settings(&[ArgSettings::Required, ArgSettings::MultipleValues, ArgSettings::MultipleOccurrences])))
.subcommand(App::new("which")
.about("Display which binary will be run for a given command")
.arg(Arg::with_name("command").setting(ArgSettings::Required)))
.subcommand(App::new("doc")
.about("Open the documentation for the current toolchain")
.after_help(DOC_HELP)
.arg(Arg::with_name("book")
.long("book")
.help("The Rust Programming Language book"))
.arg(Arg::with_name("std")
.long("std")
.help("Standard library API documentation"))
.group(ArgGroup::with_name("page").args(&["book", "std"])))
.subcommand(App::new("man")
.about("View the man page for a given command")
.arg(Arg::with_name("command").setting(ArgSettings::Required))
.arg(Arg::with_name("toolchain")
.long("toolchain")
.setting(ArgSettings::TakesValue)))
.subcommand(App::new("self")
.about("Modify the rustup installation")
.setting(AppSettings::VersionlessSubcommands)
.setting(AppSettings::DeriveDisplayOrder)
.subcommand(App::new("update")
.about("Download and install updates to rustup"))
.subcommand(App::new("uninstall")
.about("Uninstall rustup.")
.arg(Arg::with_name("no-prompt").short('y')))
.subcommand(App::new("upgrade-data")
.about("Upgrade the internal data format.")))
.subcommand(App::new("telemetry")
.about("rustup telemetry commands")
.setting(AppSettings::Hidden)
.setting(AppSettings::VersionlessSubcommands)
.setting(AppSettings::DeriveDisplayOrder)
.subcommand(App::new("enable").about("Enable rustup telemetry"))
.subcommand(App::new("disable").about("Disable rustup telemetry"))
.subcommand(App::new("analyze").about("Analyze stored telemetry")))
.subcommand(App::new("set")
.about("Alter rustup settings")
.subcommand(App::new("default-host")
.about("The triple used to identify toolchains when not specified")
.arg(Arg::with_name("host_triple").setting(ArgSettings::Required))))
.arg(
Arg::with_name("no-self-update")
.help("Don't perform self update when running the `rustup` command")
.long("no-self-update")
.setting(ArgSettings::Hidden),
),
)
.subcommand(
App::new("default")
.about("Set the default toolchain")
.after_help(DEFAULT_HELP)
.arg(Arg::with_name("toolchain").setting(ArgSettings::Required)),
)
.subcommand(
App::new("toolchain")
.about("Modify or query the installed toolchains")
.after_help(TOOLCHAIN_HELP)
.setting(AppSettings::DeriveDisplayOrder)
// .setting(AppSettings::SubcommandRequiredElseHelp)
.subcommand(App::new("list").about("List installed toolchains"))
.subcommand(
App::new("install")
.about("Install or update a given toolchain")
.arg(Arg::with_name("toolchain").setting(ArgSettings::Required)),
)
.subcommand(
App::new("uninstall")
.about("Uninstall a toolchain")
.arg(Arg::with_name("toolchain").setting(ArgSettings::Required)),
)
.subcommand(
App::new("link")
.about("Create a custom toolchain by symlinking to a directory")
.arg(Arg::with_name("toolchain").setting(ArgSettings::Required))
.arg(Arg::with_name("path").setting(ArgSettings::Required)),
)
.subcommand(
App::new("update")
.setting(AppSettings::Hidden) // synonym for 'install'
.arg(Arg::with_name("toolchain").setting(ArgSettings::Required)),
)
.subcommand(
App::new("add")
.setting(AppSettings::Hidden) // synonym for 'install'
.arg(Arg::with_name("toolchain").setting(ArgSettings::Required)),
)
.subcommand(
App::new("remove")
.setting(AppSettings::Hidden) // synonym for 'uninstall'
.arg(Arg::with_name("toolchain").setting(ArgSettings::Required)),
),
)
.subcommand(
App::new("target")
.about("Modify a toolchain's supported targets")
.setting(AppSettings::VersionlessSubcommands)
.setting(AppSettings::DeriveDisplayOrder)
// .setting(AppSettings::SubcommandRequiredElseHelp)
.subcommand(
App::new("list")
.about("List installed and available targets")
.arg(
Arg::with_name("toolchain")
.long("toolchain")
.setting(ArgSettings::TakesValue),
),
)
.subcommand(
App::new("add")
.about("Add a target to a Rust toolchain")
.arg(Arg::with_name("target").setting(ArgSettings::Required))
.arg(
Arg::with_name("toolchain")
.long("toolchain")
.setting(ArgSettings::TakesValue),
),
)
.subcommand(
App::new("remove")
.about("Remove a target from a Rust toolchain")
.arg(Arg::with_name("target").setting(ArgSettings::Required))
.arg(
Arg::with_name("toolchain")
.long("toolchain")
.setting(ArgSettings::TakesValue),
),
)
.subcommand(
App::new("install")
.setting(AppSettings::Hidden) // synonym for 'add'
.arg(Arg::with_name("target").setting(ArgSettings::Required))
.arg(
Arg::with_name("toolchain")
.long("toolchain")
.setting(ArgSettings::TakesValue),
),
)
.subcommand(
App::new("uninstall")
.setting(AppSettings::Hidden) // synonym for 'remove'
.arg(Arg::with_name("target").setting(ArgSettings::Required))
.arg(
Arg::with_name("toolchain")
.long("toolchain")
.setting(ArgSettings::TakesValue),
),
),
)
.subcommand(
App::new("component")
.about("Modify a toolchain's installed components")
.setting(AppSettings::VersionlessSubcommands)
.setting(AppSettings::DeriveDisplayOrder)
// .setting(AppSettings::SubcommandRequiredElseHelp)
.subcommand(
App::new("list")
.about("List installed and available components")
.arg(
Arg::with_name("toolchain")
.long("toolchain")
.setting(ArgSettings::TakesValue),
),
)
.subcommand(
App::new("add")
.about("Add a component to a Rust toolchain")
.arg(Arg::with_name("component").setting(ArgSettings::Required))
.arg(
Arg::with_name("toolchain")
.long("toolchain")
.setting(ArgSettings::TakesValue),
)
.arg(
Arg::with_name("target")
.long("target")
.setting(ArgSettings::TakesValue),
),
)
.subcommand(
App::new("remove")
.about("Remove a component from a Rust toolchain")
.arg(Arg::with_name("component").setting(ArgSettings::Required))
.arg(
Arg::with_name("toolchain")
.long("toolchain")
.setting(ArgSettings::TakesValue),
)
.arg(
Arg::with_name("target")
.long("target")
.setting(ArgSettings::TakesValue),
),
),
)
.subcommand(
App::new("override")
.about("Modify directory toolchain overrides")
.after_help(OVERRIDE_HELP)
.setting(AppSettings::VersionlessSubcommands)
.setting(AppSettings::DeriveDisplayOrder)
// .setting(AppSettings::SubcommandRequiredElseHelp)
.subcommand(App::new("list").about("List directory toolchain overrides"))
.subcommand(
App::new("set")
.about("Set the override toolchain for a directory")
.arg(Arg::with_name("toolchain").setting(ArgSettings::Required)),
)
.subcommand(
App::new("unset")
.about("Remove the override toolchain for a directory")
.after_help(OVERRIDE_UNSET_HELP)
.arg(
Arg::with_name("path")
.long("path")
.setting(ArgSettings::TakesValue)
.help("Path to the directory"),
)
.arg(
Arg::with_name("nonexistent")
.long("nonexistent")
.help("Remove override toolchain for all nonexistent directories"),
),
)
.subcommand(
App::new("add")
.setting(AppSettings::Hidden) // synonym for 'set'
.arg(Arg::with_name("toolchain").setting(ArgSettings::Required)),
)
.subcommand(
App::new("remove")
.setting(AppSettings::Hidden) // synonym for 'unset'
.about("Remove the override toolchain for a directory")
.arg(
Arg::with_name("path")
.long("path")
.setting(ArgSettings::TakesValue),
)
.arg(
Arg::with_name("nonexistent")
.long("nonexistent")
.help("Remove override toolchain for all nonexistent directories"),
),
),
)
.subcommand(
App::new("run")
.about("Run a command with an environment configured for a given toolchain")
.after_help(RUN_HELP)
.setting(AppSettings::TrailingVarArg)
.arg(Arg::with_name("toolchain").setting(ArgSettings::Required))
.arg(Arg::with_name("command").settings(&[
ArgSettings::Required,
ArgSettings::MultipleValues,
ArgSettings::MultipleOccurrences,
])),
)
.subcommand(
App::new("which")
.about("Display which binary will be run for a given command")
.arg(Arg::with_name("command").setting(ArgSettings::Required)),
)
.subcommand(
App::new("doc")
.about("Open the documentation for the current toolchain")
.after_help(DOC_HELP)
.arg(
Arg::with_name("book")
.long("book")
.help("The Rust Programming Language book"),
)
.arg(
Arg::with_name("std")
.long("std")
.help("Standard library API documentation"),
)
.group(ArgGroup::with_name("page").args(&["book", "std"])),
)
.subcommand(
App::new("man")
.about("View the man page for a given command")
.arg(Arg::with_name("command").setting(ArgSettings::Required))
.arg(
Arg::with_name("toolchain")
.long("toolchain")
.setting(ArgSettings::TakesValue),
),
)
.subcommand(
App::new("self")
.about("Modify the rustup installation")
.setting(AppSettings::VersionlessSubcommands)
.setting(AppSettings::DeriveDisplayOrder)
.subcommand(App::new("update").about("Download and install updates to rustup"))
.subcommand(
App::new("uninstall")
.about("Uninstall rustup.")
.arg(Arg::with_name("no-prompt").short('y')),
)
.subcommand(App::new("upgrade-data").about("Upgrade the internal data format.")),
)
.subcommand(
App::new("telemetry")
.about("rustup telemetry commands")
.setting(AppSettings::Hidden)
.setting(AppSettings::VersionlessSubcommands)
.setting(AppSettings::DeriveDisplayOrder)
.subcommand(App::new("enable").about("Enable rustup telemetry"))
.subcommand(App::new("disable").about("Disable rustup telemetry"))
.subcommand(App::new("analyze").about("Analyze stored telemetry")),
)
.subcommand(
App::new("set").about("Alter rustup settings").subcommand(
App::new("default-host")
.about("The triple used to identify toolchains when not specified")
.arg(Arg::with_name("host_triple").setting(ArgSettings::Required)),
),
)
}
static RUSTUP_HELP: &'static str = r"

View file

@ -1,6 +1,6 @@
extern crate clap;
use clap::{App, };
use clap::App;
fn main() {
// This example shows how to create an application with several arguments using usage strings, which can be

View file

@ -1,6 +1,6 @@
extern crate clap;
use clap::{App, Arg, };
use clap::{App, Arg};
fn main() {
// This method shows the traditional, and slightly more configurable way to set up arguments. This method is

View file

@ -42,7 +42,8 @@ fn main() {
(author: "Someone E. <someone_else@other.com>")
(@arg verbose: -v --verbose "Print test information verbosely")
)
).get_matches();
)
.get_matches();
// Calling .unwrap() is safe here because "INPUT" is required (if "INPUT" wasn't
// required we could have used an 'if let' to conditionally get the value)

View file

@ -26,40 +26,38 @@ fn main() {
// safely override "-V" and "-h" to your own arguments, and "--help" and "--version" will still
// be automatically generated for you.
let matches = App::new("MyApp")
// All application settings go here...
// A simple "Flag" argument example (i.e. "-d") using the builder pattern
.arg(Arg::with_name("debug")
.help("turn on debugging information")
.short('d'))
// Two arguments, one "Option" argument (i.e. one that takes a value) such
// as "-c some", and one positional argument (i.e. "myapp some_file")
.args(&[
Arg::with_name("config")
.help("sets the config file to use")
.takes_value(true)
.short('c')
.long("config"),
Arg::with_name("input")
.help("the input file to use")
.index(1)
.required(true)
])
// *Note* the following two examples are convenience methods, if you wish
// to still get the full configurability of Arg::with_name() and the readability
// of arg(), you can instantiate a new Arg with Arg::from() and
// still be able to set all the additional properties, just like Arg::with_name()
//
//
// One "Flag" using a usage string
.arg("--license 'display the license file'")
// Two args, one "Positional", and one "Option" using a usage string
.arg("[output] 'Supply an output file to use'")
.arg("-i, --int=[IFACE] 'Set an interface to use'")
.get_matches();
// All application settings go here...
// A simple "Flag" argument example (i.e. "-d") using the builder pattern
.arg(
Arg::with_name("debug")
.help("turn on debugging information")
.short('d'),
)
// Two arguments, one "Option" argument (i.e. one that takes a value) such
// as "-c some", and one positional argument (i.e. "myapp some_file")
.args(&[
Arg::with_name("config")
.help("sets the config file to use")
.takes_value(true)
.short('c')
.long("config"),
Arg::with_name("input")
.help("the input file to use")
.index(1)
.required(true),
])
// *Note* the following two examples are convenience methods, if you wish
// to still get the full configurability of Arg::with_name() and the readability
// of arg(), you can instantiate a new Arg with Arg::from() and
// still be able to set all the additional properties, just like Arg::with_name()
//
//
// One "Flag" using a usage string
.arg("--license 'display the license file'")
// Two args, one "Positional", and one "Option" using a usage string
.arg("[output] 'Supply an output file to use'")
.arg("-i, --int=[IFACE] 'Set an interface to use'")
.get_matches();
// Here are some examples of using the arguments defined above. Keep in mind that this is only
// an example, and may be somewhat contrived

View file

@ -9,31 +9,31 @@ fn main() {
// clap also supports multiple occurrences of flags, the common example is "verbosity" where a
// user could want a little information with "-v" or tons of information with "-v -v" or "-vv"
let matches = App::new("MyApp")
// Regular App configuration goes here...
// We'll add a flag that represents an awesome meter...
//
// I'll explain each possible setting that "flags" accept. Keep in mind
// that you DO NOT need to set each of these for every flag, only the ones
// you want for your individual case.
.arg(Arg::with_name("awesome")
.help("turns up the awesome") // Displayed when showing help info
.short('a') // Trigger this arg with "-a"
.long("awesome") // Trigger this arg with "--awesome"
.multiple(true) // This flag should allow multiple
// occurrences such as "-aaa" or "-a -a"
.requires("config") // Says, "If the user uses -a, they MUST
// also use this other 'config' arg too"
// Can also specifiy a list using
// requires_all(Vec<&str>)
.conflicts_with("output") // Opposite of requires(), says "if the
// user uses -a, they CANNOT use 'output'"
// also has a conflicts_with_all(Vec<&str>)
)
// NOTE: In order to compile this example, comment out requires() and
// conflicts_with() because we have not defined an "output" or "config"
// argument.
.get_matches();
// Regular App configuration goes here...
// We'll add a flag that represents an awesome meter...
//
// I'll explain each possible setting that "flags" accept. Keep in mind
// that you DO NOT need to set each of these for every flag, only the ones
// you want for your individual case.
.arg(
Arg::with_name("awesome")
.help("turns up the awesome") // Displayed when showing help info
.short('a') // Trigger this arg with "-a"
.long("awesome") // Trigger this arg with "--awesome"
.multiple(true) // This flag should allow multiple
// occurrences such as "-aaa" or "-a -a"
.requires("config") // Says, "If the user uses -a, they MUST
// also use this other 'config' arg too"
// Can also specifiy a list using
// requires_all(Vec<&str>)
.conflicts_with("output"), // Opposite of requires(), says "if the
// user uses -a, they CANNOT use 'output'"
// also has a conflicts_with_all(Vec<&str>)
)
// NOTE: In order to compile this example, comment out requires() and
// conflicts_with() because we have not defined an "output" or "config"
// argument.
.get_matches();
// We can find out whether or not awesome was used
if matches.is_present("awesome") {

View file

@ -7,39 +7,40 @@ fn main() {
// identifier (such as "myapp some_file"). Positionals support many of the same options as
// flags, as well as a few additional ones.
let matches = App::new("MyApp")
// Regular App configuration goes here...
// We'll add two positional arguments, a input file, and a config file.
//
// I'll explain each possible setting that "positionals" accept. Keep in
// mind that you DO NOT need to set each of these for every flag, only the
// ones that apply to your individual case.
.arg(Arg::with_name("input")
.help("the input file to use") // Displayed when showing help info
.index(1) // Set the order in which the user must
// specify this argument (Starts at 1)
.requires("config") // Says, "If the user uses "input", they MUST
// also use this other 'config' arg too"
// Can also specifiy a list using
// requires_all(Vec<&str>)
.conflicts_with("output") // Opposite of requires(), says "if the
// user uses -a, they CANNOT use 'output'"
// also has a conflicts_with_all(Vec<&str>)
.required(true) // By default this argument MUST be present
// NOTE: mutual exclusions take precedence over
// required arguments
)
.arg(Arg::with_name("config")
.help("the config file to use")
.index(2)) // Note, we do not need to specify required(true)
// if we don't want to, because "input" already
// requires "config"
// Note, we also do not need to specify requires("input")
// because requires lists are automatically two-way
// NOTE: In order to compile this example, comment out conflicts_with()
// because we have not defined an "output" argument.
.get_matches();
// Regular App configuration goes here...
// We'll add two positional arguments, a input file, and a config file.
//
// I'll explain each possible setting that "positionals" accept. Keep in
// mind that you DO NOT need to set each of these for every flag, only the
// ones that apply to your individual case.
.arg(
Arg::with_name("input")
.help("the input file to use") // Displayed when showing help info
.index(1) // Set the order in which the user must
// specify this argument (Starts at 1)
.requires("config") // Says, "If the user uses "input", they MUST
// also use this other 'config' arg too"
// Can also specifiy a list using
// requires_all(Vec<&str>)
.conflicts_with("output") // Opposite of requires(), says "if the
// user uses -a, they CANNOT use 'output'"
// also has a conflicts_with_all(Vec<&str>)
.required(true), // By default this argument MUST be present
// NOTE: mutual exclusions take precedence over
// required arguments
)
.arg(
Arg::with_name("config")
.help("the config file to use")
.index(2),
) // Note, we do not need to specify required(true)
// if we don't want to, because "input" already
// requires "config"
// Note, we also do not need to specify requires("input")
// because requires lists are automatically two-way
// NOTE: In order to compile this example, comment out conflicts_with()
// because we have not defined an "output" argument.
.get_matches();
// We can find out whether or not "input" or "config" were used
if matches.is_present("input") {

View file

@ -9,35 +9,35 @@ fn main() {
//
// Options also support a multiple setting, which is discussed in the example below.
let matches = App::new("MyApp")
// Regular App configuration goes here...
// Assume we have an application that accepts an input file via the "-i file"
// or the "--input file" (as well as "--input=file").
// Below every setting supported by option arguments is discussed.
// NOTE: You DO NOT need to specify each setting, only those which apply
// to your particular case.
.arg(Arg::with_name("input")
.help("the input file to use") // Displayed when showing help info
.takes_value(true) // MUST be set to true in order to be an "option" argument
.short('i') // This argument is triggered with "-i"
.long("input") // This argument is triggered with "--input"
.multiple(true) // Set to true if you wish to allow multiple occurrences
// such as "-i file -i other_file -i third_file"
.required(true) // By default this argument MUST be present
// NOTE: mutual exclusions take precedence over
// required arguments
.requires("config") // Says, "If the user uses "input", they MUST
// also use this other 'config' arg too"
// Can also specifiy a list using
// requires_all(Vec<&str>)
.conflicts_with("output") // Opposite of requires(), says "if the
// user uses -a, they CANNOT use 'output'"
// also has a conflicts_with_all(Vec<&str>)
)
// NOTE: In order to compile this example, comment out conflicts_with()
// and requires() because we have not defined an "output" or "config"
// argument.
.get_matches();
// Regular App configuration goes here...
// Assume we have an application that accepts an input file via the "-i file"
// or the "--input file" (as well as "--input=file").
// Below every setting supported by option arguments is discussed.
// NOTE: You DO NOT need to specify each setting, only those which apply
// to your particular case.
.arg(
Arg::with_name("input")
.help("the input file to use") // Displayed when showing help info
.takes_value(true) // MUST be set to true in order to be an "option" argument
.short('i') // This argument is triggered with "-i"
.long("input") // This argument is triggered with "--input"
.multiple(true) // Set to true if you wish to allow multiple occurrences
// such as "-i file -i other_file -i third_file"
.required(true) // By default this argument MUST be present
// NOTE: mutual exclusions take precedence over
// required arguments
.requires("config") // Says, "If the user uses "input", they MUST
// also use this other 'config' arg too"
// Can also specifiy a list using
// requires_all(Vec<&str>)
.conflicts_with("output"), // Opposite of requires(), says "if the
// user uses -a, they CANNOT use 'output'"
// also has a conflicts_with_all(Vec<&str>)
)
// NOTE: In order to compile this example, comment out conflicts_with()
// and requires() because we have not defined an "output" or "config"
// argument.
.get_matches();
// We can find out whether or not "input" was used
if matches.is_present("input") {

View file

@ -1,6 +1,6 @@
extern crate clap;
use clap::{App, Arg, };
use clap::{App, Arg};
fn main() {
// s function exactly like sub-Apps, because that's exactly what they are. Each
@ -18,21 +18,24 @@ fn main() {
// Just like arg() and args(), subcommands can be specified one at a time via subcommand() or
// multiple ones at once with a Vec<> provided to subcommands().
let matches = App::new("MyApp")
// Normal App and Arg configuration goes here...
// In the following example assume we wanted an application which
// supported an "add" subcommand, this "add" subcommand also took
// one positional argument of a file to add:
.subcommand(App::new("add") // The name we call argument with
.about("Adds files to myapp") // The message displayed in "myapp -h"
// or "myapp help"
.version("0.1") // Subcommands can have independent version
.author("Kevin K.") // And authors
.arg(Arg::with_name("input") // And their own arguments
.help("the file to add")
.index(1)
.required(true)))
.get_matches();
// Normal App and Arg configuration goes here...
// In the following example assume we wanted an application which
// supported an "add" subcommand, this "add" subcommand also took
// one positional argument of a file to add:
.subcommand(
App::new("add") // The name we call argument with
.about("Adds files to myapp") // The message displayed in "myapp -h"
// or "myapp help"
.version("0.1") // Subcommands can have independent version
.author("Kevin K.") // And authors
.arg(
Arg::with_name("input") // And their own arguments
.help("the file to add")
.index(1)
.required(true),
),
)
.get_matches();
// You can check if a subcommand was used like normal
if matches.is_present("add") {

View file

@ -20,9 +20,9 @@ fn main() {
// Thanks to https://github.com/jhelwig for pointing this out
App::new("myapp")
.about("does awesome things")
// use crate_version! to pull the version number
.version(crate_version!())
.get_matches();
// use crate_version! to pull the version number
.version(crate_version!())
.get_matches();
// running this app with the -V or --version will display whatever version is in your
// Cargo.toml, the default being: myapp 0.0.1

View file

@ -9,24 +9,28 @@ fn main() {
// I'll demo both here.
//
// First, we'll use clap's Arg::default_value with an "INPUT" file.
let matches = App::new("myapp").about("does awesome things")
.arg(Arg::with_name("INPUT")
.help("The input file to use") // Note, we don't need to specify
// anything like, "Defaults to..."
// because clap will automatically
// generate that for us, and place
// it in the help text
.default_value("input.txt")
.index(1))
// Next we'll use the Option::unwrap_or method on this "CONFIG" option
.arg(Arg::with_name("CONFIG")
// Note that we have to manaully include some verbage to the user
// telling them what the default will be.
.help("The config file to use (default is \"config.json\")")
.short('c')
.takes_value(true))
.get_matches();
let matches = App::new("myapp")
.about("does awesome things")
.arg(
Arg::with_name("INPUT")
.help("The input file to use") // Note, we don't need to specify
// anything like, "Defaults to..."
// because clap will automatically
// generate that for us, and place
// it in the help text
.default_value("input.txt")
.index(1),
)
// Next we'll use the Option::unwrap_or method on this "CONFIG" option
.arg(
Arg::with_name("CONFIG")
// Note that we have to manaully include some verbage to the user
// telling them what the default will be.
.help("The config file to use (default is \"config.json\")")
.short('c')
.takes_value(true),
)
.get_matches();
// It's safe to call unwrap because the value with either be what the user input at runtime
// or "input.txt"

View file

@ -26,11 +26,11 @@ fn main() {
// **NOTE:** to use the macros, you must include #[macro_use] just above the 'extern crate clap;'
// declaration in your crate root.
let matches = App::new("myapp")
// Create two arguments, a required positional which accepts multiple values
// and an optional '-l value'
.arg("<seq>... 'A sequence of whole positive numbers, i.e. 20 25 30'")
.arg("-l [len] 'A length to use, defaults to 10 when omitted'")
.get_matches();
// Create two arguments, a required positional which accepts multiple values
// and an optional '-l value'
.arg("<seq>... 'A sequence of whole positive numbers, i.e. 20 25 30'")
.arg("-l [len] 'A length to use, defaults to 10 when omitted'")
.get_matches();
// Here we get a value of type u32 from our optional -l argument.
// If the value provided to len failes to parse, we default to 10

View file

@ -40,17 +40,18 @@ fn main() {
// Create the application like normal
let enum_vals = ["fast", "slow"];
let m = App::new("myapp")
// Use a single positional argument that is required
.arg(Arg::from("<foo> 'The Foo to use'")
.possible_values(&Foo::variants()))
.arg(Arg::from("<speed> 'The speed to use'")
// You can define a list of possible values if you want the values to be
// displayed in the help information. Whether you use possible_values() or
// not, the valid values will ALWAYS be displayed on a failed parse.
.possible_values(&enum_vals))
// For the second positional, lets not use possible_values() just to show the difference
.arg("<oof> 'The Oof to use'")
.get_matches();
// Use a single positional argument that is required
.arg(Arg::from("<foo> 'The Foo to use'").possible_values(&Foo::variants()))
.arg(
Arg::from("<speed> 'The speed to use'")
// You can define a list of possible values if you want the values to be
// displayed in the help information. Whether you use possible_values() or
// not, the valid values will ALWAYS be displayed on a failed parse.
.possible_values(&enum_vals),
)
// For the second positional, lets not use possible_values() just to show the difference
.arg("<oof> 'The Oof to use'")
.get_matches();
let t = value_t!(m.value_of("foo"), Foo).unwrap_or_else(|e| e.exit());
let t2 = value_t!(m.value_of("oof"), Oof).unwrap_or_else(|e| e.exit());

View file

@ -36,11 +36,13 @@ impl FromStr for Vals {
fn main() {
// Create the application like normal
let m = App::new("myapp")
// Use a single positional argument that is required
.arg(Arg::from("<type> 'The type to use'")
// Define the list of possible values
.possible_values(&["Foo", "Bar", "Baz", "Qux"]))
.get_matches();
// Use a single positional argument that is required
.arg(
Arg::from("<type> 'The type to use'")
// Define the list of possible values
.possible_values(&["Foo", "Bar", "Baz", "Qux"]),
)
.get_matches();
let t = value_t!(m, "type", Vals).unwrap_or_else(|e| e.exit());

View file

@ -27,28 +27,30 @@ use clap::{App, Arg, ArgGroup};
fn main() {
// Create application like normal
let matches = App::new("myapp")
// Add the version arguments
.arg("--set-ver [ver] 'set version manually'")
.arg("--major 'auto inc major'")
.arg("--minor 'auto inc minor'")
.arg("--patch 'auto inc patch'")
// Create a group, make it required, and add the above arguments
.group(ArgGroup::with_name("vers")
.required(true)
.args(&["ver", "major", "minor", "patch"]))
// Arguments can also be added to a group individually, these two arguments
// are part of the "input" group which is not required
.arg(Arg::from("[INPUT_FILE] 'some regular input'")
.group("input"))
.arg(Arg::from("--spec-in [SPEC_IN] 'some special input argument'")
.group("input"))
// Now let's assume we have a -c [config] argument which requires one of
// (but **not** both) the "input" arguments
.arg(Arg::with_name("config")
.short('c')
.takes_value(true)
.requires("input"))
.get_matches();
// Add the version arguments
.arg("--set-ver [ver] 'set version manually'")
.arg("--major 'auto inc major'")
.arg("--minor 'auto inc minor'")
.arg("--patch 'auto inc patch'")
// Create a group, make it required, and add the above arguments
.group(
ArgGroup::with_name("vers")
.required(true)
.args(&["ver", "major", "minor", "patch"]),
)
// Arguments can also be added to a group individually, these two arguments
// are part of the "input" group which is not required
.arg(Arg::from("[INPUT_FILE] 'some regular input'").group("input"))
.arg(Arg::from("--spec-in [SPEC_IN] 'some special input argument'").group("input"))
// Now let's assume we have a -c [config] argument which requires one of
// (but **not** both) the "input" arguments
.arg(
Arg::with_name("config")
.short('c')
.takes_value(true)
.requires("input"),
)
.get_matches();
// Let's assume the old version 1.2.3
let mut major = 1;

View file

@ -8,14 +8,16 @@ fn main() {
// displayed to the user.
let matches = App::new("myapp")
// Application logic goes here...
.arg(Arg::with_name("input")
.help("the input file to use")
.index(1)
.required(true)
// You can pass in a closure, or a function
.validator(is_png))
.get_matches();
// Application logic goes here...
.arg(
Arg::with_name("input")
.help("the input file to use")
.index(1)
.required(true)
// You can pass in a closure, or a function
.validator(is_png),
)
.get_matches();
// Here we can call .unwrap() because the argument is required.
println!("The .PNG file is: {}", matches.value_of("input").unwrap());

View file

@ -1,6 +1,6 @@
extern crate clap;
use clap::{App, AppSettings, };
use clap::{App, AppSettings};
fn main() {
// You can use AppSettings to change the application level behavior of clap. .setting() function
@ -12,20 +12,16 @@ fn main() {
// information.
let matches = App::new("myapp")
.setting(AppSettings::SubcommandsNegateReqs)
// Negates requirement of parent command.
.arg("<input> 'input file to use'")
// Required positional argument called input. This
// will be only required if subcommand is not present.
.subcommand(App::new("test")
.about("does some testing"))
// if program is invoked with subcommand, you do not
// need to specify the <input> argument anymore due to
// the AppSettings::SubcommandsNegateReqs setting.
.get_matches();
.setting(AppSettings::SubcommandsNegateReqs)
// Negates requirement of parent command.
.arg("<input> 'input file to use'")
// Required positional argument called input. This
// will be only required if subcommand is not present.
.subcommand(App::new("test").about("does some testing"))
// if program is invoked with subcommand, you do not
// need to specify the <input> argument anymore due to
// the AppSettings::SubcommandsNegateReqs setting.
.get_matches();
// Calling unwrap() on "input" would not be advised here, because although it's required,
// if the user uses a subcommand, those requirements are no longer required. Hence, we should

View file

@ -6,9 +6,9 @@ use clap::App;
fn main() {
App::new("myapp")
.about("does awesome things")
// use crate_authors! to pull the author(s) names from the Cargo.toml
.author(crate_authors!())
.get_matches();
// use crate_authors! to pull the author(s) names from the Cargo.toml
.author(crate_authors!())
.get_matches();
// running this app with -h will display whatever author(s) are in your
// Cargo.toml

View file

@ -41,7 +41,7 @@
extern crate clap;
use clap::{App, AppSettings, Arg, };
use clap::{App, AppSettings, Arg};
fn main() {
let matches = App::new("git")
@ -60,26 +60,30 @@ fn main() {
.about("pushes things")
.setting(AppSettings::SubcommandRequiredElseHelp)
.subcommand(
App::new("remote") // Subcommands can have thier own subcommands,
// which in turn have their own subcommands
.about("pushes remote things")
.arg(Arg::with_name("repo")
.required(true)
.help("The remote repo to push things to")),
App::new("remote") // Subcommands can have thier own subcommands,
// which in turn have their own subcommands
.about("pushes remote things")
.arg(
Arg::with_name("repo")
.required(true)
.help("The remote repo to push things to"),
),
)
.subcommand(App::new("local").about("pushes local things")),
)
.subcommand(
App::new("add")
.about("adds things")
.author("Someone Else") // Subcommands can list different authors
.version("v2.0 (I'm versioned differently") // or different version from their parents
.setting(AppSettings::ArgRequiredElseHelp) // They can even have different settings
.arg(Arg::with_name("stuff")
.long("stuff")
.help("Stuff to add")
.takes_value(true)
.multiple(true)),
.about("adds things")
.author("Someone Else") // Subcommands can list different authors
.version("v2.0 (I'm versioned differently") // or different version from their parents
.setting(AppSettings::ArgRequiredElseHelp) // They can even have different settings
.arg(
Arg::with_name("stuff")
.long("stuff")
.help("Stuff to add")
.takes_value(true)
.multiple(true),
),
)
.get_matches();

View file

@ -1,6 +1,6 @@
extern crate clap;
use clap::{App, Arg, };
use clap::{App, Arg};
fn main() {
let matches = App::new("MyApp")

View file

@ -1534,7 +1534,12 @@ impl<'a, 'b> App<'a, 'b> {
pub(crate) fn _create_help_and_version(&mut self) {
debugln!("App::_create_help_and_version;");
if !(self.args.args.iter().any(|x| x.long == Some("help") || x.name == "help")) {
if !(self
.args
.args
.iter()
.any(|x| x.long == Some("help") || x.name == "help"))
{
debugln!("App::_create_help_and_version: Building --help");
let mut help = Arg::with_name("help")
.long("help")
@ -1545,7 +1550,11 @@ impl<'a, 'b> App<'a, 'b> {
self.args.push(help);
}
if !(self.args.args.iter().any(|x| x.long == Some("version") || x.name == "version")
if !(self
.args
.args
.iter()
.any(|x| x.long == Some("version") || x.name == "version")
|| self.is_set(AppSettings::DisableVersion))
{
debugln!("App::_create_help_and_version: Building --version");
@ -1602,11 +1611,7 @@ impl<'a, 'b> App<'a, 'b> {
// Long conflicts
if let Some(l) = a.long {
assert!(
self.args
.args
.iter()
.filter(|x| x.long == Some(l))
.count() < 2,
self.args.args.iter().filter(|x| x.long == Some(l)).count() < 2,
"Argument long must be unique\n\n\t--{} is already in use",
l
);
@ -1615,11 +1620,7 @@ impl<'a, 'b> App<'a, 'b> {
// Short conflicts
if let Some(s) = a.short {
assert!(
self.args
.args
.iter()
.filter(|x| x.short == Some(s))
.count() < 2,
self.args.args.iter().filter(|x| x.short == Some(s)).count() < 2,
"Argument short must be unique\n\n\t-{} is already in use",
s
);

View file

@ -59,9 +59,7 @@ impl BitOr for AppFlags {
}
impl Default for AppFlags {
fn default() -> Self {
AppFlags(Flags::UTF8_NONE | Flags::COLOR_AUTO)
}
fn default() -> Self { AppFlags(Flags::UTF8_NONE | Flags::COLOR_AUTO) }
}
#[allow(deprecated)]
@ -708,10 +706,7 @@ pub enum AppSettings {
///
/// assert!(m.subcommand_matches("foo").is_none());
/// ```
#[deprecated(
since = "2.27.0",
note = "No longer required to propagate values"
)]
#[deprecated(since = "2.27.0", note = "No longer required to propagate values")]
PropagateGlobalValuesDown,
/// Allows [``]s to override all requirements of the parent command.

View file

@ -3967,7 +3967,8 @@ impl<'a, 'b> Arg<'a, 'b> {
#[doc(hidden)]
pub fn _build(&mut self) {
if (self.is_set(ArgSettings::UseValueDelimiter)
|| self.is_set(ArgSettings::RequireDelimiter)) && self.val_delim.is_none()
|| self.is_set(ArgSettings::RequireDelimiter))
&& self.val_delim.is_none()
{
self.val_delim = Some(',');
}
@ -4012,7 +4013,8 @@ impl<'a, 'b> Arg<'a, 'b> {
.as_ref()
.map_or(true, |names| names.len() < 2);
if (self.is_set(ArgSettings::MultipleValues)
|| self.is_set(ArgSettings::MultipleOccurrences)) && mult_vals
|| self.is_set(ArgSettings::MultipleOccurrences))
&& mult_vals
{
"..."
} else {

View file

@ -78,7 +78,9 @@ impl<'a> UsageParser<'a> {
.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);
}
@ -127,7 +129,8 @@ impl<'a> UsageParser<'a> {
.usage
.as_bytes()
.get(self.pos)
.expect(INTERNAL_ERROR_MSG) == b'-'
.expect(INTERNAL_ERROR_MSG)
== b'-'
{
self.pos += 1;
self.long(arg);

View file

@ -27,8 +27,7 @@
#[macro_export]
macro_rules! load_yaml {
($yml:expr) => {
&::clap::YamlLoader::load_from_str(include_str!($yml))
.expect("failed to load YAML file")[0]
&::clap::YamlLoader::load_from_str(include_str!($yml)).expect("failed to load YAML file")[0]
};
}
@ -116,7 +115,8 @@ macro_rules! value_t_or_exit {
Err(_) => ::clap::Error::value_validation_auto(format!(
"The argument '{}' isn't a valid value",
v
)).exit(),
))
.exit(),
}
} else {
::clap::Error::argument_not_found_auto($v).exit()
@ -227,9 +227,11 @@ macro_rules! values_t_or_exit {
v.parse::<$t>().unwrap_or_else(|_| {
::clap::Error::value_validation_auto(format!(
"One or more arguments aren't valid values"
)).exit()
))
.exit()
})
}).collect::<Vec<$t>>()
})
.collect::<Vec<$t>>()
} else {
::clap::Error::argument_not_found_auto($v).exit()
}
@ -466,7 +468,7 @@ macro_rules! crate_authors {
struct CargoAuthors {
__private_field: (),
};
impl Deref for CargoAuthors {
type Target = str;
@ -984,15 +986,13 @@ macro_rules! groups_for_arg {
macro_rules! find_subcmd_cloned {
($_self:expr, $sc:expr) => {{
subcommands_cloned!($_self)
.find(|a| match_alias!(a, $sc, &*a.name))
subcommands_cloned!($_self).find(|a| match_alias!(a, $sc, &*a.name))
}};
}
macro_rules! find_subcmd {
($app:expr, $sc:expr) => {{
subcommands!($app)
.find(|a| match_alias!(a, $sc, &*a.name))
subcommands!($app).find(|a| match_alias!(a, $sc, &*a.name))
}};
}

View file

@ -4,7 +4,7 @@ use std::ffi::{OsStr, OsString};
#[derive(PartialEq, Debug, Clone)]
pub struct Key {
pub key: KeyType,
pub index: usize
pub index: usize,
}
#[derive(Default, PartialEq, Debug, Clone)]
@ -46,7 +46,7 @@ impl PartialEq<&str> for KeyType {
fn eq(&self, rhs: &&str) -> bool {
match self {
KeyType::Long(ref l) => l == OsStr::new(rhs),
_ => false
_ => false,
}
}
}
@ -55,7 +55,7 @@ impl PartialEq<char> for KeyType {
fn eq(&self, rhs: &char) -> bool {
match self {
KeyType::Short(c) => c == rhs,
_ => false
_ => false,
}
}
}
@ -65,13 +65,9 @@ impl<'a, 'b> MKeyMap<'a, 'b> {
//TODO ::from(x), ::with_capacity(n) etc
//? set theory ops?
pub fn contains_long(&self, l: &str) -> bool {
self.keys.iter().any(|x| x.key == l)
}
pub fn contains_long(&self, l: &str) -> bool { self.keys.iter().any(|x| x.key == l) }
pub fn contains_short(&self, c: char) -> bool {
self.keys.iter().any(|x| x.key == c)
}
pub fn contains_short(&self, c: char) -> bool { self.keys.iter().any(|x| x.key == c) }
pub fn insert(&mut self, key: KeyType, value: Arg<'a, 'b>) -> usize {
let index = self.push(value);
@ -96,7 +92,7 @@ impl<'a, 'b> MKeyMap<'a, 'b> {
panic!("Index out of bounds");
}
self.keys.push(Key {key, index});
self.keys.push(Key { key, index });
}
//TODO ::insert_keyset([Long, Key2])
@ -123,7 +119,7 @@ impl<'a, 'b> MKeyMap<'a, 'b> {
pub fn is_empty(&self) -> bool { self.keys.is_empty() && self.args.is_empty() }
pub fn remove_key(&mut self, key: KeyType) {
pub fn remove_key(&mut self, key: KeyType) {
let mut idx = None;
for (i, k) in self.keys.iter().enumerate() {
if k.key == key {
@ -140,7 +136,7 @@ impl<'a, 'b> MKeyMap<'a, 'b> {
pub fn insert_key_by_name(&mut self, key: KeyType, name: &str) {
let index = self.find_by_name(name);
self.keys.push(Key {key, index});
self.keys.push(Key { key, index });
}
pub fn _build(&mut self) {
@ -148,7 +144,7 @@ impl<'a, 'b> MKeyMap<'a, 'b> {
for (i, arg) in self.args.iter_mut().enumerate() {
for k in _get_keys(arg) {
self.keys.push(Key {key: k, index: i});
self.keys.push(Key { key: k, index: i });
}
}
}
@ -170,7 +166,8 @@ impl<'a, 'b> MKeyMap<'a, 'b> {
v.iter()
.map(|(n, _)| KeyType::Long(OsString::from(n)))
.collect()
}).unwrap_or(Vec::new());
})
.unwrap_or(Vec::new());
longs.extend(arg.long.map(|l| KeyType::Long(OsString::from(l))));
}

View file

@ -81,11 +81,13 @@ impl<'w> Help<'w> {
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 {
@ -141,7 +143,8 @@ impl<'w> Help<'w> {
parser.app.term_w,
parser.app.max_w,
use_long,
).write_help(parser)
)
.write_help(parser)
}
/// Writes the parser help to the wrapped stream.
@ -744,9 +747,9 @@ impl<'w> Help<'w> {
self.writer.write_all(b"\n\n")?;
}
color!(self, format!("{}:\n", heading), warning)?;
self.write_args(
parser.app.args.args.iter().filter(|a| a.help_heading.is_some() && a.help_heading.unwrap() == heading),
)?;
self.write_args(parser.app.args.args.iter().filter(|a| {
a.help_heading.is_some() && a.help_heading.unwrap() == heading
}))?;
first = false
}
}

View file

@ -81,7 +81,8 @@ impl<'a, 'b, 'c, 'z> Usage<'a, 'b, 'c, 'z> {
if opts!(self.p.app).any(|o| o.is_set(ArgSettings::MultipleValues))
&& positionals!(self.p.app).any(|p| !p.is_set(ArgSettings::Required))
&& !(self.p.app.has_visible_subcommands()
|| self.p.is_set(AS::AllowExternalSubcommands)) && !has_last
|| self.p.is_set(AS::AllowExternalSubcommands))
&& !has_last
{
usage.push_str(" [--]");
}

View file

@ -60,21 +60,23 @@ where
);
return (suffix, Some(candidate.to_owned()));
}
None => for subcommand in subcommands {
subcommand._build(Propagation::NextLevel);
if let Some(ref candidate) = did_you_mean(
arg,
longs!(subcommand).map(|x| x.to_string_lossy().into_owned()),
) {
let suffix = format!(
"\n\tDid you mean to put '{}{}' after the subcommand '{}'?",
Format::Good("--"),
Format::Good(candidate),
Format::Good(subcommand.get_name())
);
return (suffix, Some(candidate.clone()));
None => {
for subcommand in subcommands {
subcommand._build(Propagation::NextLevel);
if let Some(ref candidate) = did_you_mean(
arg,
longs!(subcommand).map(|x| x.to_string_lossy().into_owned()),
) {
let suffix = format!(
"\n\tDid you mean to put '{}{}' after the subcommand '{}'?",
Format::Good("--"),
Format::Good(candidate),
Format::Good(subcommand.get_name())
);
return (suffix, Some(candidate.clone()));
}
}
},
}
}
(String::new(), None)
}

View file

@ -34,4 +34,3 @@ pub struct SubCommand<'a> {
#[doc(hidden)]
pub matches: ArgMatches<'a>,
}

View file

@ -8,6 +8,6 @@ mod validator;
pub use self::arg_matcher::ArgMatcher;
pub use self::matches::ArgMatches;
pub use self::matches::{MatchedArg, OsValues, Values, SubCommand};
pub use self::matches::{MatchedArg, OsValues, SubCommand, Values};
pub use self::parser::{ParseResult, Parser};
pub use self::validator::Validator;

View file

@ -1,8 +1,5 @@
// Std
#[cfg(all(
feature = "debug",
any(target_os = "windows", target_arch = "wasm32")
))]
#[cfg(all(feature = "debug", any(target_os = "windows", target_arch = "wasm32")))]
use osstringext::OsStrExt3;
use std::cell::Cell;
use std::ffi::{OsStr, OsString};
@ -112,7 +109,8 @@ where
} else {
None
}
}).max()
})
.max()
.unwrap_or(&0);
//_highest_idx(&self.positionals);
@ -129,7 +127,8 @@ where
} else {
false
}
}).count();
})
.count();
assert!(
highest_idx == num_p as u64,
@ -326,19 +325,21 @@ where
// Set the LowIndexMultiple flag if required
if positionals!(self.app).any(|a| {
a.is_set(ArgSettings::MultipleValues)
&& (a.index.unwrap_or(0) as usize != self
.app
.args
.keys
.iter()
.map(|x| &x.key)
.filter(|x| {
if let KeyType::Position(_) = x {
true
} else {
false
}
}).count())
&& (a.index.unwrap_or(0) as usize
!= self
.app
.args
.keys
.iter()
.map(|x| &x.key)
.filter(|x| {
if let KeyType::Position(_) = x {
true
} else {
false
}
})
.count())
}) && positionals!(self.app).last().map_or(false, |p_name| {
!self
.app
@ -369,10 +370,7 @@ where
'b: 'c,
{
// The actual parsing function
#[cfg_attr(
feature = "lints",
allow(while_let_on_iterator, collapsible_if)
)]
#[cfg_attr(feature = "lints", allow(while_let_on_iterator, collapsible_if))]
pub fn get_matches_with<I, T>(
&mut self,
matcher: &mut ArgMatcher<'a>,
@ -520,7 +518,8 @@ where
} else {
false
}
}).count();
})
.count();
let is_second_to_last = positional_count > 1 && (pos_counter == (positional_count - 1));
let low_index_mults = self.is_set(AS::LowIndexMultiplePositional) && is_second_to_last;
@ -550,10 +549,10 @@ where
ParseResult::ValuesDone
};
let sc_match = { self.possible_subcommand(&n).0 };
if self.is_new_arg(&n, needs_val_of) || sc_match || suggestions::did_you_mean(
&n.to_string_lossy(),
sc_names!(self.app),
).is_some()
if self.is_new_arg(&n, needs_val_of)
|| sc_match
|| suggestions::did_you_mean(&n.to_string_lossy(), sc_names!(self.app))
.is_some()
{
debugln!("Parser::get_matches_with: Bumping the positional counter...");
pos_counter += 1;
@ -580,7 +579,8 @@ where
} else {
false
}
}).count();
})
.count();
}
if let Some(p) = positionals!(self.app).find(|p| p.index == Some(pos_counter as u64)) {
if p.is_set(ArgSettings::Last) && !self.is_set(AS::TrailingValues) {
@ -592,19 +592,22 @@ where
));
}
if !self.is_set(AS::TrailingValues)
&& (self.is_set(AS::TrailingVarArg) && pos_counter == self
.app
.args
.keys
.iter()
.map(|x| &x.key)
.filter(|x| {
if let KeyType::Position(_) = x {
true
} else {
false
}
}).count())
&& (self.is_set(AS::TrailingVarArg)
&& pos_counter
== self
.app
.args
.keys
.iter()
.map(|x| &x.key)
.filter(|x| {
if let KeyType::Position(_) = x {
true
} else {
false
}
})
.count())
{
self.app.settings.set(AS::TrailingValues);
}
@ -650,7 +653,7 @@ where
sc_m.add_val_to("", &a);
}
matcher.subcommand( SubCommand{
matcher.subcommand(SubCommand {
name: sc_name,
matches: sc_m.into(),
});
@ -922,7 +925,7 @@ where
let name = sc.name.clone();
let mut p = Parser::new(sc);
p.get_matches_with(&mut sc_matcher, it)?;
matcher.subcommand( SubCommand{
matcher.subcommand(SubCommand {
name: name,
matches: sc_matcher.into(),
});
@ -1482,7 +1485,7 @@ where
.map(|x| &x.key)
.filter_map(|x| match x {
KeyType::Long(l) => Some(l.to_string_lossy().into_owned()),
_ => None
_ => None,
})
.collect::<Vec<_>>();
debugln!("Parser::did_you_mean_error: longs={:?}", longs);

View file

@ -11,8 +11,8 @@ use parse::errors::Result as ClapResult;
use parse::errors::{Error, ErrorKind};
use parse::{ArgMatcher, MatchedArg, ParseResult, Parser};
use util::ChildGraph;
use INVALID_UTF8;
use INTERNAL_ERROR_MSG;
use INVALID_UTF8;
pub struct Validator<'a, 'b, 'c, 'z>
where
@ -229,7 +229,8 @@ impl<'a, 'b, 'c, 'z> Validator<'a, 'b, 'c, 'z> {
.unroll_args_in_group(g.name)
.iter()
.filter(|a| matcher.contains(a))
.count() > 1;
.count()
> 1;
let conf_with_arg = if let Some(ref c) = g.conflicts {
c.iter().any(|x| matcher.contains(x))

View file

@ -1,7 +1,7 @@
extern crate clap;
extern crate regex;
use clap::{App, AppSettings, Arg, ErrorKind, Propagation, };
use clap::{App, AppSettings, Arg, ErrorKind, Propagation};
include!("../clap-test.rs");
@ -285,14 +285,13 @@ fn global_setting() {
.global_setting(AppSettings::ColoredHelp)
.subcommand(App::new("subcmd"));
app._propagate(Propagation::NextLevel);
assert!(
app.subcommands
.iter()
.filter(|s| s.name == "subcmd")
.next()
.unwrap()
.is_set(AppSettings::ColoredHelp)
);
assert!(app
.subcommands
.iter()
.filter(|s| s.name == "subcmd")
.next()
.unwrap()
.is_set(AppSettings::ColoredHelp));
}
#[test]
@ -302,22 +301,20 @@ fn global_settings() {
.global_setting(AppSettings::TrailingVarArg)
.subcommand(App::new("subcmd"));
app._propagate(Propagation::NextLevel);
assert!(
app.subcommands
.iter()
.filter(|s| s.name == "subcmd")
.next()
.unwrap()
.is_set(AppSettings::ColoredHelp)
);
assert!(
app.subcommands
.iter()
.filter(|s| s.name == "subcmd")
.next()
.unwrap()
.is_set(AppSettings::TrailingVarArg)
);
assert!(app
.subcommands
.iter()
.filter(|s| s.name == "subcmd")
.next()
.unwrap()
.is_set(AppSettings::ColoredHelp));
assert!(app
.subcommands
.iter()
.filter(|s| s.name == "subcmd")
.next()
.unwrap()
.is_set(AppSettings::TrailingVarArg));
}
#[test]
@ -510,9 +507,15 @@ fn unset_settings() {
assert!(&m.is_set(AppSettings::AllowInvalidUtf8));
assert!(&m.is_set(AppSettings::ColorAuto));
let m = m.unset_setting(AppSettings::AllowInvalidUtf8)
let m = m
.unset_setting(AppSettings::AllowInvalidUtf8)
.unset_setting(AppSettings::ColorAuto);
assert!(!m.is_set(AppSettings::AllowInvalidUtf8), "l: {:?}\ng:{:?}", m.settings, m.g_settings);
assert!(
!m.is_set(AppSettings::AllowInvalidUtf8),
"l: {:?}\ng:{:?}",
m.settings,
m.g_settings
);
assert!(!m.is_set(AppSettings::ColorAuto));
}
@ -566,16 +569,13 @@ fn require_eq() {
#[test]
fn args_negate_subcommands_one_level() {
let res =
App::new("disablehelp")
.setting(AppSettings::ArgsNegateSubcommands)
.setting(AppSettings::SubcommandsNegateReqs)
.arg("<arg1> 'some arg'")
.arg("<arg2> 'some arg'")
.subcommand(App::new("sub1").subcommand(
App::new("sub2").subcommand(App::new("sub3")),
))
.try_get_matches_from(vec!["", "pickles", "sub1"]);
let res = App::new("disablehelp")
.setting(AppSettings::ArgsNegateSubcommands)
.setting(AppSettings::SubcommandsNegateReqs)
.arg("<arg1> 'some arg'")
.arg("<arg2> 'some arg'")
.subcommand(App::new("sub1").subcommand(App::new("sub2").subcommand(App::new("sub3"))))
.try_get_matches_from(vec!["", "pickles", "sub1"]);
assert!(res.is_ok(), "error: {:?}", res.unwrap_err().kind);
let m = res.unwrap();
assert_eq!(m.value_of("arg2"), Some("sub1"));
@ -592,9 +592,7 @@ fn args_negate_subcommands_two_levels() {
App::new("sub1")
.arg("<arg> 'some'")
.arg("<arg2> 'some'")
.subcommand(
App::new("sub2").subcommand(App::new("sub3")),
),
.subcommand(App::new("sub2").subcommand(App::new("sub3"))),
)
.try_get_matches_from(vec!["", "sub1", "arg", "sub2"]);
assert!(res.is_ok(), "error: {:?}", res.unwrap_err().kind);

View file

@ -3,7 +3,7 @@ extern crate regex;
include!("../clap-test.rs");
use clap::{App, Arg, };
use clap::{App, Arg};
static SC_VISIBLE_ALIAS_HELP: &'static str = "ct-test 1.2
Some help

View file

@ -1,7 +1,7 @@
extern crate clap;
extern crate regex;
use clap::{App, Arg, };
use clap::{App, Arg};
include!("../clap-test.rs");

View file

@ -3,7 +3,7 @@ extern crate regex;
use std::str;
use clap::{App, AppSettings, Arg, };
use clap::{App, AppSettings, Arg};
include!("../clap-test.rs");

View file

@ -249,7 +249,8 @@ fn validator_output() {
Arg::from("[arg] 'some opt'")
.env("CLP_TEST_ENV_VO")
.validator(|s| s.parse::<i32>()),
).get_matches_from(vec![""]);
)
.get_matches_from(vec![""]);
assert_eq!(m.value_of("arg").unwrap().parse(), Ok(42));
}

View file

@ -4,7 +4,7 @@ extern crate regex;
#[cfg(test)]
mod tests {
include!("../clap-test.rs");
use clap::{App, Arg, };
use clap::{App, Arg};
fn get_app() -> App<'static, 'static> {
App::new("myprog")

View file

@ -4,7 +4,7 @@ extern crate regex;
include!("../clap-test.rs");
use clap::{App, AppSettings, Arg, ArgSettings, ErrorKind, };
use clap::{App, AppSettings, Arg, ArgSettings, ErrorKind};
static REQUIRE_DELIM_HELP: &'static str = "test 1.3
Kevin K.
@ -603,30 +603,35 @@ fn args_with_last_usage() {
.short('v')
.long("verbose")
.setting(ArgSettings::MultipleOccurrences),
).arg(
)
.arg(
Arg::with_name("timeout")
.help("Timeout in seconds.")
.short('t')
.long("timeout")
.value_name("SECONDS"),
).arg(
)
.arg(
Arg::with_name("frequency")
.help("The sampling frequency.")
.short('f')
.long("frequency")
.value_name("HERTZ"),
).arg(
)
.arg(
Arg::with_name("binary path")
.help("The path of the binary to be profiled. for a binary.")
.value_name("BINFILE"),
).arg(
)
.arg(
Arg::with_name("pass through args")
.help("Any arguments you wish to pass to the being profiled.")
.settings(&[
ArgSettings::MultipleValues,
ArgSettings::MultipleOccurrences,
ArgSettings::Last,
]).value_name("ARGS"),
])
.value_name("ARGS"),
);
assert!(test::compare_output(
app,
@ -694,7 +699,7 @@ fn multi_level_sc_help() {
.author("Kevin K. <kbknapp@gmail.com>")
.version("0.1")
.arg("-f, --flag 'tests flags'")
.arg("-o, --option [scoption]... 'tests options'")
.arg("-o, --option [scoption]... 'tests options'"),
),
);
assert!(test::compare_output(
@ -707,7 +712,9 @@ fn multi_level_sc_help() {
#[test]
fn no_wrap_help() {
let app = App::new("ctest").set_term_width(0).override_help(MULTI_SC_HELP);
let app = App::new("ctest")
.set_term_width(0)
.override_help(MULTI_SC_HELP);
assert!(test::compare_output(
app,
"ctest --help",
@ -752,7 +759,8 @@ fn issue_626_unicode_cutoff() {
beverages. Some coffeehouses also serve cold beverages such as \
iced coffee and iced tea. Many cafés also serve some type of \
food, such as light snacks, muffins, or pastries.",
).takes_value(true),
)
.takes_value(true),
);
assert!(test::compare_output(
app,
@ -774,7 +782,8 @@ fn hide_possible_vals() {
.possible_values(&["fast", "slow"])
.help("Some vals")
.takes_value(true),
).arg(
)
.arg(
Arg::with_name("cafe")
.short('c')
.long("cafe")
@ -927,13 +936,15 @@ fn issue_702_multiple_values() {
.short('s')
.long("some")
.takes_value(true),
).arg(
)
.arg(
Arg::with_name("other")
.help("some other option")
.short('o')
.long("other")
.takes_value(true),
).arg(
)
.arg(
Arg::with_name("label")
.help("a label")
.short('l')
@ -952,7 +963,8 @@ fn long_about() {
.about("bar")
.long_about(
"something really really long, with\nmultiple lines of text\nthat should be displayed",
).arg(Arg::with_name("arg1").help("some option"));
)
.arg(Arg::with_name("arg1").help("some option"));
assert!(test::compare_output(app, "myapp --help", LONG_ABOUT, false));
}
@ -968,7 +980,8 @@ fn issue_760() {
.takes_value(true)
.multiple(true)
.number_of_values(1),
).arg(
)
.arg(
Arg::with_name("opt")
.help("tests options")
.short('O')
@ -1089,8 +1102,14 @@ fn customize_version_and_help() {
.version("0.1")
.author("Nobody <odysseus@example.com>")
.about("You can customize the version and help text")
.mut_arg("help", |h| h.short('H').long("help").help("Print help information"))
.mut_arg("version", |v| v.short('v').long("version").help("Print version information"));
.mut_arg("help", |h| {
h.short('H').long("help").help("Print help information")
})
.mut_arg("version", |v| {
v.short('v')
.long("version")
.help("Print version information")
});
assert!(test::compare_output(
app,
"customize --help",
@ -1236,12 +1255,11 @@ fn issue_1112_override_help_subcmd_long() {
let m = issue_1112_setup().try_get_matches_from(vec!["test", "foo", "--help"]);
assert!(m.is_ok());
assert!(
m.unwrap()
.subcommand_matches("foo")
.unwrap()
.is_present("help")
);
assert!(m
.unwrap()
.subcommand_matches("foo")
.unwrap()
.is_present("help"));
}
#[test]
@ -1249,12 +1267,11 @@ fn issue_1112_override_help_subcmd_short() {
let m = issue_1112_setup().try_get_matches_from(vec!["test", "foo", "-h"]);
assert!(m.is_ok());
assert!(
m.unwrap()
.subcommand_matches("foo")
.unwrap()
.is_present("help")
);
assert!(m
.unwrap()
.subcommand_matches("foo")
.unwrap()
.is_present("help"));
}
#[test]
@ -1292,7 +1309,8 @@ fn hide_env_vals() {
.possible_values(&["fast", "slow"])
.help("Some vals")
.takes_value(true),
).arg(
)
.arg(
Arg::with_name("cafe")
.short('c')
.long("cafe")
@ -1325,7 +1343,8 @@ fn show_env_vals() {
.possible_values(&["fast", "slow"])
.help("Some vals")
.takes_value(true),
).arg(
)
.arg(
Arg::with_name("cafe")
.short('c')
.long("cafe")
@ -1353,7 +1372,8 @@ fn custom_headers_headers() {
Arg::from("-f, --fake <some> <val> 'some help'")
.require_delimiter(true)
.value_delimiter(":"),
).help_heading("NETWORKING")
)
.help_heading("NETWORKING")
.arg(
Arg::with_name("no-proxy")
.short('n')
@ -1400,16 +1420,19 @@ fn multiple_custom_help_headers() {
Arg::from("-f, --fake <some> <val> 'some help'")
.require_delimiter(true)
.value_delimiter(":"),
).help_heading("NETWORKING")
)
.help_heading("NETWORKING")
.arg(
Arg::with_name("no-proxy")
.short('n')
.long("no-proxy")
.help("Do not use system proxy settings"),
).help_heading("SPECIAL")
)
.help_heading("SPECIAL")
.arg(Arg::from(
"-b, --birthday-song <song> 'Change which song is played for birthdays'",
)).stop_custom_headings()
))
.stop_custom_headings()
.arg(
Arg::with_name("speed")
.long("speed")

View file

@ -1,6 +1,6 @@
extern crate clap;
use clap::{App, Arg, ErrorKind, };
use clap::{App, Arg, ErrorKind};
#[test]
fn option_long() {

View file

@ -200,12 +200,11 @@ fn case_insensitive() {
.try_get_matches_from(vec!["pv", "--option", "TeSt123"]);
assert!(m.is_ok());
assert!(
m.unwrap()
.value_of("option")
.unwrap()
.eq_ignore_ascii_case("test123")
);
assert!(m
.unwrap()
.value_of("option")
.unwrap()
.eq_ignore_ascii_case("test123"));
}
#[test]

View file

@ -4,7 +4,7 @@ extern crate regex;
#[cfg(test)]
mod tests {
include!("../clap-test.rs");
use clap::{App, Arg, ArgMatches, ArgSettings, };
use clap::{App, Arg, ArgMatches, ArgSettings};
fn get_app() -> App<'static, 'static> {
App::new("myprog")

View file

@ -3,7 +3,7 @@ extern crate regex;
include!("../clap-test.rs");
use clap::{App, Arg, ErrorKind, };
use clap::{App, Arg, ErrorKind};
static VISIBLE_ALIAS_HELP: &'static str = "clap-test 2.6
@ -63,7 +63,8 @@ fn subcommand() {
.takes_value(true)
.help("testing testing"),
),
).arg(Arg::with_name("other").long("other"))
)
.arg(Arg::with_name("other").long("other"))
.get_matches_from(vec!["myprog", "some", "--test", "testing"]);
assert_eq!(m.subcommand_name().unwrap(), "some");
@ -83,7 +84,8 @@ fn subcommand_none_given() {
.takes_value(true)
.help("testing testing"),
),
).arg(Arg::with_name("other").long("other"))
)
.arg(Arg::with_name("other").long("other"))
.get_matches_from(vec![""]);
assert!(m.subcommand_name().is_none());
@ -139,9 +141,8 @@ fn subcmd_did_you_mean_output() {
#[test]
#[cfg(feature = "suggestions")]
fn subcmd_did_you_mean_output_arg() {
let app = App::new("dym").subcommand(
App::new("subcmd").arg("-s --subcmdarg [subcmdarg] 'tests'"),
);
let app =
App::new("dym").subcommand(App::new("subcmd").arg("-s --subcmdarg [subcmdarg] 'tests'"));
assert!(test::compare_output(app, "dym --subcm foo", DYM_ARG, true));
}
@ -173,11 +174,9 @@ fn visible_aliases_help_output() {
#[test]
fn invisible_aliases_help_output() {
let app = App::new("clap-test").version("2.6").subcommand(
App::new("test")
.about("Some help")
.alias("invisible"),
);
let app = App::new("clap-test")
.version("2.6")
.subcommand(App::new("test").about("Some help").alias("invisible"));
assert!(test::compare_output(
app,
"clap-test --help",

View file

@ -1,7 +1,7 @@
extern crate clap;
extern crate regex;
use clap::{App, };
use clap::App;
include!("../clap-test.rs");

View file

@ -106,7 +106,8 @@ pub fn check_complex_output(args: &str, out: &str) {
"option present {} times with value: {}",
matches.occurrences_of("option"),
v
).unwrap();
)
.unwrap();
}
if let Some(ov) = matches.values_of("option") {
for o in ov {
@ -129,24 +130,28 @@ pub fn check_complex_output(args: &str, out: &str) {
w,
"option2 present with value of: {}",
matches.value_of("long-option-2").unwrap()
).unwrap();
)
.unwrap();
writeln!(
w,
"positional2 present with value of: {}",
matches.value_of("positional2").unwrap()
).unwrap();
)
.unwrap();
} else {
writeln!(w, "flag2 NOT present").unwrap();
writeln!(
w,
"option2 maybe present with value of: {}",
matches.value_of("long-option-2").unwrap_or("Nothing")
).unwrap();
)
.unwrap();
writeln!(
w,
"positional2 maybe present with value of: {}",
matches.value_of("positional2").unwrap_or("Nothing")
).unwrap();
)
.unwrap();
}
let _ = match matches.value_of("Option3").unwrap_or("") {
@ -168,7 +173,8 @@ pub fn check_complex_output(args: &str, out: &str) {
"option present {} times with value: {}",
matches.occurrences_of("option"),
v
).unwrap();
)
.unwrap();
}
if let Some(ov) = matches.values_of("option") {
for o in ov {

View file

@ -3,7 +3,7 @@ extern crate regex;
use std::str;
use clap::{App, Arg, ErrorKind, AppSettings};
use clap::{App, AppSettings, Arg, ErrorKind};
include!("../clap-test.rs");
@ -51,7 +51,9 @@ fn override_ver() {
.author("Kevin K.")
.about("tests stuff")
.version("1.3")
.mut_arg("version", |a| a.short('v').long("version").help("some version"))
.mut_arg("version", |a| {
a.short('v').long("version").help("some version")
})
.try_get_matches_from(vec!["test", "--version"]);
assert!(m.is_ok(), "{:?}", m.unwrap_err().kind);