Merge pull request #3472 from epage/cmd

fix: Rename App to Command
This commit is contained in:
Ed Page 2022-02-15 07:55:36 -06:00 committed by GitHub
commit 7aa45667f5
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
141 changed files with 3678 additions and 3631 deletions

View file

@ -119,7 +119,7 @@ Why use the procedural [Builder API](https://github.com/clap-rs/clap/blob/v3.0.1
- [wild](https://crates.io/crates/wild) for supporting wildcards (`*`) on Windows like you do Linux
- [argfile](https://crates.io/crates/argfile) for loading additional arguments from a file (aka response files)
- [shadow-rs](https://crates.io/crates/shadow-rs) for generating `App::long_version`
- [shadow-rs](https://crates.io/crates/shadow-rs) for generating `Command::long_version`
- [clap_mangen](https://crates.io/crates/clap_mangen) for generating man page source (roff)
- [clap_complete](https://crates.io/crates/clap_complete) for shell completion support
- [clap-verbosity-flag](https://crates.io/crates/clap-verbosity-flag)
@ -150,8 +150,8 @@ Why use the procedural [Builder API](https://github.com/clap-rs/clap/blob/v3.0.1
**Warning:** These may contain breaking changes between minor releases.
* **unstable-replace**: Enable [`App::replace`](https://github.com/clap-rs/clap/issues/2836)
* **unstable-multicall**: Enable [`App::multicall`](https://github.com/clap-rs/clap/issues/2861)
* **unstable-replace**: Enable [`Command::replace`](https://github.com/clap-rs/clap/issues/2836)
* **unstable-multicall**: Enable [`Command::multicall`](https://github.com/clap-rs/clap/issues/2861)
* **unstable-grouped**: Enable [`ArgMatches::grouped_values_of`](https://github.com/clap-rs/clap/issues/2924)
## Sponsors

View file

@ -1,13 +1,13 @@
use clap::App;
use clap::Command;
use criterion::{criterion_group, criterion_main, Criterion};
pub fn build_empty(c: &mut Criterion) {
c.bench_function("build_empty", |b| b.iter(|| App::new("claptests")));
c.bench_function("build_empty", |b| b.iter(|| Command::new("claptests")));
}
pub fn parse_empty(c: &mut Criterion) {
c.bench_function("parse_empty", |b| {
b.iter(|| App::new("claptests").get_matches_from(vec![""]))
b.iter(|| Command::new("claptests").get_matches_from(vec![""]))
});
}

View file

@ -1,9 +1,9 @@
use clap::{arg, App, Arg};
use clap::{arg, Arg, Command};
use criterion::{criterion_group, criterion_main, Criterion};
macro_rules! create_app {
() => {{
App::new("claptests")
Command::new("claptests")
.version("0.1")
.about("tests clap library")
.author("Kevin K. <kbknapp@gmail.com>")
@ -19,7 +19,7 @@ pub fn build_simple(c: &mut Criterion) {
pub fn build_with_flag(c: &mut Criterion) {
c.bench_function("build_with_flag", |b| {
b.iter(|| App::new("claptests").arg(arg!(-s --some "something")))
b.iter(|| Command::new("claptests").arg(arg!(-s --some "something")))
});
}
@ -27,14 +27,14 @@ pub fn build_with_flag_ref(c: &mut Criterion) {
c.bench_function("build_with_flag_ref", |b| {
b.iter(|| {
let arg = arg!(-s --some "something");
App::new("claptests").arg(&arg)
Command::new("claptests").arg(&arg)
})
});
}
pub fn build_with_opt(c: &mut Criterion) {
c.bench_function("build_with_opt", |b| {
b.iter(|| App::new("claptests").arg(arg!(-s --some <FILE> "something")))
b.iter(|| Command::new("claptests").arg(arg!(-s --some <FILE> "something")))
});
}
@ -42,14 +42,14 @@ pub fn build_with_opt_ref(c: &mut Criterion) {
c.bench_function("build_with_opt_ref", |b| {
b.iter(|| {
let arg = arg!(-s --some <FILE> "something");
App::new("claptests").arg(&arg)
Command::new("claptests").arg(&arg)
})
});
}
pub fn build_with_pos(c: &mut Criterion) {
c.bench_function("build_with_pos", |b| {
b.iter(|| App::new("claptests").arg(Arg::new("some")))
b.iter(|| Command::new("claptests").arg(Arg::new("some")))
});
}
@ -57,7 +57,7 @@ pub fn build_with_pos_ref(c: &mut Criterion) {
c.bench_function("build_with_pos_ref", |b| {
b.iter(|| {
let arg = Arg::new("some");
App::new("claptests").arg(&arg)
Command::new("claptests").arg(&arg)
})
});
}

View file

@ -1,4 +1,4 @@
use clap::{arg, App, Arg};
use clap::{arg, Arg, Command};
use criterion::{criterion_group, criterion_main, Criterion};
static OPT3_VALS: [&str; 2] = ["fast", "slow"];
@ -6,7 +6,7 @@ static POS3_VALS: [&str; 2] = ["vi", "emacs"];
macro_rules! create_app {
() => {{
App::new("claptests")
Command::new("claptests")
.version("0.1")
.about("tests clap library")
.author("Kevin K. <kbknapp@gmail.com>")
@ -35,7 +35,7 @@ macro_rules! create_app {
arg!(--maxvals3 <maxvals> ... "Tests 3 max vals").max_values(3).multiple_values(true).required(false),
])
.subcommand(
App::new("subcmd")
Command::new("subcmd")
.about("tests subcommands")
.version("0.1")
.author("Kevin K. <kbknapp@gmail.com>")
@ -48,7 +48,7 @@ macro_rules! create_app {
pub fn build_from_builder(c: &mut Criterion) {
c.bench_function("build_from_builder", |b| {
b.iter(|| {
App::new("claptests")
Command::new("claptests")
.version("0.1")
.about("tests clap library")
.author("Kevin K. <kbknapp@gmail.com>")
@ -141,7 +141,7 @@ pub fn build_from_builder(c: &mut Criterion) {
.max_values(3),
)
.subcommand(
App::new("subcmd")
Command::new("subcmd")
.about("tests subcommands")
.version("0.1")
.author("Kevin K. <kbknapp@gmail.com>")

View file

@ -1,17 +1,17 @@
use clap::App;
use clap::Command;
use clap::{arg, Arg};
use criterion::{criterion_group, criterion_main, Criterion};
use std::io::Cursor;
fn build_help(app: &mut App) -> String {
fn build_help(cmd: &mut Command) -> String {
let mut buf = Cursor::new(Vec::with_capacity(50));
app.write_help(&mut buf).unwrap();
cmd.write_help(&mut buf).unwrap();
let content = buf.into_inner();
String::from_utf8(content).unwrap()
}
fn app_example1<'c>() -> App<'c> {
App::new("MyApp")
fn app_example1<'c>() -> Command<'c> {
Command::new("MyApp")
.version("1.0")
.author("Kevin K. <kbknapp@gmail.com>")
.about("Does awesome things")
@ -24,21 +24,21 @@ fn app_example1<'c>() -> App<'c> {
.arg(arg!(<output> "Sets an optional output file"))
.arg(arg!(d: -d ... "Turn debugging information on"))
.subcommand(
App::new("test")
Command::new("test")
.about("does testing things")
.arg(arg!(-l --list "lists test values")),
)
}
fn app_example2<'c>() -> App<'c> {
App::new("MyApp")
fn app_example2<'c>() -> Command<'c> {
Command::new("MyApp")
.version("1.0")
.author("Kevin K. <kbknapp@gmail.com>")
.about("Does awesome things")
}
fn app_example3<'c>() -> App<'c> {
App::new("MyApp")
fn app_example3<'c>() -> Command<'c> {
Command::new("MyApp")
.arg(
Arg::new("debug")
.help("turn on debugging information")
@ -64,8 +64,8 @@ fn app_example3<'c>() -> App<'c> {
)
}
fn app_example4<'c>() -> App<'c> {
App::new("MyApp")
fn app_example4<'c>() -> Command<'c> {
Command::new("MyApp")
.about("Parses an input file to do awesome things")
.version("1.0")
.author("Kevin K. <kbknapp@gmail.com>")
@ -89,8 +89,8 @@ fn app_example4<'c>() -> App<'c> {
)
}
fn app_example5<'c>() -> App<'c> {
App::new("MyApp").arg(
fn app_example5<'c>() -> Command<'c> {
Command::new("MyApp").arg(
Arg::new("awesome")
.help("turns up the awesome")
.short('a')
@ -99,8 +99,8 @@ fn app_example5<'c>() -> App<'c> {
)
}
fn app_example6<'c>() -> App<'c> {
App::new("MyApp")
fn app_example6<'c>() -> Command<'c> {
Command::new("MyApp")
.arg(
Arg::new("input")
.help("the input file to use")
@ -111,8 +111,8 @@ fn app_example6<'c>() -> App<'c> {
.arg(Arg::new("config").help("the config file to use").index(2))
}
fn app_example7<'c>() -> App<'c> {
App::new("MyApp")
fn app_example7<'c>() -> Command<'c> {
Command::new("MyApp")
.arg(Arg::new("config"))
.arg(Arg::new("output"))
.arg(
@ -129,8 +129,8 @@ fn app_example7<'c>() -> App<'c> {
)
}
fn app_example8<'c>() -> App<'c> {
App::new("MyApp")
fn app_example8<'c>() -> Command<'c> {
Command::new("MyApp")
.arg(Arg::new("config"))
.arg(Arg::new("output"))
.arg(
@ -147,8 +147,8 @@ fn app_example8<'c>() -> App<'c> {
)
}
fn app_example10<'c>() -> App<'c> {
App::new("myapp").about("does awesome things").arg(
fn app_example10<'c>() -> Command<'c> {
Command::new("myapp").about("does awesome things").arg(
Arg::new("CONFIG")
.help("The config file to use (default is \"config.json\")")
.short('c')
@ -157,53 +157,53 @@ fn app_example10<'c>() -> App<'c> {
}
pub fn example1(c: &mut Criterion) {
let mut app = app_example1();
c.bench_function("example1", |b| b.iter(|| build_help(&mut app)));
let mut cmd = app_example1();
c.bench_function("example1", |b| b.iter(|| build_help(&mut cmd)));
}
pub fn example2(c: &mut Criterion) {
let mut app = app_example2();
c.bench_function("example2", |b| b.iter(|| build_help(&mut app)));
let mut cmd = app_example2();
c.bench_function("example2", |b| b.iter(|| build_help(&mut cmd)));
}
pub fn example3(c: &mut Criterion) {
let mut app = app_example3();
c.bench_function("example3", |b| b.iter(|| build_help(&mut app)));
let mut cmd = app_example3();
c.bench_function("example3", |b| b.iter(|| build_help(&mut cmd)));
}
pub fn example4(c: &mut Criterion) {
let mut app = app_example4();
c.bench_function("example4", |b| b.iter(|| build_help(&mut app)));
let mut cmd = app_example4();
c.bench_function("example4", |b| b.iter(|| build_help(&mut cmd)));
}
pub fn example5(c: &mut Criterion) {
let mut app = app_example5();
c.bench_function("example5", |b| b.iter(|| build_help(&mut app)));
let mut cmd = app_example5();
c.bench_function("example5", |b| b.iter(|| build_help(&mut cmd)));
}
pub fn example6(c: &mut Criterion) {
let mut app = app_example6();
c.bench_function("example6", |b| b.iter(|| build_help(&mut app)));
let mut cmd = app_example6();
c.bench_function("example6", |b| b.iter(|| build_help(&mut cmd)));
}
pub fn example7(c: &mut Criterion) {
let mut app = app_example7();
c.bench_function("example7", |b| b.iter(|| build_help(&mut app)));
let mut cmd = app_example7();
c.bench_function("example7", |b| b.iter(|| build_help(&mut cmd)));
}
pub fn example8(c: &mut Criterion) {
let mut app = app_example8();
c.bench_function("example8", |b| b.iter(|| build_help(&mut app)));
let mut cmd = app_example8();
c.bench_function("example8", |b| b.iter(|| build_help(&mut cmd)));
}
pub fn example10(c: &mut Criterion) {
let mut app = app_example10();
c.bench_function("example10", |b| b.iter(|| build_help(&mut app)));
let mut cmd = app_example10();
c.bench_function("example10", |b| b.iter(|| build_help(&mut cmd)));
}
pub fn example4_template(c: &mut Criterion) {
let mut app = app_example4().help_template("{bin} {version}\n{author}\n{about}\n\nUSAGE:\n {usage}\n\nOPTIONS:\n{options}\n\nARGS:\n{args}\n");
c.bench_function("example4_template", |b| b.iter(|| build_help(&mut app)));
let mut cmd = app_example4().help_template("{bin} {version}\n{author}\n{about}\n\nUSAGE:\n {usage}\n\nOPTIONS:\n{options}\n\nARGS:\n{args}\n");
c.bench_function("example4_template", |b| b.iter(|| build_help(&mut cmd)));
}
criterion_group!(

View file

@ -3,7 +3,7 @@
//
// CLI used is adapted from ripgrep 48a8a3a691220f9e5b2b08f4051abe8655ea7e8a
use clap::{App, Arg};
use clap::{Arg, Command};
use criterion::{criterion_group, criterion_main, Criterion};
use std::collections::HashMap;
use std::io::Cursor;
@ -19,13 +19,13 @@ pub fn build_rg_with_long_help(c: &mut Criterion) {
}
pub fn write_rg_short_help(c: &mut Criterion) {
let mut app = app_short();
c.bench_function("write_rg_short_help", |b| b.iter(|| build_help(&mut app)));
let mut cmd = app_short();
c.bench_function("write_rg_short_help", |b| b.iter(|| build_help(&mut cmd)));
}
pub fn write_rg_long_help(c: &mut Criterion) {
let mut app = app_long();
c.bench_function("write_rg_long_help", |b| b.iter(|| build_help(&mut app)));
let mut cmd = app_long();
c.bench_function("write_rg_long_help", |b| b.iter(|| build_help(&mut cmd)));
}
pub fn parse_rg(c: &mut Criterion) {
@ -270,19 +270,19 @@ OPTIONS:
{options}";
/// Build a clap application with short help strings.
fn app_short() -> App<'static> {
app(false, |k| USAGES[k].short)
fn app_short() -> Command<'static> {
cmd(false, |k| USAGES[k].short)
}
/// Build a clap application with long help strings.
fn app_long() -> App<'static> {
app(true, |k| USAGES[k].long)
fn app_long() -> Command<'static> {
cmd(true, |k| USAGES[k].long)
}
/// Build the help text of an application.
fn build_help(app: &mut App) -> String {
fn build_help(cmd: &mut Command) -> String {
let mut buf = Cursor::new(Vec::with_capacity(50));
app.write_help(&mut buf).unwrap();
cmd.write_help(&mut buf).unwrap();
let content = buf.into_inner();
String::from_utf8(content).unwrap()
}
@ -290,18 +290,18 @@ fn build_help(app: &mut App) -> String {
/// Build a clap application parameterized by usage strings.
///
/// The function given should take a clap argument name and return a help
/// string. `app` will panic if a usage string is not defined.
/// string. `cmd` will panic if a usage string is not defined.
///
/// This is an intentionally stand-alone module so that it can be used easily
/// in a `build.rs` script to build shell completion files.
fn app<F>(_next_line_help: bool, doc: F) -> App<'static>
fn cmd<F>(_next_line_help: bool, doc: F) -> Command<'static>
where
F: Fn(&'static str) -> &'static str,
{
let arg = |name| Arg::new(name).help(doc(name));
let flag = |name| arg(name).long(name);
App::new("ripgrep")
Command::new("ripgrep")
.author("BurntSushi") // simulating since it's only a bench
.version("0.4.0") // Simulating
.about(ABOUT)

View file

@ -2,7 +2,7 @@
//
// CLI used is from rustup 408ed84f0e50511ed44a405dd91365e5da588790
use clap::{App, AppSettings, Arg, ArgGroup};
use clap::{AppSettings, Arg, ArgGroup, Command};
use criterion::{criterion_group, criterion_main, Criterion};
pub fn build_rustup(c: &mut Criterion) {
@ -21,8 +21,8 @@ pub fn parse_rustup_with_sc(c: &mut Criterion) {
});
}
fn build_cli() -> App<'static> {
App::new("rustup")
fn build_cli() -> Command<'static> {
Command::new("rustup")
.version("0.9.0") // Simulating
.about("The Rust toolchain installer")
.after_help(RUSTUP_HELP)
@ -35,19 +35,19 @@ fn build_cli() -> App<'static> {
.long("verbose"),
)
.subcommand(
App::new("show")
Command::new("show")
.about("Show the active and installed toolchains")
.after_help(SHOW_HELP),
)
.subcommand(
App::new("install")
Command::new("install")
.about("Update Rust toolchains")
.after_help(TOOLCHAIN_INSTALL_HELP)
.hide(true) // synonym for 'toolchain install'
.arg(Arg::new("toolchain").required(true)),
)
.subcommand(
App::new("update")
Command::new("update")
.about("Update Rust toolchains")
.after_help(UPDATE_HELP)
.arg(Arg::new("toolchain").required(true))
@ -59,104 +59,104 @@ fn build_cli() -> App<'static> {
),
)
.subcommand(
App::new("default")
Command::new("default")
.about("Set the default toolchain")
.after_help(DEFAULT_HELP)
.arg(Arg::new("toolchain").required(true)),
)
.subcommand(
App::new("toolchain")
Command::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(Command::new("list").about("List installed toolchains"))
.subcommand(
App::new("install")
Command::new("install")
.about("Install or update a given toolchain")
.arg(Arg::new("toolchain").required(true)),
)
.subcommand(
App::new("uninstall")
Command::new("uninstall")
.about("Uninstall a toolchain")
.arg(Arg::new("toolchain").required(true)),
)
.subcommand(
App::new("link")
Command::new("link")
.about("Create a custom toolchain by symlinking to a directory")
.arg(Arg::new("toolchain").required(true))
.arg(Arg::new("path").required(true)),
)
.subcommand(
App::new("update")
Command::new("update")
.hide(true) // synonym for 'install'
.arg(Arg::new("toolchain").required(true)),
)
.subcommand(
App::new("add")
Command::new("add")
.hide(true) // synonym for 'install'
.arg(Arg::new("toolchain").required(true)),
)
.subcommand(
App::new("remove")
Command::new("remove")
.hide(true) // synonym for 'uninstall'
.arg(Arg::new("toolchain").required(true)),
),
)
.subcommand(
App::new("target")
Command::new("target")
.about("Modify a toolchain's supported targets")
.setting(AppSettings::DeriveDisplayOrder)
// .setting(AppSettings::SubcommandRequiredElseHelp)
.subcommand(
App::new("list")
Command::new("list")
.about("List installed and available targets")
.arg(Arg::new("toolchain").long("toolchain").takes_value(true)),
)
.subcommand(
App::new("add")
Command::new("add")
.about("Add a target to a Rust toolchain")
.arg(Arg::new("target").required(true))
.arg(Arg::new("toolchain").long("toolchain").takes_value(true)),
)
.subcommand(
App::new("remove")
Command::new("remove")
.about("Remove a target from a Rust toolchain")
.arg(Arg::new("target").required(true))
.arg(Arg::new("toolchain").long("toolchain").takes_value(true)),
)
.subcommand(
App::new("install")
Command::new("install")
.hide(true) // synonym for 'add'
.arg(Arg::new("target").required(true))
.arg(Arg::new("toolchain").long("toolchain").takes_value(true)),
)
.subcommand(
App::new("uninstall")
Command::new("uninstall")
.hide(true) // synonym for 'remove'
.arg(Arg::new("target").required(true))
.arg(Arg::new("toolchain").long("toolchain").takes_value(true)),
),
)
.subcommand(
App::new("component")
Command::new("component")
.about("Modify a toolchain's installed components")
.setting(AppSettings::DeriveDisplayOrder)
// .setting(AppSettings::SubcommandRequiredElseHelp)
.subcommand(
App::new("list")
Command::new("list")
.about("List installed and available components")
.arg(Arg::new("toolchain").long("toolchain").takes_value(true)),
)
.subcommand(
App::new("add")
Command::new("add")
.about("Add a component to a Rust toolchain")
.arg(Arg::new("component").required(true))
.arg(Arg::new("toolchain").long("toolchain").takes_value(true))
.arg(Arg::new("target").long("target").takes_value(true)),
)
.subcommand(
App::new("remove")
Command::new("remove")
.about("Remove a component from a Rust toolchain")
.arg(Arg::new("component").required(true))
.arg(Arg::new("toolchain").long("toolchain").takes_value(true))
@ -164,19 +164,19 @@ fn build_cli() -> App<'static> {
),
)
.subcommand(
App::new("override")
Command::new("override")
.about("Modify directory toolchain overrides")
.after_help(OVERRIDE_HELP)
.setting(AppSettings::DeriveDisplayOrder)
// .setting(AppSettings::SubcommandRequiredElseHelp)
.subcommand(App::new("list").about("List directory toolchain overrides"))
.subcommand(Command::new("list").about("List directory toolchain overrides"))
.subcommand(
App::new("set")
Command::new("set")
.about("Set the override toolchain for a directory")
.arg(Arg::new("toolchain").required(true)),
)
.subcommand(
App::new("unset")
Command::new("unset")
.about("Remove the override toolchain for a directory")
.after_help(OVERRIDE_UNSET_HELP)
.arg(
@ -192,12 +192,12 @@ fn build_cli() -> App<'static> {
),
)
.subcommand(
App::new("add")
Command::new("add")
.hide(true) // synonym for 'set'
.arg(Arg::new("toolchain").required(true)),
)
.subcommand(
App::new("remove")
Command::new("remove")
.hide(true) // synonym for 'unset'
.about("Remove the override toolchain for a directory")
.arg(Arg::new("path").long("path").takes_value(true))
@ -209,7 +209,7 @@ fn build_cli() -> App<'static> {
),
)
.subcommand(
App::new("run")
Command::new("run")
.about("Run a command with an environment configured for a given toolchain")
.after_help(RUN_HELP)
.trailing_var_arg(true)
@ -223,12 +223,12 @@ fn build_cli() -> App<'static> {
),
)
.subcommand(
App::new("which")
Command::new("which")
.about("Display which binary will be run for a given command")
.arg(Arg::new("command").required(true)),
)
.subcommand(
App::new("doc")
Command::new("doc")
.about("Open the documentation for the current toolchain")
.after_help(DOC_HELP)
.arg(
@ -244,38 +244,42 @@ fn build_cli() -> App<'static> {
.group(ArgGroup::new("page").args(&["book", "std"])),
)
.subcommand(
App::new("man")
Command::new("man")
.about("View the man page for a given command")
.arg(Arg::new("command").required(true))
.arg(Arg::new("toolchain").long("toolchain").takes_value(true)),
)
.subcommand(
App::new("self")
Command::new("self")
.about("Modify the rustup installation")
.setting(AppSettings::DeriveDisplayOrder)
.subcommand(App::new("update").about("Download and install updates to rustup"))
.subcommand(Command::new("update").about("Download and install updates to rustup"))
.subcommand(
App::new("uninstall")
Command::new("uninstall")
.about("Uninstall rustup.")
.arg(Arg::new("no-prompt").short('y')),
)
.subcommand(App::new("upgrade-data").about("Upgrade the internal data format.")),
.subcommand(
Command::new("upgrade-data").about("Upgrade the internal data format."),
),
)
.subcommand(
App::new("telemetry")
Command::new("telemetry")
.about("rustup telemetry commands")
.hide(true)
.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(Command::new("enable").about("Enable rustup telemetry"))
.subcommand(Command::new("disable").about("Disable rustup telemetry"))
.subcommand(Command::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::new("host_triple").required(true)),
),
Command::new("set")
.about("Alter rustup settings")
.subcommand(
Command::new("default-host")
.about("The triple used to identify toolchains when not specified")
.arg(Arg::new("host_triple").required(true)),
),
)
}

View file

@ -8,7 +8,7 @@ include = [
"LICENSE-*",
"README.md"
]
description = "Generate shell completion scripts for your clap::App"
description = "Generate shell completion scripts for your clap::Command"
repository = "https://github.com/clap-rs/clap/tree/master/clap_complete"
documentation = "https://docs.rs/clap_complete"
keywords = [

View file

@ -1,11 +1,11 @@
use clap::App;
use clap::Command;
use clap_complete::{generate, shells::Bash};
use std::io;
fn main() {
let mut app = App::new("myapp")
.subcommand(App::new("test").subcommand(App::new("config")))
.subcommand(App::new("hello"));
let mut cmd = Command::new("myapp")
.subcommand(Command::new("test").subcommand(Command::new("config")))
.subcommand(Command::new("hello"));
generate(Bash, &mut app, "myapp", &mut io::stdout());
generate(Bash, &mut cmd, "myapp", &mut io::stdout());
}

View file

@ -12,12 +12,12 @@
//! . ./value_hints.fish
//! ./target/debug/examples/value_hints --<TAB>
//! ```
use clap::{App, Arg, ValueHint};
use clap::{Arg, Command, ValueHint};
use clap_complete::{generate, Generator, Shell};
use std::io;
fn build_cli() -> App<'static> {
App::new("value_hints")
fn build_cli() -> Command<'static> {
Command::new("value_hints")
// AppSettings::TrailingVarArg is required to use ValueHint::CommandWithArguments
.trailing_var_arg(true)
.arg(
@ -92,16 +92,16 @@ fn build_cli() -> App<'static> {
)
}
fn print_completions<G: Generator>(gen: G, app: &mut App) {
generate(gen, app, app.get_name().to_string(), &mut io::stdout());
fn print_completions<G: Generator>(gen: G, cmd: &mut Command) {
generate(gen, cmd, cmd.get_name().to_string(), &mut io::stdout());
}
fn main() {
let matches = build_cli().get_matches();
if let Ok(generator) = matches.value_of_t::<Shell>("generator") {
let mut app = build_cli();
let mut cmd = build_cli();
eprintln!("Generating completion file for {}...", generator);
print_completions(generator, &mut app);
print_completions(generator, &mut cmd);
}
}

View file

@ -12,7 +12,7 @@
//! . ./value_hints_derive.fish
//! ./target/debug/examples/value_hints_derive --<TAB>
//! ```
use clap::{App, IntoApp, Parser, ValueHint};
use clap::{Command, IntoApp, Parser, ValueHint};
use clap_complete::{generate, Generator, Shell};
use std::ffi::OsString;
use std::io;
@ -21,7 +21,7 @@ use std::path::PathBuf;
#[derive(Parser, Debug, PartialEq)]
#[clap(
name = "value_hints_derive",
// App::trailing_var_ar is required to use ValueHint::CommandWithArguments
// Command::trailing_var_ar is required to use ValueHint::CommandWithArguments
trailing_var_arg = true,
)]
struct Opt {
@ -57,17 +57,17 @@ struct Opt {
email: Option<String>,
}
fn print_completions<G: Generator>(gen: G, app: &mut App) {
generate(gen, app, app.get_name().to_string(), &mut io::stdout());
fn print_completions<G: Generator>(gen: G, cmd: &mut Command) {
generate(gen, cmd, cmd.get_name().to_string(), &mut io::stdout());
}
fn main() {
let opt = Opt::parse();
if let Some(generator) = opt.generator {
let mut app = Opt::into_app();
let mut cmd = Opt::into_app();
eprintln!("Generating completion file for {:?}...", generator);
print_completions(generator, &mut app);
print_completions(generator, &mut cmd);
} else {
println!("{:#?}", opt);
}

View file

@ -8,7 +8,7 @@ use std::io::Error;
use std::io::Write;
use std::path::PathBuf;
use clap::App;
use clap::Command;
/// Generator trait which can be used to write generators
pub trait Generator {
@ -22,13 +22,13 @@ pub trait Generator {
///
/// ```
/// # use std::io::Write;
/// # use clap::App;
/// # use clap::Command;
/// use clap_complete::Generator;
///
/// pub struct Fish;
///
/// impl Generator for Fish {
/// # fn generate(&self, app: &App, buf: &mut dyn Write) {}
/// # fn generate(&self, cmd: &Command, buf: &mut dyn Write) {}
/// fn file_name(&self, name: &str) -> String {
/// format!("{}.fish", name)
/// }
@ -36,7 +36,7 @@ pub trait Generator {
/// ```
fn file_name(&self, name: &str) -> String;
/// Generates output out of [`clap::App`](App).
/// Generates output out of [`clap::Command`](Command).
///
/// # Panics
///
@ -44,26 +44,26 @@ pub trait Generator {
///
/// # Examples
///
/// The following example generator displays the [`clap::App`](App)
/// The following example generator displays the [`clap::Command`](Command)
/// as if it is printed using [`std::println`].
///
/// ```
/// use std::{io::Write, fmt::write};
/// use clap::App;
/// use clap::Command;
/// use clap_complete::Generator;
///
/// pub struct ClapDebug;
///
/// impl Generator for ClapDebug {
/// fn generate(&self, app: &App, buf: &mut dyn Write) {
/// write!(buf, "{}", app).unwrap();
/// fn generate(&self, cmd: &Command, buf: &mut dyn Write) {
/// write!(buf, "{}", cmd).unwrap();
/// }
/// # fn file_name(&self, name: &str) -> String {
/// # name.into()
/// # }
/// }
/// ```
fn generate(&self, app: &App, buf: &mut dyn Write);
fn generate(&self, cmd: &Command, buf: &mut dyn Write);
}
/// Generate a completions file for a specified shell at compile-time.
@ -78,20 +78,20 @@ pub trait Generator {
/// args. Real applications could be many multiple levels deep in subcommands, and have tens or
/// potentially hundreds of arguments.
///
/// First, it helps if we separate out our `App` definition into a separate file. Whether you
/// do this as a function, or bare App definition is a matter of personal preference.
/// First, it helps if we separate out our `Command` definition into a separate file. Whether you
/// do this as a function, or bare Command definition is a matter of personal preference.
///
/// ```
/// // src/cli.rs
///
/// use clap::{App, Arg};
/// use clap::{Command, Arg};
///
/// pub fn build_cli() -> App<'static> {
/// App::new("compl")
/// pub fn build_cli() -> Command<'static> {
/// Command::new("compl")
/// .about("Tests completions")
/// .arg(Arg::new("file")
/// .help("some input file"))
/// .subcommand(App::new("test")
/// .subcommand(Command::new("test")
/// .about("tests things")
/// .arg(Arg::new("case")
/// .long("case")
@ -144,10 +144,10 @@ pub trait Generator {
/// Some(outdir) => outdir,
/// };
///
/// let mut app = build_cli();
/// let mut cmd = build_cli();
/// let path = generate_to(
/// Bash,
/// &mut app, // We need to specify what generator to use
/// &mut cmd, // We need to specify what generator to use
/// "myapp", // We need to specify the bin name manually
/// outdir, // We need to specify where to write to
/// )?;
@ -166,7 +166,7 @@ pub trait Generator {
/// to see the name of the files generated.
pub fn generate_to<G, S, T>(
gen: G,
app: &mut clap::App,
cmd: &mut clap::Command,
bin_name: S,
out_dir: T,
) -> Result<PathBuf, Error>
@ -175,15 +175,15 @@ where
S: Into<String>,
T: Into<OsString>,
{
app.set_bin_name(bin_name);
cmd.set_bin_name(bin_name);
let out_dir = PathBuf::from(out_dir.into());
let file_name = gen.file_name(app.get_bin_name().unwrap());
let file_name = gen.file_name(cmd.get_bin_name().unwrap());
let path = out_dir.join(file_name);
let mut file = File::create(&path)?;
_generate::<G, S>(gen, app, &mut file);
_generate::<G, S>(gen, cmd, &mut file);
Ok(path)
}
@ -222,21 +222,21 @@ where
/// ```shell
/// $ myapp generate-bash-completions > /usr/share/bash-completion/completions/myapp.bash
/// ```
pub fn generate<G, S>(gen: G, app: &mut clap::App, bin_name: S, buf: &mut dyn Write)
pub fn generate<G, S>(gen: G, cmd: &mut clap::Command, bin_name: S, buf: &mut dyn Write)
where
G: Generator,
S: Into<String>,
{
app.set_bin_name(bin_name);
_generate::<G, S>(gen, app, buf)
cmd.set_bin_name(bin_name);
_generate::<G, S>(gen, cmd, buf)
}
fn _generate<G, S>(gen: G, app: &mut clap::App, buf: &mut dyn Write)
fn _generate<G, S>(gen: G, cmd: &mut clap::Command, buf: &mut dyn Write)
where
G: Generator,
S: Into<String>,
{
app._build_all();
cmd._build_all();
gen.generate(app, buf)
gen.generate(cmd, buf)
}

View file

@ -1,42 +1,42 @@
//! Helpers for writing generators
use clap::{App, Arg};
use clap::{Arg, Command};
/// Gets all subcommands including child subcommands in the form of `("name", "bin_name")`.
///
/// Subcommand `rustup toolchain install` would be converted to
/// `("install", "rustup toolchain install")`.
pub fn all_subcommands(app: &App) -> Vec<(String, String)> {
let mut subcmds: Vec<_> = subcommands(app);
pub fn all_subcommands(cmd: &Command) -> Vec<(String, String)> {
let mut subcmds: Vec<_> = subcommands(cmd);
for sc_v in app.get_subcommands().map(all_subcommands) {
for sc_v in cmd.get_subcommands().map(all_subcommands) {
subcmds.extend(sc_v);
}
subcmds
}
/// Finds the subcommand [`clap::App`] from the given [`clap::App`] with the given path.
/// Finds the subcommand [`clap::Command`] from the given [`clap::Command`] with the given path.
///
/// **NOTE:** `path` should not contain the root `bin_name`.
pub fn find_subcommand_with_path<'help, 'app>(
p: &'app App<'help>,
pub fn find_subcommand_with_path<'help, 'cmd>(
p: &'cmd Command<'help>,
path: Vec<&str>,
) -> &'app App<'help> {
let mut app = p;
) -> &'cmd Command<'help> {
let mut cmd = p;
for sc in path {
app = app.find_subcommand(sc).unwrap();
cmd = cmd.find_subcommand(sc).unwrap();
}
app
cmd
}
/// Gets subcommands of [`clap::App`] in the form of `("name", "bin_name")`.
/// Gets subcommands of [`clap::Command`] in the form of `("name", "bin_name")`.
///
/// Subcommand `rustup toolchain install` would be converted to
/// `("install", "rustup toolchain install")`.
pub fn subcommands(p: &App) -> Vec<(String, String)> {
pub fn subcommands(p: &Command) -> Vec<(String, String)> {
debug!("subcommands: name={}", p.get_name());
debug!("subcommands: Has subcommands...{:?}", p.has_subcommands());
@ -61,9 +61,9 @@ pub fn subcommands(p: &App) -> Vec<(String, String)> {
subcmds
}
/// Gets all the short options, their visible aliases and flags of a [`clap::App`].
/// Gets all the short options, their visible aliases and flags of a [`clap::Command`].
/// Includes `h` and `V` depending on the [`clap::AppSettings`].
pub fn shorts_and_visible_aliases(p: &App) -> Vec<char> {
pub fn shorts_and_visible_aliases(p: &Command) -> Vec<char> {
debug!("shorts: name={}", p.get_name());
p.get_arguments()
@ -86,9 +86,9 @@ pub fn shorts_and_visible_aliases(p: &App) -> Vec<char> {
.collect()
}
/// Gets all the long options, their visible aliases and flags of a [`clap::App`].
/// Gets all the long options, their visible aliases and flags of a [`clap::Command`].
/// Includes `help` and `version` depending on the [`clap::AppSettings`].
pub fn longs_and_visible_aliases(p: &App) -> Vec<String> {
pub fn longs_and_visible_aliases(p: &Command) -> Vec<String> {
debug!("longs: name={}", p.get_name());
p.get_arguments()
@ -116,9 +116,9 @@ pub fn longs_and_visible_aliases(p: &App) -> Vec<String> {
.collect()
}
/// Gets all the flags of a [`clap::App`](App).
/// Gets all the flags of a [`clap::Command`](Command).
/// Includes `help` and `version` depending on the [`clap::AppSettings`].
pub fn flags<'help>(p: &App<'help>) -> Vec<Arg<'help>> {
pub fn flags<'help>(p: &Command<'help>) -> Vec<Arg<'help>> {
debug!("flags: name={}", p.get_name());
p.get_arguments()
.filter(|a| !a.is_takes_value_set() && !a.is_positional())
@ -132,10 +132,10 @@ mod tests {
use clap::Arg;
use pretty_assertions::assert_eq;
fn common_app() -> App<'static> {
App::new("myapp")
fn common_app() -> Command<'static> {
Command::new("myapp")
.subcommand(
App::new("test").subcommand(App::new("config")).arg(
Command::new("test").subcommand(Command::new("config")).arg(
Arg::new("file")
.short('f')
.short_alias('c')
@ -144,72 +144,72 @@ mod tests {
.visible_alias("path"),
),
)
.subcommand(App::new("hello"))
.bin_name("my-app")
.subcommand(Command::new("hello"))
.bin_name("my-cmd")
}
fn built() -> App<'static> {
let mut app = common_app();
fn built() -> Command<'static> {
let mut cmd = common_app();
app._build_all();
app
cmd._build_all();
cmd
}
fn built_with_version() -> App<'static> {
let mut app = common_app().version("3.0");
fn built_with_version() -> Command<'static> {
let mut cmd = common_app().version("3.0");
app._build_all();
app
cmd._build_all();
cmd
}
#[test]
fn test_subcommands() {
let app = built_with_version();
let cmd = built_with_version();
assert_eq!(
subcommands(&app),
subcommands(&cmd),
vec![
("test".to_string(), "my-app test".to_string()),
("hello".to_string(), "my-app hello".to_string()),
("help".to_string(), "my-app help".to_string()),
("test".to_string(), "my-cmd test".to_string()),
("hello".to_string(), "my-cmd hello".to_string()),
("help".to_string(), "my-cmd help".to_string()),
]
);
}
#[test]
fn test_all_subcommands() {
let app = built_with_version();
let cmd = built_with_version();
assert_eq!(
all_subcommands(&app),
all_subcommands(&cmd),
vec![
("test".to_string(), "my-app test".to_string()),
("hello".to_string(), "my-app hello".to_string()),
("help".to_string(), "my-app help".to_string()),
("config".to_string(), "my-app test config".to_string()),
("help".to_string(), "my-app test help".to_string()),
("test".to_string(), "my-cmd test".to_string()),
("hello".to_string(), "my-cmd hello".to_string()),
("help".to_string(), "my-cmd help".to_string()),
("config".to_string(), "my-cmd test config".to_string()),
("help".to_string(), "my-cmd test help".to_string()),
]
);
}
#[test]
fn test_find_subcommand_with_path() {
let app = built_with_version();
let sc_app = find_subcommand_with_path(&app, "test config".split(' ').collect());
let cmd = built_with_version();
let sc_app = find_subcommand_with_path(&cmd, "test config".split(' ').collect());
assert_eq!(sc_app.get_name(), "config");
}
#[test]
fn test_flags() {
let app = built_with_version();
let actual_flags = flags(&app);
let cmd = built_with_version();
let actual_flags = flags(&cmd);
assert_eq!(actual_flags.len(), 2);
assert_eq!(actual_flags[0].get_long(), Some("help"));
assert_eq!(actual_flags[1].get_long(), Some("version"));
let sc_flags = flags(find_subcommand_with_path(&app, vec!["test"]));
let sc_flags = flags(find_subcommand_with_path(&cmd, vec!["test"]));
assert_eq!(sc_flags.len(), 2);
assert_eq!(sc_flags[0].get_long(), Some("file"));
@ -218,13 +218,13 @@ mod tests {
#[test]
fn test_flag_subcommand() {
let app = built();
let actual_flags = flags(&app);
let cmd = built();
let actual_flags = flags(&cmd);
assert_eq!(actual_flags.len(), 1);
assert_eq!(actual_flags[0].get_long(), Some("help"));
let sc_flags = flags(find_subcommand_with_path(&app, vec!["test"]));
let sc_flags = flags(find_subcommand_with_path(&cmd, vec!["test"]));
assert_eq!(sc_flags.len(), 2);
assert_eq!(sc_flags[0].get_long(), Some("file"));
@ -233,14 +233,14 @@ mod tests {
#[test]
fn test_shorts() {
let app = built_with_version();
let shorts = shorts_and_visible_aliases(&app);
let cmd = built_with_version();
let shorts = shorts_and_visible_aliases(&cmd);
assert_eq!(shorts.len(), 2);
assert_eq!(shorts[0], 'h');
assert_eq!(shorts[1], 'V');
let sc_shorts = shorts_and_visible_aliases(find_subcommand_with_path(&app, vec!["test"]));
let sc_shorts = shorts_and_visible_aliases(find_subcommand_with_path(&cmd, vec!["test"]));
assert_eq!(sc_shorts.len(), 3);
assert_eq!(sc_shorts[0], 'p');
@ -250,14 +250,14 @@ mod tests {
#[test]
fn test_longs() {
let app = built_with_version();
let longs = longs_and_visible_aliases(&app);
let cmd = built_with_version();
let longs = longs_and_visible_aliases(&cmd);
assert_eq!(longs.len(), 2);
assert_eq!(longs[0], "help");
assert_eq!(longs[1], "version");
let sc_longs = longs_and_visible_aliases(find_subcommand_with_path(&app, vec!["test"]));
let sc_longs = longs_and_visible_aliases(find_subcommand_with_path(&cmd, vec!["test"]));
assert_eq!(sc_longs.len(), 3);
assert_eq!(sc_longs[0], "path");

View file

@ -22,12 +22,12 @@
//! ## Example
//!
//! ```rust,no_run
//! use clap::{App, AppSettings, Arg, ValueHint};
//! use clap::{Command, AppSettings, Arg, ValueHint};
//! use clap_complete::{generate, Generator, Shell};
//! use std::io;
//!
//! fn build_cli() -> App<'static> {
//! App::new("example")
//! fn build_cli() -> Command<'static> {
//! Command::new("example")
//! .arg(Arg::new("file")
//! .help("some input file")
//! .value_hint(ValueHint::AnyPath),
@ -39,17 +39,17 @@
//! )
//! }
//!
//! fn print_completions<G: Generator>(gen: G, app: &mut App) {
//! generate(gen, app, app.get_name().to_string(), &mut io::stdout());
//! fn print_completions<G: Generator>(gen: G, cmd: &mut Command) {
//! generate(gen, cmd, cmd.get_name().to_string(), &mut io::stdout());
//! }
//!
//! fn main() {
//! let matches = build_cli().get_matches();
//!
//! if let Ok(generator) = matches.value_of_t::<Shell>("generator") {
//! let mut app = build_cli();
//! let mut cmd = build_cli();
//! eprintln!("Generating completion file for {}...", generator);
//! print_completions(generator, &mut app);
//! print_completions(generator, &mut cmd);
//! }
//! }
//! ```

View file

@ -13,8 +13,8 @@ impl Generator for Bash {
format!("{}.bash", name)
}
fn generate(&self, app: &App, buf: &mut dyn Write) {
let bin_name = app
fn generate(&self, cmd: &Command, buf: &mut dyn Write) {
let bin_name = cmd
.get_bin_name()
.expect("crate::generate should have set the bin_name");
@ -62,21 +62,21 @@ complete -F _{name} -o bashdefault -o default {name}
",
name = bin_name,
cmd = bin_name.replace('-', "__"),
name_opts = all_options_for_path(app, bin_name),
name_opts_details = option_details_for_path(app, bin_name),
subcmds = all_subcommands(app),
subcmd_details = subcommand_details(app)
name_opts = all_options_for_path(cmd, bin_name),
name_opts_details = option_details_for_path(cmd, bin_name),
subcmds = all_subcommands(cmd),
subcmd_details = subcommand_details(cmd)
)
.as_bytes()
);
}
}
fn all_subcommands(app: &App) -> String {
fn all_subcommands(cmd: &Command) -> String {
debug!("all_subcommands");
let mut subcmds = vec![String::new()];
let mut scs = utils::all_subcommands(app)
let mut scs = utils::all_subcommands(cmd)
.iter()
.map(|x| x.0.clone())
.collect::<Vec<_>>();
@ -97,11 +97,11 @@ fn all_subcommands(app: &App) -> String {
subcmds.join("\n ")
}
fn subcommand_details(app: &App) -> String {
fn subcommand_details(cmd: &Command) -> String {
debug!("subcommand_details");
let mut subcmd_dets = vec![String::new()];
let mut scs = utils::all_subcommands(app)
let mut scs = utils::all_subcommands(cmd)
.iter()
.map(|x| x.1.replace(' ', "__"))
.collect::<Vec<_>>();
@ -125,19 +125,19 @@ fn subcommand_details(app: &App) -> String {
return 0
;;",
subcmd = sc.replace('-', "__"),
sc_opts = all_options_for_path(app, &*sc),
sc_opts = all_options_for_path(cmd, &*sc),
level = sc.split("__").map(|_| 1).sum::<u64>(),
opts_details = option_details_for_path(app, &*sc)
opts_details = option_details_for_path(cmd, &*sc)
)
}));
subcmd_dets.join("\n ")
}
fn option_details_for_path(app: &App, path: &str) -> String {
fn option_details_for_path(cmd: &Command, path: &str) -> String {
debug!("option_details_for_path: path={}", path);
let p = utils::find_subcommand_with_path(app, path.split("__").skip(1).collect());
let p = utils::find_subcommand_with_path(cmd, path.split("__").skip(1).collect());
let mut opts = vec![String::new()];
for o in p.get_opts() {
@ -187,10 +187,10 @@ fn vals_for(o: &Arg) -> String {
}
}
fn all_options_for_path(app: &App, path: &str) -> String {
fn all_options_for_path(cmd: &Command, path: &str) -> String {
debug!("all_options_for_path: path={}", path);
let p = utils::find_subcommand_with_path(app, path.split("__").skip(1).collect());
let p = utils::find_subcommand_with_path(cmd, path.split("__").skip(1).collect());
let mut opts = String::new();
for short in utils::shorts_and_visible_aliases(p) {

View file

@ -14,13 +14,13 @@ impl Generator for Elvish {
format!("{}.elv", name)
}
fn generate(&self, app: &App, buf: &mut dyn Write) {
let bin_name = app
fn generate(&self, cmd: &Command, buf: &mut dyn Write) {
let bin_name = cmd
.get_bin_name()
.expect("crate::generate should have set the bin_name");
let mut names = vec![];
let subcommands_cases = generate_inner(app, "", &mut names);
let subcommands_cases = generate_inner(cmd, "", &mut names);
let result = format!(
r#"
@ -67,7 +67,7 @@ fn get_tooltip<T: ToString>(help: Option<&str>, data: T) -> String {
}
fn generate_inner<'help>(
p: &App<'help>,
p: &Command<'help>,
previous_command_name: &str,
names: &mut Vec<&'help str>,
) -> String {

View file

@ -15,13 +15,13 @@ impl Generator for Fish {
format!("{}.fish", name)
}
fn generate(&self, app: &App, buf: &mut dyn Write) {
let bin_name = app
fn generate(&self, cmd: &Command, buf: &mut dyn Write) {
let bin_name = cmd
.get_bin_name()
.expect("crate::generate should have set the bin_name");
let mut buffer = String::new();
gen_fish_inner(bin_name, &[], app, &mut buffer);
gen_fish_inner(bin_name, &[], cmd, &mut buffer);
w!(buf, buffer.as_bytes());
}
}
@ -31,7 +31,12 @@ fn escape_string(string: &str) -> String {
string.replace('\\', "\\\\").replace('\'', "\\'")
}
fn gen_fish_inner(root_command: &str, parent_commands: &[&str], app: &App, buffer: &mut String) {
fn gen_fish_inner(
root_command: &str,
parent_commands: &[&str],
cmd: &Command,
buffer: &mut String,
) {
debug!("gen_fish_inner");
// example :
//
@ -49,7 +54,7 @@ fn gen_fish_inner(root_command: &str, parent_commands: &[&str], app: &App, buffe
let mut basic_template = format!("complete -c {}", root_command);
if parent_commands.is_empty() {
if app.has_subcommands() {
if cmd.has_subcommands() {
basic_template.push_str(" -n \"__fish_use_subcommand\"");
}
} else {
@ -60,7 +65,7 @@ fn gen_fish_inner(root_command: &str, parent_commands: &[&str], app: &App, buffe
.iter()
.map(|command| format!("__fish_seen_subcommand_from {}", command))
.chain(
app.get_subcommands()
cmd.get_subcommands()
.map(|command| format!("not __fish_seen_subcommand_from {}", command))
)
.collect::<Vec<_>>()
@ -72,7 +77,7 @@ fn gen_fish_inner(root_command: &str, parent_commands: &[&str], app: &App, buffe
debug!("gen_fish_inner: parent_commands={:?}", parent_commands);
for option in app.get_opts() {
for option in cmd.get_opts() {
let mut template = basic_template.clone();
if let Some(shorts) = option.get_short_and_visible_aliases() {
@ -97,7 +102,7 @@ fn gen_fish_inner(root_command: &str, parent_commands: &[&str], app: &App, buffe
buffer.push('\n');
}
for flag in utils::flags(app) {
for flag in utils::flags(cmd) {
let mut template = basic_template.clone();
if let Some(shorts) = flag.get_short_and_visible_aliases() {
@ -120,7 +125,7 @@ fn gen_fish_inner(root_command: &str, parent_commands: &[&str], app: &App, buffe
buffer.push('\n');
}
for subcommand in app.get_subcommands() {
for subcommand in cmd.get_subcommands() {
let mut template = basic_template.clone();
template.push_str(" -f");
@ -135,7 +140,7 @@ fn gen_fish_inner(root_command: &str, parent_commands: &[&str], app: &App, buffe
}
// generate options of subcommands
for subcommand in app.get_subcommands() {
for subcommand in cmd.get_subcommands() {
let mut parent_commands: Vec<_> = parent_commands.into();
parent_commands.push(subcommand.get_name());
gen_fish_inner(root_command, &parent_commands, subcommand, buffer);

View file

@ -14,13 +14,13 @@ impl Generator for PowerShell {
format!("_{}.ps1", name)
}
fn generate(&self, app: &App, buf: &mut dyn Write) {
let bin_name = app
fn generate(&self, cmd: &Command, buf: &mut dyn Write) {
let bin_name = cmd
.get_bin_name()
.expect("crate::generate should have set the bin_name");
let mut names = vec![];
let subcommands_cases = generate_inner(app, "", &mut names);
let subcommands_cases = generate_inner(cmd, "", &mut names);
let result = format!(
r#"
@ -72,7 +72,7 @@ fn get_tooltip<T: ToString>(help: Option<&str>, data: T) -> String {
}
fn generate_inner<'help>(
p: &App<'help>,
p: &Command<'help>,
previous_command_name: &str,
names: &mut Vec<&'help str>,
) -> String {

View file

@ -87,13 +87,13 @@ impl Generator for Shell {
}
}
fn generate(&self, app: &clap::App, buf: &mut dyn std::io::Write) {
fn generate(&self, cmd: &clap::Command, buf: &mut dyn std::io::Write) {
match self {
Shell::Bash => shells::Bash.generate(app, buf),
Shell::Elvish => shells::Elvish.generate(app, buf),
Shell::Fish => shells::Fish.generate(app, buf),
Shell::PowerShell => shells::PowerShell.generate(app, buf),
Shell::Zsh => shells::Zsh.generate(app, buf),
Shell::Bash => shells::Bash.generate(cmd, buf),
Shell::Elvish => shells::Elvish.generate(cmd, buf),
Shell::Fish => shells::Fish.generate(cmd, buf),
Shell::PowerShell => shells::PowerShell.generate(cmd, buf),
Shell::Zsh => shells::Zsh.generate(cmd, buf),
}
}
}

View file

@ -14,8 +14,8 @@ impl Generator for Zsh {
format!("_{}", name)
}
fn generate(&self, app: &App, buf: &mut dyn Write) {
let bin_name = app
fn generate(&self, cmd: &Command, buf: &mut dyn Write) {
let bin_name = cmd
.get_bin_name()
.expect("crate::generate should have set the bin_name");
@ -46,9 +46,9 @@ _{name}() {{
_{name} \"$@\"
",
name = bin_name,
initial_args = get_args_of(app, None),
subcommands = get_subcommands_of(app),
subcommand_details = subcommand_details(app)
initial_args = get_args_of(cmd, None),
subcommands = get_subcommands_of(cmd),
subcommand_details = subcommand_details(cmd)
)
.as_bytes()
);
@ -82,7 +82,7 @@ _{name} \"$@\"
// )
// _describe -t commands 'rustup commands' commands "$@"
//
fn subcommand_details(p: &App) -> String {
fn subcommand_details(p: &Command) -> String {
debug!("subcommand_details");
let bin_name = p
@ -142,12 +142,12 @@ _{bin_name_underscore}_commands() {{
// A snippet from rustup:
// 'show:Show the active and installed toolchains'
// 'update:Update Rust toolchains'
fn subcommands_of(p: &App) -> String {
fn subcommands_of(p: &Command) -> String {
debug!("subcommands_of");
let mut segments = vec![];
fn add_subcommands(subcommand: &App, name: &str, ret: &mut Vec<String>) {
fn add_subcommands(subcommand: &Command, name: &str, ret: &mut Vec<String>) {
debug!("add_subcommands");
let text = format!(
@ -212,7 +212,7 @@ fn subcommands_of(p: &App) -> String {
// [name_hyphen] = The full space delineated bin_name, but replace spaces with hyphens
// [repeat] = From the same recursive calls, but for all subcommands
// [subcommand_args] = The same as zsh::get_args_of
fn get_subcommands_of(parent: &App) -> String {
fn get_subcommands_of(parent: &Command) -> String {
debug!(
"get_subcommands_of: Has subcommands...{:?}",
parent.has_subcommands()
@ -276,11 +276,14 @@ esac",
)
}
// Get the App for a given subcommand tree.
// Get the Command for a given subcommand tree.
//
// Given the bin_name "a b c" and the App for "a" this returns the "c" App.
// Given the bin_name "a b c" and the App for "b" this returns the "c" App.
fn parser_of<'help, 'app>(parent: &'app App<'help>, bin_name: &str) -> Option<&'app App<'help>> {
// Given the bin_name "a b c" and the Command for "a" this returns the "c" Command.
// Given the bin_name "a b c" and the Command for "b" this returns the "c" Command.
fn parser_of<'help, 'cmd>(
parent: &'cmd Command<'help>,
bin_name: &str,
) -> Option<&'cmd Command<'help>> {
debug!("parser_of: p={}, bin_name={}", parent.get_name(), bin_name);
if bin_name == parent.get_bin_name().unwrap_or(&String::new()) {
@ -316,7 +319,7 @@ fn parser_of<'help, 'app>(parent: &'app App<'help>, bin_name: &str) -> Option<&'
// -C: modify the $context internal variable
// -s: Allow stacking of short args (i.e. -a -b -c => -abc)
// -S: Do not complete anything after '--' and treat those as argument values
fn get_args_of(parent: &App, p_global: Option<&App>) -> String {
fn get_args_of(parent: &Command, p_global: Option<&Command>) -> String {
debug!("get_args_of");
let mut segments = vec![String::from("_arguments \"${_arguments_options[@]}\" \\")];
@ -436,7 +439,7 @@ fn escape_value(string: &str) -> String {
.replace(' ', "\\ ")
}
fn write_opts_of(p: &App, p_global: Option<&App>) -> String {
fn write_opts_of(p: &Command, p_global: Option<&Command>) -> String {
debug!("write_opts_of");
let mut ret = vec![];
@ -501,7 +504,7 @@ fn write_opts_of(p: &App, p_global: Option<&App>) -> String {
ret.join("\n")
}
fn arg_conflicts(app: &App, arg: &Arg, app_global: Option<&App>) -> String {
fn arg_conflicts(cmd: &Command, arg: &Arg, app_global: Option<&Command>) -> String {
fn push_conflicts(conflicts: &[&Arg], res: &mut Vec<String>) {
for conflict in conflicts {
if let Some(s) = conflict.get_short() {
@ -526,7 +529,7 @@ fn arg_conflicts(app: &App, arg: &Arg, app_global: Option<&App>) -> String {
push_conflicts(&conflicts, &mut res);
}
(_, _) => {
let conflicts = app.get_arg_conflicts_with(arg);
let conflicts = cmd.get_arg_conflicts_with(arg);
if conflicts.is_empty() {
return String::new();
@ -539,7 +542,7 @@ fn arg_conflicts(app: &App, arg: &Arg, app_global: Option<&App>) -> String {
format!("({})", res.join(" "))
}
fn write_flags_of(p: &App, p_global: Option<&App>) -> String {
fn write_flags_of(p: &Command, p_global: Option<&Command>) -> String {
debug!("write_flags_of;");
let mut ret = vec![];
@ -620,7 +623,7 @@ fn write_flags_of(p: &App, p_global: Option<&App>) -> String {
ret.join("\n")
}
fn write_positionals_of(p: &App) -> String {
fn write_positionals_of(p: &Command) -> String {
debug!("write_positionals_of;");
let mut ret = vec![];

View file

@ -1,11 +1,11 @@
use super::*;
fn build_app() -> App<'static> {
fn build_app() -> Command<'static> {
build_app_with_name("myapp")
}
fn build_app_with_name(s: &'static str) -> App<'static> {
App::new(s)
fn build_app_with_name(s: &'static str) -> Command<'static> {
Command::new(s)
.version("3.0")
.propagate_version(true)
.about("Tests completions")
@ -16,7 +16,7 @@ fn build_app_with_name(s: &'static str) -> App<'static> {
)
.arg(Arg::new("choice").possible_values(["first", "second"]))
.subcommand(
App::new("test").about("tests things").arg(
Command::new("test").about("tests things").arg(
Arg::new("case")
.long("case")
.takes_value(true)
@ -27,8 +27,8 @@ fn build_app_with_name(s: &'static str) -> App<'static> {
#[test]
fn bash() {
let mut app = build_app();
common(Bash, &mut app, "myapp", BASH);
let mut cmd = build_app();
common(Bash, &mut cmd, "myapp", BASH);
}
static BASH: &str = r#"_myapp() {
@ -111,21 +111,21 @@ complete -F _myapp -o bashdefault -o default myapp
#[test]
fn bash_with_special_commands() {
let mut app = build_app_special_commands();
common(Bash, &mut app, "my_app", BASH_SPECIAL_CMDS);
let mut cmd = build_app_special_commands();
common(Bash, &mut cmd, "my_app", BASH_SPECIAL_CMDS);
}
fn build_app_special_commands() -> App<'static> {
fn build_app_special_commands() -> Command<'static> {
build_app_with_name("my_app")
.subcommand(
App::new("some_cmd").about("tests other things").arg(
Command::new("some_cmd").about("tests other things").arg(
Arg::new("config")
.long("--config")
.takes_value(true)
.help("the other case to test"),
),
)
.subcommand(App::new("some-cmd-with-hyphens").alias("hyphen"))
.subcommand(Command::new("some-cmd-with-hyphens").alias("hyphen"))
}
static BASH_SPECIAL_CMDS: &str = r#"_my_app() {
@ -246,12 +246,12 @@ complete -F _my_app -o bashdefault -o default my_app
#[test]
fn bash_with_aliases() {
let mut app = build_app_with_aliases();
common(Bash, &mut app, "cmd", BASH_ALIASES);
let mut cmd = build_app_with_aliases();
common(Bash, &mut cmd, "cmd", BASH_ALIASES);
}
fn build_app_with_aliases() -> App<'static> {
App::new("cmd")
fn build_app_with_aliases() -> Command<'static> {
Command::new("cmd")
.version("3.0")
.about("testing bash completions")
.arg(

View file

@ -1,11 +1,11 @@
use super::*;
fn build_app() -> App<'static> {
fn build_app() -> Command<'static> {
build_app_with_name("myapp")
}
fn build_app_with_name(s: &'static str) -> App<'static> {
App::new(s)
fn build_app_with_name(s: &'static str) -> Command<'static> {
Command::new(s)
.version("3.0")
.propagate_version(true)
.about("Tests completions")
@ -15,7 +15,7 @@ fn build_app_with_name(s: &'static str) -> App<'static> {
.help("some input file"),
)
.subcommand(
App::new("test").about("tests things").arg(
Command::new("test").about("tests things").arg(
Arg::new("case")
.long("case")
.takes_value(true)
@ -26,8 +26,8 @@ fn build_app_with_name(s: &'static str) -> App<'static> {
#[test]
fn elvish() {
let mut app = build_app();
common(Elvish, &mut app, "my_app", ELVISH);
let mut cmd = build_app();
common(Elvish, &mut cmd, "my_app", ELVISH);
}
static ELVISH: &str = r#"
@ -73,21 +73,21 @@ set edit:completion:arg-completer[my_app] = {|@words|
#[test]
fn elvish_with_special_commands() {
let mut app = build_app_special_commands();
common(Elvish, &mut app, "my_app", ELVISH_SPECIAL_CMDS);
let mut cmd = build_app_special_commands();
common(Elvish, &mut cmd, "my_app", ELVISH_SPECIAL_CMDS);
}
fn build_app_special_commands() -> App<'static> {
fn build_app_special_commands() -> Command<'static> {
build_app_with_name("my_app")
.subcommand(
App::new("some_cmd").about("tests other things").arg(
Command::new("some_cmd").about("tests other things").arg(
Arg::new("config")
.long("--config")
.takes_value(true)
.help("the other case to test"),
),
)
.subcommand(App::new("some-cmd-with-hyphens").alias("hyphen"))
.subcommand(Command::new("some-cmd-with-hyphens").alias("hyphen"))
}
static ELVISH_SPECIAL_CMDS: &str = r#"
@ -148,12 +148,12 @@ set edit:completion:arg-completer[my_app] = {|@words|
#[test]
fn elvish_with_aliases() {
let mut app = build_app_with_aliases();
common(Elvish, &mut app, "cmd", ELVISH_ALIASES);
let mut cmd = build_app_with_aliases();
common(Elvish, &mut cmd, "cmd", ELVISH_ALIASES);
}
fn build_app_with_aliases() -> App<'static> {
App::new("cmd")
fn build_app_with_aliases() -> Command<'static> {
Command::new("cmd")
.version("3.0")
.about("testing bash completions")
.arg(

View file

@ -2,12 +2,12 @@ use clap::PossibleValue;
use super::*;
fn build_app() -> App<'static> {
fn build_app() -> Command<'static> {
build_app_with_name("myapp")
}
fn build_app_with_name(s: &'static str) -> App<'static> {
App::new(s)
fn build_app_with_name(s: &'static str) -> Command<'static> {
Command::new(s)
.version("3.0")
.propagate_version(true)
.about("Tests completions")
@ -17,7 +17,7 @@ fn build_app_with_name(s: &'static str) -> App<'static> {
.help("some input file"),
)
.subcommand(
App::new("test").about("tests things").arg(
Command::new("test").about("tests things").arg(
Arg::new("case")
.long("case")
.takes_value(true)
@ -28,8 +28,8 @@ fn build_app_with_name(s: &'static str) -> App<'static> {
#[test]
fn fish() {
let mut app = build_app();
common(Fish, &mut app, "myapp", FISH);
let mut cmd = build_app();
common(Fish, &mut cmd, "myapp", FISH);
}
static FISH: &str = r#"complete -c myapp -n "__fish_use_subcommand" -s h -l help -d 'Print help information'
@ -43,21 +43,21 @@ complete -c myapp -n "__fish_seen_subcommand_from test" -s V -l version -d 'Prin
#[test]
fn fish_with_special_commands() {
let mut app = build_app_special_commands();
common(Fish, &mut app, "my_app", FISH_SPECIAL_CMDS);
let mut cmd = build_app_special_commands();
common(Fish, &mut cmd, "my_app", FISH_SPECIAL_CMDS);
}
fn build_app_special_commands() -> App<'static> {
fn build_app_special_commands() -> Command<'static> {
build_app_with_name("my_app")
.subcommand(
App::new("some_cmd").about("tests other things").arg(
Command::new("some_cmd").about("tests other things").arg(
Arg::new("config")
.long("--config")
.takes_value(true)
.help("the other case to test"),
),
)
.subcommand(App::new("some-cmd-with-hyphens").alias("hyphen"))
.subcommand(Command::new("some-cmd-with-hyphens").alias("hyphen"))
}
static FISH_SPECIAL_CMDS: &str = r#"complete -c my_app -n "__fish_use_subcommand" -s h -l help -d 'Print help information'
@ -78,12 +78,12 @@ complete -c my_app -n "__fish_seen_subcommand_from some-cmd-with-hyphens" -s V -
#[test]
fn fish_with_special_help() {
let mut app = build_app_special_help();
common(Fish, &mut app, "my_app", FISH_SPECIAL_HELP);
let mut cmd = build_app_special_help();
common(Fish, &mut cmd, "my_app", FISH_SPECIAL_HELP);
}
fn build_app_special_help() -> App<'static> {
App::new("my_app")
fn build_app_special_help() -> Command<'static> {
Command::new("my_app")
.version("3.0")
.arg(
Arg::new("single-quotes")
@ -125,12 +125,12 @@ complete -c my_app -l expansions -d 'Execute the shell command with $SHELL'
#[test]
fn fish_with_aliases() {
let mut app = build_app_with_aliases();
common(Fish, &mut app, "cmd", FISH_ALIASES);
let mut cmd = build_app_with_aliases();
common(Fish, &mut cmd, "cmd", FISH_ALIASES);
}
fn build_app_with_aliases() -> App<'static> {
App::new("cmd")
fn build_app_with_aliases() -> Command<'static> {
Command::new("cmd")
.version("3.0")
.about("testing bash completions")
.arg(
@ -161,16 +161,16 @@ complete -c cmd -s f -s F -l flag -l flg -d 'cmd flag'
#[test]
fn fish_with_sub_subcommands() {
let mut app = build_app_sub_subcommands();
common(Fish, &mut app, "my_app", FISH_SUB_SUBCMDS);
let mut cmd = build_app_sub_subcommands();
common(Fish, &mut cmd, "my_app", FISH_SUB_SUBCMDS);
}
fn build_app_sub_subcommands() -> App<'static> {
fn build_app_sub_subcommands() -> Command<'static> {
build_app_with_name("my_app").subcommand(
App::new("some_cmd")
Command::new("some_cmd")
.about("top level subcommand")
.subcommand(
App::new("sub_cmd").about("sub-subcommand").arg(
Command::new("sub_cmd").about("sub-subcommand").arg(
Arg::new("config")
.long("--config")
.takes_value(true)

View file

@ -1,4 +1,4 @@
use clap::{App, Arg, ValueHint};
use clap::{Arg, Command, ValueHint};
use clap_complete::{generate, shells::*, Generator};
use std::fmt;
@ -23,9 +23,9 @@ macro_rules! assert_eq {
};
}
pub fn common<G: Generator>(gen: G, app: &mut App, name: &str, fixture: &str) {
pub fn common<G: Generator>(gen: G, cmd: &mut Command, name: &str, fixture: &str) {
let mut buf = vec![];
generate(gen, app, name, &mut buf);
generate(gen, cmd, name, &mut buf);
let string = String::from_utf8(buf).unwrap();
assert_eq!(&string, fixture);

View file

@ -1,11 +1,11 @@
use super::*;
fn build_app() -> App<'static> {
fn build_app() -> Command<'static> {
build_app_with_name("myapp")
}
fn build_app_with_name(s: &'static str) -> App<'static> {
App::new(s)
fn build_app_with_name(s: &'static str) -> Command<'static> {
Command::new(s)
.version("3.0")
.propagate_version(true)
.about("Tests completions")
@ -23,7 +23,7 @@ fn build_app_with_name(s: &'static str) -> App<'static> {
.visible_alias("conf"),
)
.subcommand(
App::new("test").about("tests things").arg(
Command::new("test").about("tests things").arg(
Arg::new("case")
.long("case")
.takes_value(true)
@ -34,8 +34,8 @@ fn build_app_with_name(s: &'static str) -> App<'static> {
#[test]
fn powershell() {
let mut app = build_app();
common(PowerShell, &mut app, "my_app", POWERSHELL);
let mut cmd = build_app();
common(PowerShell, &mut cmd, "my_app", POWERSHELL);
}
static POWERSHELL: &str = r#"
@ -93,21 +93,21 @@ Register-ArgumentCompleter -Native -CommandName 'my_app' -ScriptBlock {
#[test]
fn powershell_with_special_commands() {
let mut app = build_app_special_commands();
common(PowerShell, &mut app, "my_app", POWERSHELL_SPECIAL_CMDS);
let mut cmd = build_app_special_commands();
common(PowerShell, &mut cmd, "my_app", POWERSHELL_SPECIAL_CMDS);
}
fn build_app_special_commands() -> App<'static> {
fn build_app_special_commands() -> Command<'static> {
build_app_with_name("my_app")
.subcommand(
App::new("some_cmd").about("tests other things").arg(
Command::new("some_cmd").about("tests other things").arg(
Arg::new("config")
.long("--config")
.takes_value(true)
.help("the other case to test"),
),
)
.subcommand(App::new("some-cmd-with-hyphens").alias("hyphen"))
.subcommand(Command::new("some-cmd-with-hyphens").alias("hyphen"))
}
static POWERSHELL_SPECIAL_CMDS: &str = r#"
@ -182,12 +182,12 @@ Register-ArgumentCompleter -Native -CommandName 'my_app' -ScriptBlock {
#[test]
fn powershell_with_aliases() {
let mut app = build_app_with_aliases();
common(PowerShell, &mut app, "cmd", POWERSHELL_ALIASES);
let mut cmd = build_app_with_aliases();
common(PowerShell, &mut cmd, "cmd", POWERSHELL_ALIASES);
}
fn build_app_with_aliases() -> App<'static> {
App::new("cmd")
fn build_app_with_aliases() -> Command<'static> {
Command::new("cmd")
.version("3.0")
.about("testing bash completions")
.arg(

View file

@ -1,11 +1,11 @@
use super::*;
fn build_app() -> App<'static> {
fn build_app() -> Command<'static> {
build_app_with_name("myapp")
}
fn build_app_with_name(s: &'static str) -> App<'static> {
App::new(s)
fn build_app_with_name(s: &'static str) -> Command<'static> {
Command::new(s)
.version("3.0")
.propagate_version(true)
.about("Test test's completions")
@ -15,7 +15,7 @@ fn build_app_with_name(s: &'static str) -> App<'static> {
.help("some input's file"),
)
.subcommand(
App::new("test").about("test test's things").arg(
Command::new("test").about("test test's things").arg(
Arg::new("case")
.long("case")
.takes_value(true)
@ -26,8 +26,8 @@ fn build_app_with_name(s: &'static str) -> App<'static> {
#[test]
fn zsh() {
let mut app = build_app();
common(Zsh, &mut app, "myapp", ZSH);
let mut cmd = build_app();
common(Zsh, &mut cmd, "myapp", ZSH);
}
static ZSH: &str = r#"#compdef myapp
@ -104,23 +104,23 @@ _myapp "$@"
#[test]
fn zsh_with_special_commands() {
let mut app = build_app_special_commands();
common(Zsh, &mut app, "my_app", ZSH_SPECIAL_CMDS);
let mut cmd = build_app_special_commands();
common(Zsh, &mut cmd, "my_app", ZSH_SPECIAL_CMDS);
}
fn build_app_special_commands() -> App<'static> {
fn build_app_special_commands() -> Command<'static> {
build_app_with_name("my_app")
.subcommand(
App::new("some_cmd").about("tests other things").arg(
Command::new("some_cmd").about("tests other things").arg(
Arg::new("config")
.long("--config")
.takes_value(true)
.help("the other case to test"),
),
)
.subcommand(App::new("some-cmd-with-hypens").alias("hyphen"))
.subcommand(Command::new("some-cmd-with-hypens").alias("hyphen"))
.subcommand(
App::new("some_cmd_with_special_characters")
Command::new("some_cmd_with_special_characters")
.about("This 'is' a \"special\" [character] string \\"),
)
}
@ -242,12 +242,12 @@ _my_app "$@"
#[test]
fn zsh_with_special_help() {
let mut app = build_app_special_help();
common(Zsh, &mut app, "my_app", ZSH_SPECIAL_HELP);
let mut cmd = build_app_special_help();
common(Zsh, &mut cmd, "my_app", ZSH_SPECIAL_HELP);
}
fn build_app_special_help() -> App<'static> {
App::new("my_app")
fn build_app_special_help() -> Command<'static> {
Command::new("my_app")
.version("3.0")
.arg(
Arg::new("single-quotes")
@ -318,14 +318,14 @@ _my_app "$@"
#[test]
fn zsh_with_nested_subcommands() {
let mut app = build_app_nested_subcommands();
common(Zsh, &mut app, "my_app", ZSH_NESTED_SUBCOMMANDS);
let mut cmd = build_app_nested_subcommands();
common(Zsh, &mut cmd, "my_app", ZSH_NESTED_SUBCOMMANDS);
}
fn build_app_nested_subcommands() -> App<'static> {
App::new("first")
fn build_app_nested_subcommands() -> Command<'static> {
Command::new("first")
.version("3.0")
.subcommand(App::new("second").subcommand(App::new("third")))
.subcommand(Command::new("second").subcommand(Command::new("third")))
}
static ZSH_NESTED_SUBCOMMANDS: &str = r#"#compdef my_app
@ -438,12 +438,12 @@ _my_app "$@"
#[test]
fn zsh_with_aliases() {
let mut app = build_app_with_aliases();
common(Zsh, &mut app, "cmd", ZSH_ALIASES);
let mut cmd = build_app_with_aliases();
common(Zsh, &mut cmd, "cmd", ZSH_ALIASES);
}
fn build_app_with_aliases() -> App<'static> {
App::new("cmd")
fn build_app_with_aliases() -> Command<'static> {
Command::new("cmd")
.version("3.0")
.about("testing bash completions")
.arg(
@ -510,12 +510,12 @@ _cmd "$@"
#[test]
fn zsh_with_files_and_dirs() {
let mut app = build_app_with_files_and_dirs();
common(Zsh, &mut app, "my_app", ZSH_PATHS);
let mut cmd = build_app_with_files_and_dirs();
common(Zsh, &mut cmd, "my_app", ZSH_PATHS);
}
fn build_app_with_files_and_dirs() -> App<'static> {
App::new("my_app")
fn build_app_with_files_and_dirs() -> Command<'static> {
Command::new("my_app")
.version("3.0")
.about("testing zsh completions")
.arg(

View file

@ -1,23 +1,23 @@
use std::io;
use clap::{App, Arg};
use clap::{Arg, Command};
use clap_complete::{generate, shells::*};
#[test]
fn generate_completions() {
let mut app = App::new("test_app")
let mut cmd = Command::new("test_app")
.arg(Arg::new("config").short('c').global(true))
.arg(Arg::new("v").short('v').conflicts_with("config"))
.subcommand(
App::new("test")
Command::new("test")
.about("Subcommand")
.arg(Arg::new("debug").short('d')),
);
generate(Bash, &mut app, "test_app", &mut io::sink());
generate(Fish, &mut app, "test_app", &mut io::sink());
generate(PowerShell, &mut app, "test_app", &mut io::sink());
generate(Elvish, &mut app, "test_app", &mut io::sink());
generate(Zsh, &mut app, "test_app", &mut io::sink());
generate(Bash, &mut cmd, "test_app", &mut io::sink());
generate(Fish, &mut cmd, "test_app", &mut io::sink());
generate(PowerShell, &mut cmd, "test_app", &mut io::sink());
generate(Elvish, &mut cmd, "test_app", &mut io::sink());
generate(Zsh, &mut cmd, "test_app", &mut io::sink());
}

View file

@ -1,12 +1,12 @@
mod completions;
use clap::{App, Arg, ValueHint};
use clap::{Arg, Command, ValueHint};
use clap_complete::shells::*;
use completions::common;
pub fn build_app_with_value_hints() -> App<'static> {
App::new("my_app")
pub fn build_app_with_value_hints() -> Command<'static> {
Command::new("my_app")
.trailing_var_arg(true)
.arg(
Arg::new("choice")
@ -149,12 +149,12 @@ complete -c my_app -l help -d 'Print help information'
#[test]
fn zsh_with_value_hints() {
let mut app = build_app_with_value_hints();
common(Zsh, &mut app, "my_app", ZSH_VALUE_HINTS);
let mut cmd = build_app_with_value_hints();
common(Zsh, &mut cmd, "my_app", ZSH_VALUE_HINTS);
}
#[test]
fn fish_with_value_hints() {
let mut app = build_app_with_value_hints();
common(Fish, &mut app, "my_app", FISH_VALUE_HINTS);
let mut cmd = build_app_with_value_hints();
common(Fish, &mut cmd, "my_app", FISH_VALUE_HINTS);
}

View file

@ -1,12 +1,12 @@
use clap::App;
use clap::Command;
use clap_complete::generate;
use clap_complete_fig::Fig;
use std::io;
fn main() {
let mut app = App::new("myapp")
.subcommand(App::new("test").subcommand(App::new("config")))
.subcommand(App::new("hello"));
let mut cmd = Command::new("myapp")
.subcommand(Command::new("test").subcommand(Command::new("config")))
.subcommand(Command::new("hello"));
generate(Fig, &mut app, "myapp", &mut io::stdout());
generate(Fig, &mut cmd, "myapp", &mut io::stdout());
}

View file

@ -13,8 +13,8 @@ impl Generator for Fig {
format!("{}.ts", name)
}
fn generate(&self, app: &App, buf: &mut dyn Write) {
let command = app.get_bin_name().unwrap();
fn generate(&self, cmd: &Command, buf: &mut dyn Write) {
let command = cmd.get_bin_name().unwrap();
let mut buffer = String::new();
buffer.push_str(&format!(
@ -24,10 +24,10 @@ impl Generator for Fig {
buffer.push_str(&format!(
" description: \"{}\",\n",
app.get_about().unwrap_or_default()
cmd.get_about().unwrap_or_default()
));
gen_fig_inner(command, &[], 2, app, &mut buffer);
gen_fig_inner(command, &[], 2, cmd, &mut buffer);
buffer.push_str("};\n\nexport default completion;\n");
@ -45,13 +45,13 @@ fn gen_fig_inner(
root_command: &str,
parent_commands: &[&str],
indent: usize,
app: &App,
cmd: &Command,
buffer: &mut String,
) {
if app.has_subcommands() {
if cmd.has_subcommands() {
buffer.push_str(&format!("{:indent$}subcommands: [\n", "", indent = indent));
// generate subcommands
for subcommand in app.get_subcommands() {
for subcommand in cmd.get_subcommands() {
buffer.push_str(&format!(
"{:indent$}{{\n{:indent$} name: \"{}\",\n",
"",
@ -84,9 +84,9 @@ fn gen_fig_inner(
buffer.push_str(&format!("{:indent$}],\n", "", indent = indent));
}
buffer.push_str(&gen_options(app, indent));
buffer.push_str(&gen_options(cmd, indent));
let args = app.get_positionals().collect::<Vec<_>>();
let args = cmd.get_positionals().collect::<Vec<_>>();
match args.len() {
0 => {}
@ -105,12 +105,12 @@ fn gen_fig_inner(
};
}
fn gen_options(app: &App, indent: usize) -> String {
fn gen_options(cmd: &Command, indent: usize) -> String {
let mut buffer = String::new();
buffer.push_str(&format!("{:indent$}options: [\n", "", indent = indent));
for option in app.get_opts() {
for option in cmd.get_opts() {
buffer.push_str(&format!("{:indent$}{{\n", "", indent = indent + 2));
let mut names = vec![];
@ -160,7 +160,7 @@ fn gen_options(app: &App, indent: usize) -> String {
buffer.push_str(&format!("{:indent$}}},\n", "", indent = indent + 2));
}
for flag in generator::utils::flags(app) {
for flag in generator::utils::flags(cmd) {
buffer.push_str(&format!("{:indent$}{{\n", "", indent = indent + 2));
let mut flags = vec![];

View file

@ -1,12 +1,12 @@
use super::*;
use crate::Fig;
fn build_app() -> App<'static> {
fn build_app() -> Command<'static> {
build_app_with_name("myapp")
}
fn build_app_with_name(s: &'static str) -> App<'static> {
App::new(s)
fn build_app_with_name(s: &'static str) -> Command<'static> {
Command::new(s)
.version("3.0")
.propagate_version(true)
.about("Tests completions")
@ -16,7 +16,7 @@ fn build_app_with_name(s: &'static str) -> App<'static> {
.help("some input file"),
)
.subcommand(
App::new("test").about("tests things").arg(
Command::new("test").about("tests things").arg(
Arg::new("case")
.long("case")
.takes_value(true)
@ -27,8 +27,8 @@ fn build_app_with_name(s: &'static str) -> App<'static> {
#[test]
fn fig() {
let mut app = build_app();
common(Fig, &mut app, "myapp", FIG);
let mut cmd = build_app();
common(Fig, &mut cmd, "myapp", FIG);
}
static FIG: &str = r#"const completion: Fig.Spec = {
@ -90,21 +90,21 @@ export default completion;
#[test]
fn fig_with_special_commands() {
let mut app = build_app_special_commands();
common(Fig, &mut app, "my_app", FIG_SPECIAL_CMDS);
let mut cmd = build_app_special_commands();
common(Fig, &mut cmd, "my_app", FIG_SPECIAL_CMDS);
}
fn build_app_special_commands() -> App<'static> {
fn build_app_special_commands() -> Command<'static> {
build_app_with_name("my_app")
.subcommand(
App::new("some_cmd").about("tests other things").arg(
Command::new("some_cmd").about("tests other things").arg(
Arg::new("config")
.long("--config")
.takes_value(true)
.help("the other case to test"),
),
)
.subcommand(App::new("some-cmd-with-hyphens").alias("hyphen"))
.subcommand(Command::new("some-cmd-with-hyphens").alias("hyphen"))
}
static FIG_SPECIAL_CMDS: &str = r#"const completion: Fig.Spec = {
@ -201,12 +201,12 @@ export default completion;
#[test]
fn fig_with_special_help() {
let mut app = build_app_special_help();
common(Fig, &mut app, "my_app", FIG_SPECIAL_HELP);
let mut cmd = build_app_special_help();
common(Fig, &mut cmd, "my_app", FIG_SPECIAL_HELP);
}
fn build_app_special_help() -> App<'static> {
App::new("my_app")
fn build_app_special_help() -> Command<'static> {
Command::new("my_app")
.version("3.0")
.arg(
Arg::new("single-quotes")
@ -280,12 +280,12 @@ export default completion;
#[test]
fn fig_with_aliases() {
let mut app = build_app_with_aliases();
common(Fig, &mut app, "cmd", FIG_ALIASES);
let mut cmd = build_app_with_aliases();
common(Fig, &mut cmd, "cmd", FIG_ALIASES);
}
fn build_app_with_aliases() -> App<'static> {
App::new("cmd")
fn build_app_with_aliases() -> Command<'static> {
Command::new("cmd")
.version("3.0")
.about("testing bash completions")
.arg(
@ -344,16 +344,16 @@ export default completion;
#[test]
fn fig_with_sub_subcommands() {
let mut app = build_app_sub_subcommands();
common(Fig, &mut app, "my_app", FIG_SUB_SUBCMDS);
let mut cmd = build_app_sub_subcommands();
common(Fig, &mut cmd, "my_app", FIG_SUB_SUBCMDS);
}
fn build_app_sub_subcommands() -> App<'static> {
fn build_app_sub_subcommands() -> Command<'static> {
build_app_with_name("my_app").subcommand(
App::new("some_cmd")
Command::new("some_cmd")
.about("top level subcommand")
.subcommand(
App::new("sub_cmd").about("sub-subcommand").arg(
Command::new("sub_cmd").about("sub-subcommand").arg(
Arg::new("config")
.long("--config")
.takes_value(true)

View file

@ -1,4 +1,4 @@
use clap::{App, Arg, ValueHint};
use clap::{Arg, Command, ValueHint};
use clap_complete::{generate, Generator};
use std::fmt;
@ -19,9 +19,9 @@ macro_rules! assert_eq {
};
}
pub fn common<G: Generator>(gen: G, app: &mut App, name: &str, fixture: &str) {
pub fn common<G: Generator>(gen: G, cmd: &mut Command, name: &str, fixture: &str) {
let mut buf = vec![];
generate(gen, app, name, &mut buf);
generate(gen, cmd, name, &mut buf);
let string = String::from_utf8(buf).unwrap();
assert_eq!(&string, fixture);

View file

@ -1,18 +1,18 @@
use clap::{App, Arg};
use clap::{Arg, Command};
use clap_complete::generate;
use clap_complete_fig::Fig;
use std::io;
#[test]
fn generate_completions() {
let mut app = App::new("test_app")
let mut cmd = Command::new("test_app")
.arg(Arg::new("config").short('c').global(true))
.arg(Arg::new("v").short('v').conflicts_with("config"))
.subcommand(
App::new("test")
Command::new("test")
.about("Subcommand")
.arg(Arg::new("debug").short('d')),
);
generate(Fig, &mut app, "test_app", &mut io::sink());
generate(Fig, &mut cmd, "test_app", &mut io::sink());
}

View file

@ -1,11 +1,11 @@
use clap::{App, Arg, ValueHint};
use clap::{Arg, Command, ValueHint};
use clap_complete_fig::Fig;
use completions::common;
mod completions;
pub fn build_app_with_value_hints() -> App<'static> {
App::new("my_app")
pub fn build_app_with_value_hints() -> Command<'static> {
Command::new("my_app")
.disable_version_flag(true)
.trailing_var_arg(true)
.arg(
@ -210,6 +210,6 @@ export default completion;
#[test]
fn fig_with_value_hints() {
let mut app = build_app_with_value_hints();
common(Fig, &mut app, "my_app", FIG_VALUE_HINTS);
let mut cmd = build_app_with_value_hints();
common(Fig, &mut cmd, "my_app", FIG_VALUE_HINTS);
}

View file

@ -87,10 +87,10 @@ pub fn gen_for_struct(
)]
#[deny(clippy::correctness)]
impl #impl_generics clap::Args for #struct_name #ty_generics #where_clause {
fn augment_args<'b>(#app_var: clap::App<'b>) -> clap::App<'b> {
fn augment_args<'b>(#app_var: clap::Command<'b>) -> clap::Command<'b> {
#augmentation
}
fn augment_args_for_update<'b>(#app_var: clap::App<'b>) -> clap::App<'b> {
fn augment_args_for_update<'b>(#app_var: clap::Command<'b>) -> clap::Command<'b> {
#augmentation_update
}
}
@ -145,7 +145,7 @@ pub fn gen_from_arg_matches_for_struct(
}
/// Generate a block of code to add arguments/subcommands corresponding to
/// the `fields` to an app.
/// the `fields` to an cmd.
pub fn gen_augment(
fields: &Punctuated<Field, Comma>,
app_var: &Ident,

View file

@ -57,13 +57,13 @@ pub fn gen_for_struct(
)]
#[deny(clippy::correctness)]
impl #impl_generics clap::IntoApp for #struct_name #ty_generics #where_clause {
fn into_app<'b>() -> clap::App<'b> {
let #app_var = clap::App::new(#name);
fn into_app<'b>() -> clap::Command<'b> {
let #app_var = clap::Command::new(#name);
<Self as clap::Args>::augment_args(#app_var)
}
fn into_app_for_update<'b>() -> clap::App<'b> {
let #app_var = clap::App::new(#name);
fn into_app_for_update<'b>() -> clap::Command<'b> {
let #app_var = clap::Command::new(#name);
<Self as clap::Args>::augment_args_for_update(#app_var)
}
}
@ -102,15 +102,15 @@ pub fn gen_for_enum(enum_name: &Ident, generics: &Generics, attrs: &[Attribute])
)]
#[deny(clippy::correctness)]
impl #impl_generics clap::IntoApp for #enum_name #ty_generics #where_clause {
fn into_app<'b>() -> clap::App<'b> {
fn into_app<'b>() -> clap::Command<'b> {
#[allow(deprecated)]
let #app_var = clap::App::new(#name)
let #app_var = clap::Command::new(#name)
.setting(clap::AppSettings::SubcommandRequiredElseHelp);
<Self as clap::Subcommand>::augment_subcommands(#app_var)
}
fn into_app_for_update<'b>() -> clap::App<'b> {
let #app_var = clap::App::new(#name);
fn into_app_for_update<'b>() -> clap::Command<'b> {
let #app_var = clap::Command::new(#name);
<Self as clap::Subcommand>::augment_subcommands_for_update(#app_var)
}
}

View file

@ -75,10 +75,10 @@ pub fn gen_for_enum(
)]
#[deny(clippy::correctness)]
impl #impl_generics clap::Subcommand for #enum_name #ty_generics #where_clause {
fn augment_subcommands <'b>(__clap_app: clap::App<'b>) -> clap::App<'b> {
fn augment_subcommands <'b>(__clap_app: clap::Command<'b>) -> clap::Command<'b> {
#augmentation
}
fn augment_subcommands_for_update <'b>(__clap_app: clap::App<'b>) -> clap::App<'b> {
fn augment_subcommands_for_update <'b>(__clap_app: clap::Command<'b>) -> clap::Command<'b> {
#augmentation_update
}
fn has_subcommand(__clap_name: &str) -> bool {
@ -245,7 +245,7 @@ fn gen_augment(
let final_from_attrs = attrs.final_top_level_methods();
let subcommand = quote! {
let #app_var = #app_var.subcommand({
let #subcommand_var = clap::App::new(#name);
let #subcommand_var = clap::Command::new(#name);
let #subcommand_var = #subcommand_var #initial_app_methods;
let #subcommand_var = #arg_block;
#[allow(deprecated)]
@ -260,7 +260,7 @@ fn gen_augment(
let subcommand_var = Ident::new("__clap_subcommand", Span::call_site());
let sub_augment = match variant.fields {
Named(ref fields) => {
// Defer to `gen_augment` for adding app methods
// Defer to `gen_augment` for adding cmd methods
args::gen_augment(&fields.named, &subcommand_var, &attrs, override_required)
}
Unit => {
@ -304,7 +304,7 @@ fn gen_augment(
let name = attrs.cased_name();
let subcommand = quote! {
let #app_var = #app_var.subcommand({
let #subcommand_var = clap::App::new(#name);
let #subcommand_var = clap::Command::new(#name);
#sub_augment
});
};

View file

@ -19,10 +19,10 @@ pub fn parser_enum(name: &Ident) {
pub fn into_app(name: &Ident) {
append_dummy(quote! {
impl clap::IntoApp for #name {
fn into_app<'b>() -> clap::App<'b> {
fn into_app<'b>() -> clap::Command<'b> {
unimplemented!()
}
fn into_app_for_update<'b>() -> clap::App<'b> {
fn into_app_for_update<'b>() -> clap::Command<'b> {
unimplemented!()
}
}
@ -46,10 +46,10 @@ pub fn subcommand(name: &Ident) {
from_arg_matches(name);
append_dummy(quote! {
impl clap::Subcommand for #name {
fn augment_subcommands(_app: clap::App<'_>) -> clap::App<'_> {
fn augment_subcommands(_cmd: clap::Command<'_>) -> clap::Command<'_> {
unimplemented!()
}
fn augment_subcommands_for_update(_app: clap::App<'_>) -> clap::App<'_> {
fn augment_subcommands_for_update(_cmd: clap::Command<'_>) -> clap::Command<'_> {
unimplemented!()
}
fn has_subcommand(name: &str) -> bool {
@ -63,10 +63,10 @@ pub fn args(name: &Ident) {
from_arg_matches(name);
append_dummy(quote! {
impl clap::Args for #name {
fn augment_args(_app: clap::App<'_>) -> clap::App<'_> {
fn augment_args(_cmd: clap::Command<'_>) -> clap::Command<'_> {
unimplemented!()
}
fn augment_args_for_update(_app: clap::App<'_>) -> clap::App<'_> {
fn augment_args_for_update(_cmd: clap::Command<'_>) -> clap::Command<'_> {
unimplemented!()
}
}

View file

@ -38,7 +38,7 @@ pub fn arg_enum(input: TokenStream) -> TokenStream {
/// Generates the `Parser` implementation.
///
/// This is far less verbose than defining the `clap::App` struct manually,
/// This is far less verbose than defining the `clap::Command` struct manually,
/// receiving an instance of `clap::ArgMatches` from conducting parsing, and then
/// implementing a conversion code to instantiate an instance of the user
/// context struct.

View file

@ -266,12 +266,12 @@ fn raw_method_suggestion(ts: ParseBuffer) -> String {
};
format!(
"if you need to call `clap::Arg/App::{}` method you \
"if you need to call `clap::Arg/Command::{}` method you \
can do it like this: #[clap({}{})]",
name, name, suggestion
)
} else {
"if you need to call some method from `clap::Arg/App` \
"if you need to call some method from `clap::Arg/Command` \
you should use raw method, see \
https://github.com/clap-rs/clap/blob/master/examples/derive_ref/README.md#raw-attributes"
.into()

View file

@ -22,7 +22,7 @@ pub mod utils {
#[deprecated(since = "3.0.0", note = "Renamed to `clap_complete::generate_to`")]
pub fn generate_to<G, S, T>(
gen: G,
app: &mut clap::App,
cmd: &mut clap::Command,
bin_name: S,
out_dir: T,
) -> Result<PathBuf, Error>
@ -31,14 +31,14 @@ where
S: Into<String>,
T: Into<OsString>,
{
clap_complete::generate_to(gen, app, bin_name, out_dir)
clap_complete::generate_to(gen, cmd, bin_name, out_dir)
}
#[deprecated(since = "3.0.0", note = "Renamed to `clap_complete`")]
pub fn generate<G, S>(gen: G, app: &mut clap::App, bin_name: S, buf: &mut dyn Write)
pub fn generate<G, S>(gen: G, cmd: &mut clap::Command, bin_name: S, buf: &mut dyn Write)
where
G: Generator,
S: Into<String>,
{
clap_complete::generate(gen, app, bin_name, buf)
clap_complete::generate(gen, cmd, bin_name, buf)
}

View file

@ -1,23 +1,23 @@
#![allow(deprecated)]
use clap::{App, Arg};
use clap::{Arg, Command};
use clap_generate::{generate, generators::*};
use std::io;
#[test]
fn generate_completions() {
let mut app = App::new("test_app")
let mut cmd = Command::new("test_app")
.arg(Arg::new("config").short('c').global(true))
.arg(Arg::new("v").short('v').conflicts_with("config"))
.subcommand(
App::new("test")
Command::new("test")
.about("Subcommand")
.arg(Arg::new("debug").short('d')),
);
generate(Bash, &mut app, "test_app", &mut io::sink());
generate(Fish, &mut app, "test_app", &mut io::sink());
generate(PowerShell, &mut app, "test_app", &mut io::sink());
generate(Elvish, &mut app, "test_app", &mut io::sink());
generate(Zsh, &mut app, "test_app", &mut io::sink());
generate(Bash, &mut cmd, "test_app", &mut io::sink());
generate(Fish, &mut cmd, "test_app", &mut io::sink());
generate(PowerShell, &mut cmd, "test_app", &mut io::sink());
generate(Elvish, &mut cmd, "test_app", &mut io::sink());
generate(Zsh, &mut cmd, "test_app", &mut io::sink());
}

View file

@ -18,7 +18,7 @@ Dual-licensed under [Apache 2.0](LICENSE-APACHE) or [MIT](LICENSE-MIT).
## About
Generate [ROFF](https://en.wikipedia.org/wiki/Roff_(software)) from a `clap::App`.
Generate [ROFF](https://en.wikipedia.org/wiki/Roff_(software)) from a `clap::Command`.
### Example
@ -36,11 +36,11 @@ In your `build.rs`:
fn main() -> std::io::Result<()> {
let out_dir = std::path::PathBuf::from(std::env::var_os("OUT_DIR").ok_or_else(|| std::io::ErrorKind::NotFound)?);
let app = clap::App::new("mybin")
let cmd = clap::Command::new("mybin")
.arg(clap::arg!(-n --name <NAME>))
.arg(clap::arg!(-c --count <NUM>));
let man = clap_mangen::Man::new(app);
let man = clap_mangen::Man::new(cmd);
let mut buffer: Vec<u8> = Default::default();
man.render(&mut buffer)?;

View file

@ -1,11 +1,11 @@
use clap::{arg, App};
use clap::{arg, Command};
use clap_mangen::Man;
use std::io;
// Run this example as `cargo run --example man | man -l -`.
fn main() -> Result<(), std::io::Error> {
let app = App::new("myapp")
let cmd = Command::new("myapp")
.version("1.0")
.author("Kevin K. <kbknapp@gmail.com>:Ola Nordmann <old@nordmann.no>")
.about("Does awesome things")
@ -31,10 +31,10 @@ And a few newlines.",
.hide_env(true),
)
.subcommand(
App::new("test")
Command::new("test")
.about("does testing things")
.arg(arg!(-l --list "Lists test values")),
);
Man::new(app).render(&mut io::stdout())
Man::new(cmd).render(&mut io::stdout())
}

View file

@ -14,7 +14,7 @@ use std::io::Write;
/// A manpage writer
pub struct Man<'a> {
app: clap::App<'a>,
cmd: clap::Command<'a>,
title: String,
section: String,
date: String,
@ -25,19 +25,19 @@ pub struct Man<'a> {
/// Build a [`Man`]
impl<'a> Man<'a> {
/// Create a new manual page.
pub fn new(mut app: clap::App<'a>) -> Self {
app._build_all();
let title = app.get_name().to_owned();
pub fn new(mut cmd: clap::Command<'a>) -> Self {
cmd._build_all();
let title = cmd.get_name().to_owned();
let section = "1".to_owned();
let date = "".to_owned();
let source = format!(
"{} {}",
app.get_name(),
app.get_version().unwrap_or_default()
cmd.get_name(),
cmd.get_version().unwrap_or_default()
);
let manual = "".to_owned();
Self {
app,
cmd,
title,
section,
date,
@ -105,23 +105,23 @@ impl<'a> Man<'a> {
self._render_synopsis_section(&mut roff);
self._render_description_section(&mut roff);
if app_has_arguments(&self.app) {
if app_has_arguments(&self.cmd) {
self._render_options_section(&mut roff);
}
if app_has_subcommands(&self.app) {
if app_has_subcommands(&self.cmd) {
self._render_subcommands_section(&mut roff);
}
if self.app.get_after_long_help().is_some() || self.app.get_after_help().is_some() {
if self.cmd.get_after_long_help().is_some() || self.cmd.get_after_help().is_some() {
self._render_extra_section(&mut roff);
}
if app_has_version(&self.app) {
if app_has_version(&self.cmd) {
self._render_version_section(&mut roff);
}
if self.app.get_author().is_some() {
if self.cmd.get_author().is_some() {
self._render_authors_section(&mut roff);
}
@ -159,7 +159,7 @@ impl<'a> Man<'a> {
fn _render_name_section(&self, roff: &mut Roff) {
roff.control("SH", ["NAME"]);
render::about(roff, &self.app);
render::about(roff, &self.cmd);
}
/// Render the SYNOPSIS section into the writer.
@ -171,7 +171,7 @@ impl<'a> Man<'a> {
fn _render_synopsis_section(&self, roff: &mut Roff) {
roff.control("SH", ["SYNOPSIS"]);
render::synopsis(roff, &self.app);
render::synopsis(roff, &self.cmd);
}
/// Render the DESCRIPTION section into the writer.
@ -183,7 +183,7 @@ impl<'a> Man<'a> {
fn _render_description_section(&self, roff: &mut Roff) {
roff.control("SH", ["DESCRIPTION"]);
render::description(roff, &self.app);
render::description(roff, &self.cmd);
}
/// Render the OPTIONS section into the writer.
@ -195,7 +195,7 @@ impl<'a> Man<'a> {
fn _render_options_section(&self, roff: &mut Roff) {
roff.control("SH", ["OPTIONS"]);
render::options(roff, &self.app);
render::options(roff, &self.cmd);
}
/// Render the SUBCOMMANDS section into the writer.
@ -206,9 +206,9 @@ impl<'a> Man<'a> {
}
fn _render_subcommands_section(&self, roff: &mut Roff) {
let heading = subcommand_heading(&self.app);
let heading = subcommand_heading(&self.cmd);
roff.control("SH", [heading.as_str()]);
render::subcommands(roff, &self.app, &self.section);
render::subcommands(roff, &self.cmd, &self.section);
}
/// Render the EXTRA section into the writer.
@ -220,7 +220,7 @@ impl<'a> Man<'a> {
fn _render_extra_section(&self, roff: &mut Roff) {
roff.control("SH", ["EXTRA"]);
render::after_help(roff, &self.app);
render::after_help(roff, &self.cmd);
}
/// Render the VERSION section into the writer.
@ -231,7 +231,7 @@ impl<'a> Man<'a> {
}
fn _render_version_section(&self, roff: &mut Roff) {
let version = roman(&render::version(&self.app));
let version = roman(&render::version(&self.cmd));
roff.control("SH", ["VERSION"]);
roff.text([version]);
}
@ -244,25 +244,25 @@ impl<'a> Man<'a> {
}
fn _render_authors_section(&self, roff: &mut Roff) {
let author = roman(self.app.get_author().unwrap_or_default());
let author = roman(self.cmd.get_author().unwrap_or_default());
roff.control("SH", ["AUTHORS"]);
roff.text([author]);
}
}
// Does the application have a version?
fn app_has_version(app: &clap::App) -> bool {
app.get_version()
.or_else(|| app.get_long_version())
fn app_has_version(cmd: &clap::Command) -> bool {
cmd.get_version()
.or_else(|| cmd.get_long_version())
.is_some()
}
// Does the application have any command line arguments?
fn app_has_arguments(app: &clap::App) -> bool {
app.get_arguments().any(|i| !i.is_hide_set())
fn app_has_arguments(cmd: &clap::Command) -> bool {
cmd.get_arguments().any(|i| !i.is_hide_set())
}
// Does the application have any subcommands?
fn app_has_subcommands(app: &clap::App) -> bool {
app.get_subcommands().any(|i| !i.is_hide_set())
fn app_has_subcommands(cmd: &clap::Command) -> bool {
cmd.get_subcommands().any(|i| !i.is_hide_set())
}

View file

@ -1,23 +1,23 @@
use clap::AppSettings;
use roff::{bold, italic, roman, Inline, Roff};
pub(crate) fn subcommand_heading(app: &clap::App) -> String {
match app.get_subcommand_help_heading() {
pub(crate) fn subcommand_heading(cmd: &clap::Command) -> String {
match cmd.get_subcommand_help_heading() {
Some(title) => title.to_string(),
None => "SUBCOMMANDS".to_string(),
}
}
pub(crate) fn about(roff: &mut Roff, app: &clap::App) {
let s = match app.get_about().or_else(|| app.get_long_about()) {
Some(about) => format!("{} - {}", app.get_name(), about),
None => app.get_name().to_string(),
pub(crate) fn about(roff: &mut Roff, cmd: &clap::Command) {
let s = match cmd.get_about().or_else(|| cmd.get_long_about()) {
Some(about) => format!("{} - {}", cmd.get_name(), about),
None => cmd.get_name().to_string(),
};
roff.text([roman(&s)]);
}
pub(crate) fn description(roff: &mut Roff, app: &clap::App) {
if let Some(about) = app.get_long_about().or_else(|| app.get_about()) {
pub(crate) fn description(roff: &mut Roff, cmd: &clap::Command) {
if let Some(about) = cmd.get_long_about().or_else(|| cmd.get_about()) {
for line in about.lines() {
if line.trim().is_empty() {
roff.control("PP", []);
@ -28,10 +28,10 @@ pub(crate) fn description(roff: &mut Roff, app: &clap::App) {
}
}
pub(crate) fn synopsis(roff: &mut Roff, app: &clap::App) {
let mut line = vec![bold(app.get_name()), roman(" ")];
pub(crate) fn synopsis(roff: &mut Roff, cmd: &clap::Command) {
let mut line = vec![bold(cmd.get_name()), roman(" ")];
for opt in app.get_arguments() {
for opt in cmd.get_arguments() {
let (lhs, rhs) = option_markers(opt);
match (opt.get_short(), opt.get_long()) {
(Some(short), Some(long)) => {
@ -58,7 +58,7 @@ pub(crate) fn synopsis(roff: &mut Roff, app: &clap::App) {
};
}
for arg in app.get_positionals() {
for arg in cmd.get_positionals() {
let (lhs, rhs) = option_markers(arg);
line.push(roman(lhs));
line.push(italic(arg.get_id()));
@ -66,12 +66,12 @@ pub(crate) fn synopsis(roff: &mut Roff, app: &clap::App) {
line.push(roman(" "));
}
if app.has_subcommands() {
let (lhs, rhs) = subcommand_markers(app);
if cmd.has_subcommands() {
let (lhs, rhs) = subcommand_markers(cmd);
line.push(roman(lhs));
line.push(italic(
&app.get_subcommand_value_name()
.unwrap_or(&subcommand_heading(app))
&cmd.get_subcommand_value_name()
.unwrap_or(&subcommand_heading(cmd))
.to_lowercase(),
));
line.push(roman(rhs));
@ -80,8 +80,8 @@ pub(crate) fn synopsis(roff: &mut Roff, app: &clap::App) {
roff.text(line);
}
pub(crate) fn options(roff: &mut Roff, app: &clap::App) {
let items: Vec<_> = app.get_arguments().filter(|i| !i.is_hide_set()).collect();
pub(crate) fn options(roff: &mut Roff, cmd: &clap::Command) {
let items: Vec<_> = cmd.get_arguments().filter(|i| !i.is_hide_set()).collect();
for opt in items.iter().filter(|a| !a.is_positional()) {
let mut body = vec![];
@ -143,11 +143,11 @@ pub(crate) fn options(roff: &mut Roff, app: &clap::App) {
}
}
pub(crate) fn subcommands(roff: &mut Roff, app: &clap::App, section: &str) {
for sub in app.get_subcommands().filter(|s| !s.is_hide_set()) {
pub(crate) fn subcommands(roff: &mut Roff, cmd: &clap::Command, section: &str) {
for sub in cmd.get_subcommands().filter(|s| !s.is_hide_set()) {
roff.control("TP", []);
let name = format!("{}-{}({})", app.get_name(), sub.get_name(), section);
let name = format!("{}-{}({})", cmd.get_name(), sub.get_name(), section);
roff.text([roman(&name)]);
if let Some(about) = sub.get_about().or_else(|| sub.get_long_about()) {
@ -158,24 +158,24 @@ pub(crate) fn subcommands(roff: &mut Roff, app: &clap::App, section: &str) {
}
}
pub(crate) fn version(app: &clap::App) -> String {
pub(crate) fn version(cmd: &clap::Command) -> String {
format!(
"v{}",
app.get_long_version()
.or_else(|| app.get_version())
cmd.get_long_version()
.or_else(|| cmd.get_version())
.unwrap()
)
}
pub(crate) fn after_help(roff: &mut Roff, app: &clap::App) {
if let Some(about) = app.get_after_long_help().or_else(|| app.get_after_help()) {
pub(crate) fn after_help(roff: &mut Roff, cmd: &clap::Command) {
if let Some(about) = cmd.get_after_long_help().or_else(|| cmd.get_after_help()) {
for line in about.lines() {
roff.text([roman(line)]);
}
}
}
fn subcommand_markers(cmd: &clap::App) -> (&'static str, &'static str) {
fn subcommand_markers(cmd: &clap::Command) -> (&'static str, &'static str) {
#[allow(deprecated)]
markers(cmd.is_subcommand_required_set() || cmd.is_set(AppSettings::SubcommandRequiredElseHelp))
}

View file

@ -1,10 +1,10 @@
use clap::{arg, App};
use clap::{arg, Command};
use clap_mangen::Man;
use std::io;
#[test]
fn render_manpage() {
let app = App::new("myapp")
let cmd = Command::new("myapp")
.version("1.0")
.author("Kevin K. <kbknapp@gmail.com>")
.about("Does awesome things")
@ -20,10 +20,10 @@ fn render_manpage() {
.arg(arg!([output] "Sets an optional output file").index(1))
.arg(arg!(-d --debug ... "Turn debugging information on"))
.subcommand(
App::new("test")
Command::new("test")
.about("does testing things")
.arg(arg!(-l --list "Lists test values")),
);
Man::new(app).render(&mut io::sink()).unwrap();
Man::new(cmd).render(&mut io::sink()).unwrap();
}

View file

@ -66,7 +66,7 @@ Previously, we supported:
There are also experiments with other APIs:
- [fncmd](https://github.com/yuhr/fncmd): function attribute
- [clap-serde](https://github.com/aobatact/clap-serde): create an `App` from a deserializer
- [clap-serde](https://github.com/aobatact/clap-serde): create an `Command` from a deserializer
### Why is there a default subcommand of help?

View file

@ -1,7 +1,7 @@
// Note: this requires the `cargo` feature
fn main() {
let app = clap::App::new("cargo")
let cmd = clap::Command::new("cargo")
.bin_name("cargo")
.subcommand_required(true)
.subcommand(
@ -11,7 +11,7 @@ fn main() {
.allow_invalid_utf8(true),
),
);
let matches = app.get_matches();
let matches = cmd.get_matches();
let matches = match matches.subcommand() {
Some(("example", matches)) => matches,
_ => unreachable!("clap should ensure we don't get here"),

View file

@ -3,7 +3,7 @@
1. [Overview](#overview)
2. [Raw Attributes](#raw-attributes)
3. [Magic Attributes](#magic-attributes)
1. [App Attributes](#app-attributes)
1. [Command Attributes](#cmd-attributes)
2. [Arg Attributes](#arg-attributes)
3. [Arg Types](#arg-types)
4. [Arg Enum Attributes](#arg-enum-attributes)
@ -85,7 +85,7 @@ See also the [tutorial](../tutorial_derive/README.md) and [examples](../README.m
## Raw Attributes
**Raw attributes** are forwarded directly to the underlying `clap` builder. Any
`App`, `Arg`, or `PossibleValue` method can be used as an attribute.
`Command`, `Arg`, or `PossibleValue` method can be used as an attribute.
Raw attributes come in two different syntaxes:
```rust
@ -107,33 +107,33 @@ translated into a mere method call.
- Providing of defaults
- Special behavior is triggered off of it
### App Attributes
### Command Attributes
These correspond to a `clap::App` which is used for both top-level parsers and
These correspond to a `clap::Command` which is used for both top-level parsers and
when defining subcommands.
In addition to the raw attributes, the following magic attributes are supported:
- `name = <expr>`: `clap::App::name`
- `name = <expr>`: `clap::Command::name`
- When not present: [crate `name`](https://doc.rust-lang.org/cargo/reference/manifest.html#the-name-field) (`Parser` container), variant name (`Subcommand` variant)
- `version [= <expr>]`: `clap::App::version`
- `version [= <expr>]`: `clap::Command::version`
- When not present: no version set
- Without `<expr>`: defaults to [crate `version`](https://doc.rust-lang.org/cargo/reference/manifest.html#the-version-field)
- `author [= <expr>]`: `clap::App::author`
- `author [= <expr>]`: `clap::Command::author`
- When not present: no author set
- Without `<expr>`: defaults to [crate `authors`](https://doc.rust-lang.org/cargo/reference/manifest.html#the-authors-field)
- `about [= <expr>]`: `clap::App::about`
- `about [= <expr>]`: `clap::Command::about`
- When not present: [Doc comment summary](#doc-comments)
- Without `<expr>`: [crate `description`](https://doc.rust-lang.org/cargo/reference/manifest.html#the-description-field) (`Parser` container)
- **TIP:** When a doc comment is also present, you most likely want to add
`#[clap(long_about = None)]` to clear the doc comment so only `about`
gets shown with both `-h` and `--help`.
- `long_about = <expr>`: `clap::App::long_about`
- `long_about = <expr>`: `clap::Command::long_about`
- When not present: [Doc comment](#doc-comments) if there is a blank line, else nothing
- `verbatim_doc_comment`: Minimizes pre-processing when converting doc comments to `about` / `long_about`
- `next_display_order`: `clap::App::next_display_order`
- `next_help_heading`: `clap::App::next_help_heading`
- `next_display_order`: `clap::Command::next_display_order`
- `next_help_heading`: `clap::Command::next_help_heading`
- When `flatten`ing `Args`, this is scoped to just the args in this struct and any struct `flatten`ed into it
- `rename_all = <expr>`: Override default field / variant name case conversion for `App::name` / `Arg::name`
- `rename_all = <expr>`: Override default field / variant name case conversion for `Command::name` / `Arg::name`
- When not present: `kebab-case`
- Available values: `camelCase`, `kebab-case`, `PascalCase`, `SCREAMING_SNAKE_CASE`, `snake_case`, `lower`, `UPPER`, `verbatim`
- `rename_all_env = <expr>`: Override default field name case conversion for env variables for `clap::Arg::env`
@ -144,7 +144,7 @@ And for `Subcommand` variants:
- `skip`: Ignore this variant
- `flatten`: Delegates to the variant for more subcommands (must implement `Subcommand`)
- `subcommand`: Nest subcommands under the current set of subcommands (must implement `Subcommand`)
- `external_subcommand`: `clap::App::allow_external_subcommand(true)`
- `external_subcommand`: `clap::Command::allow_external_subcommand(true)`
- Variant must be either `Variant(Vec<String>)` or `Variant(Vec<OsString>)`
### Arg Attributes
@ -172,8 +172,8 @@ In addition to the raw attributes, the following magic attributes are supported:
- Only `help_heading` can be used with `flatten`. See
[clap-rs/clap#3269](https://github.com/clap-rs/clap/issues/3269) for why
arg attributes are not generally supported.
- **Tip:** Though we do apply a flattened `Args`'s Parent App Attributes, this
makes reuse harder. Generally prefer putting the app attributes on the `Parser`
- **Tip:** Though we do apply a flattened `Args`'s Parent Command Attributes, this
makes reuse harder. Generally prefer putting the cmd attributes on the `Parser`
or on the flattened field.
- `subcommand`: Delegates definition of subcommands to the field (must implement `Subcommand`)
- When `Option<T>`, the subcommand becomes optional
@ -259,7 +259,7 @@ These correspond to a `clap::PossibleValue`.
### Doc Comments
In clap, help messages for the whole binary can be specified
via [`App::about`] and [`App::long_about`] while help messages
via [`Command::about`] and [`Command::long_about`] while help messages
for individual arguments can be specified via [`Arg::help`] and [`Arg::long_help`]".
`long_*` variants are used when user calls the program with
@ -292,8 +292,8 @@ struct Foo {
**NOTE:** Attributes have priority over doc comments!
**Top level doc comments always generate `App::about/long_about` calls!**
If you really want to use the `App::about/long_about` methods (you likely don't),
**Top level doc comments always generate `Command::about/long_about` calls!**
If you really want to use the `Command::about/long_about` methods (you likely don't),
use the `about` / `long_about` attributes to override the calls generated from
the doc comment. To clear `long_about`, you can use
`#[clap(long_about = None)]`.
@ -326,10 +326,10 @@ A doc comment consists of three parts:
- A blank line (whitespace only)
- Detailed description, all the rest
The summary corresponds with `App::about` / `Arg::help`. When a blank line is
present, the whole doc comment will be passed to `App::long_about` /
`Arg::long_help`. Or in other words, a doc may result in just a `App::about` /
`Arg::help` or `App::about` / `Arg::help` and `App::long_about` /
The summary corresponds with `Command::about` / `Arg::help`. When a blank line is
present, the whole doc comment will be passed to `Command::long_about` /
`Arg::long_help`. Or in other words, a doc may result in just a `Command::about` /
`Arg::help` or `Command::about` / `Arg::help` and `Command::long_about` /
`Arg::long_help`
In addition, when `verbatim_doc_comment` is not present, `clap` applies some preprocessing, including:

View file

@ -2,29 +2,29 @@
use std::path::PathBuf;
use clap::{arg, App};
use clap::{arg, Command};
fn main() {
let matches = App::new("git")
let matches = Command::new("git")
.about("A fictional versioning CLI")
.subcommand_required(true)
.arg_required_else_help(true)
.allow_external_subcommands(true)
.allow_invalid_utf8_for_external_subcommands(true)
.subcommand(
App::new("clone")
Command::new("clone")
.about("Clones repos")
.arg(arg!(<REMOTE> "The remote to clone"))
.arg_required_else_help(true),
)
.subcommand(
App::new("push")
Command::new("push")
.about("pushes things")
.arg(arg!(<REMOTE> "The remote to target"))
.arg_required_else_help(true),
)
.subcommand(
App::new("add")
Command::new("add")
.about("adds things")
.arg_required_else_help(true)
.arg(arg!(<PATH> ... "Stuff to add").allow_invalid_utf8(true)),

View file

@ -2,7 +2,7 @@
Example of a busybox-style multicall program
See the documentation for `clap::App::multicall` for rationale.
See the documentation for `clap::Command::multicall` for rationale.
This example omits every command except true and false,
which are the most trivial to implement,

View file

@ -2,20 +2,20 @@
use std::process::exit;
use clap::{App, Arg};
use clap::{Arg, Command};
fn applet_commands() -> [App<'static>; 2] {
fn applet_commands() -> [Command<'static>; 2] {
[
App::new("true").about("does nothing successfully"),
App::new("false").about("does nothing unsuccessfully"),
Command::new("true").about("does nothing successfully"),
Command::new("false").about("does nothing unsuccessfully"),
]
}
fn main() {
let app = App::new(env!("CARGO_CRATE_NAME"))
let cmd = Command::new(env!("CARGO_CRATE_NAME"))
.multicall(true)
.subcommand(
App::new("busybox")
Command::new("busybox")
.arg_required_else_help(true)
.subcommand_value_name("APPLET")
.subcommand_help_heading("APPLETS")
@ -32,7 +32,7 @@ fn main() {
)
.subcommands(applet_commands());
let matches = app.get_matches();
let matches = cmd.get_matches();
let mut subcommand = matches.subcommand();
if let Some(("busybox", cmd)) = subcommand {
if cmd.occurrences_of("install") > 0 {

View file

@ -2,7 +2,7 @@
Example of a `hostname-style` multicall program
See the documentation for `clap::App::multicall` for rationale.
See the documentation for `clap::Command::multicall` for rationale.
This example omits the implementation of displaying address config

View file

@ -1,18 +1,18 @@
// Note: this requires the `unstable-multicall` feature
use clap::App;
use clap::Command;
fn main() {
let app = App::new(env!("CARGO_CRATE_NAME"))
let cmd = Command::new(env!("CARGO_CRATE_NAME"))
.arg_required_else_help(true)
.subcommand_value_name("APPLET")
.subcommand_help_heading("APPLETS")
.subcommand(App::new("hostname").about("show hostname part of FQDN"))
.subcommand(App::new("dnsdomainname").about("show domain name part of FQDN"));
.subcommand(Command::new("hostname").about("show hostname part of FQDN"))
.subcommand(Command::new("dnsdomainname").about("show domain name part of FQDN"));
let app = app.multicall(true);
let cmd = cmd.multicall(true);
match app.get_matches().subcommand_name() {
match cmd.get_matches().subcommand_name() {
Some("hostname") => println!("www"),
Some("dnsdomainname") => println!("example.com"),
_ => unreachable!("parser should ensure only valid subcommand names are used"),

View file

@ -1,7 +1,7 @@
use clap::{App, Arg};
use clap::{Arg, Command};
fn main() {
let matches = App::new("pacman")
let matches = Command::new("pacman")
.about("package manager utility")
.version("5.2.1")
.subcommand_required(true)
@ -11,7 +11,7 @@ fn main() {
//
// Only a few of its arguments are implemented below.
.subcommand(
App::new("query")
Command::new("query")
.short_flag('Q')
.long_flag("query")
.about("Query the package database.")
@ -38,7 +38,7 @@ fn main() {
//
// Only a few of its arguments are implemented below.
.subcommand(
App::new("sync")
Command::new("sync")
.short_flag('S')
.long_flag("sync")
.about("Synchronize packages.")

View file

@ -1,4 +1,4 @@
use clap::{app_from_crate, arg, App};
use clap::{app_from_crate, arg, Command};
use std::path::Path;
fn main() {
@ -17,7 +17,7 @@ fn main() {
-d --debug ... "Turn debugging information on"
))
.subcommand(
App::new("test")
Command::new("test")
.about("does testing things")
.arg(arg!(-l --list "lists test values")),
)
@ -43,7 +43,7 @@ fn main() {
}
// You can check for the existence of subcommands, and if found use their
// matches just as you would the top level app
// matches just as you would the top level cmd
if let Some(matches) = matches.subcommand_matches("test") {
// "$ myapp test" was run
if matches.is_present("list") {

View file

@ -1,7 +1,7 @@
use clap::{arg, App};
use clap::{arg, Command};
fn main() {
let matches = App::new("MyApp")
let matches = Command::new("MyApp")
.version("1.0")
.author("Kevin K. <kbknapp@gmail.com>")
.about("Does awesome things")

View file

@ -1,4 +1,4 @@
use clap::{app_from_crate, arg, App};
use clap::{app_from_crate, arg, Command};
fn main() {
let matches = app_from_crate!()
@ -6,7 +6,7 @@ fn main() {
.subcommand_required(true)
.arg_required_else_help(true)
.subcommand(
App::new("add")
Command::new("add")
.about("Adds files to myapp")
.arg(arg!([NAME])),
)

View file

@ -2,7 +2,7 @@ use clap::{app_from_crate, arg, ErrorKind};
fn main() {
// Create application like normal
let mut app = app_from_crate!()
let mut cmd = app_from_crate!()
// Add the version arguments
.arg(arg!(--"set-ver" <VER> "set version manually").required(false))
.arg(arg!(--major "auto inc major"))
@ -15,7 +15,7 @@ fn main() {
// Now let's assume we have a -c [config] argument which requires one of
// (but **not** both) the "input" arguments
.arg(arg!(config: -c <CONFIG>).required(false));
let matches = app.get_matches_mut();
let matches = cmd.get_matches_mut();
// Let's assume the old version 1.2.3
let mut major = 1;
@ -26,7 +26,7 @@ fn main() {
let version = if let Some(ver) = matches.value_of("set-ver") {
if matches.is_present("major") || matches.is_present("minor") || matches.is_present("patch")
{
app.error(
cmd.error(
ErrorKind::ArgumentConflict,
"Can't do relative and absolute version change",
)
@ -45,7 +45,7 @@ fn main() {
(false, true, false) => minor += 1,
(false, false, true) => patch += 1,
_ => {
app.error(
cmd.error(
ErrorKind::ArgumentConflict,
"Cam only modify one version field",
)
@ -63,7 +63,7 @@ fn main() {
.value_of("INPUT_FILE")
.or_else(|| matches.value_of("spec-in"))
.unwrap_or_else(|| {
app.error(
cmd.error(
ErrorKind::MissingRequiredArgument,
"INPUT_FILE or --spec-in is required when using --config",
)

View file

@ -1,7 +1,7 @@
use clap::{app_from_crate, arg};
fn main() {
let matches = app().get_matches();
let matches = cmd().get_matches();
// Note, it's safe to call unwrap() because the arg is required
let port: usize = matches
@ -10,7 +10,7 @@ fn main() {
println!("PORT = {}", port);
}
fn app() -> clap::App<'static> {
fn cmd() -> clap::Command<'static> {
app_from_crate!().arg(
arg!(<PORT>)
.help("Network port to use")
@ -20,5 +20,5 @@ fn app() -> clap::App<'static> {
#[test]
fn verify_app() {
app().debug_assert();
cmd().debug_assert();
}

View file

@ -63,7 +63,7 @@ Not printing testing lists...
## Configuring the Parser
You use the `App` the start building a parser.
You use the `Command` the start building a parser.
[Example:](02_apps.rs)
```console
@ -109,7 +109,7 @@ clap [..]
```
You can use `App` methods to change the application level behavior of clap.
You can use `Command` methods to change the application level behavior of clap.
[Example:](02_app_settings.rs)
```console
@ -264,7 +264,7 @@ NAME: Some("bob")
### Subcommands
Subcommands are defined as `App`s that get added via `App::subcommand`. Each
Subcommands are defined as `Command`s that get added via `Command::subcommand`. Each
instance of a Subcommand can have its own version, author(s), Args, and even its own
subcommands.
@ -304,7 +304,7 @@ $ 03_04_subcommands add bob
```
Because we set `App::arg_required_else_help`:
Because we set `Command::arg_required_else_help`:
```console
$ 03_04_subcommands
? failed
@ -324,7 +324,7 @@ SUBCOMMANDS:
```
Because we set `App::propagate_version`:
Because we set `Command::propagate_version`:
```console
$ 03_04_subcommands --version
clap [..]
@ -642,7 +642,7 @@ Doing work using input input.txt and config config.toml
## Tips
- Proactively check for bad `App` configurations by calling `App::debug_assert` ([example](05_01_assert.rs))
- Proactively check for bad `Command` configurations by calling `Command::debug_assert` ([example](05_01_assert.rs))
## Contributing

View file

@ -52,7 +52,7 @@ fn main() {
}
// You can check for the existence of subcommands, and if found use their
// matches just as you would the top level app
// matches just as you would the top level cmd
match &cli.command {
Some(Commands::Test { list }) => {
if *list {

View file

@ -18,7 +18,7 @@ fn main() {
let cli = Cli::parse();
// You can check for the existence of subcommands, and if found use their
// matches just as you would the top level app
// matches just as you would the top level cmd
match &cli.command {
Commands::Add { name } => {
println!("'myapp add' was used, name is: {:?}", name)

View file

@ -41,8 +41,8 @@ fn main() {
// See if --set-ver was used to set the version manually
let version = if let Some(ver) = cli.set_ver.as_deref() {
if cli.major || cli.minor || cli.patch {
let mut app = Cli::into_app();
app.error(
let mut cmd = Cli::into_app();
cmd.error(
ErrorKind::ArgumentConflict,
"Can't do relative and absolute version change",
)
@ -57,8 +57,8 @@ fn main() {
(false, true, false) => minor += 1,
(false, false, true) => patch += 1,
_ => {
let mut app = Cli::into_app();
app.error(
let mut cmd = Cli::into_app();
cmd.error(
ErrorKind::ArgumentConflict,
"Cam only modify one version field",
)
@ -80,8 +80,8 @@ fn main() {
// 'or' is preferred to 'or_else' here since `Option::as_deref` is 'const'
.or(cli.spec_in.as_deref())
.unwrap_or_else(|| {
let mut app = Cli::into_app();
app.error(
let mut cmd = Cli::into_app();
cmd.error(
ErrorKind::MissingRequiredArgument,
"INPUT_FILE or --spec-in is required when using --config",
)

View file

@ -66,7 +66,7 @@ In addition to this tutorial, see the [derive reference](../derive_ref/README.md
## Configuring the Parser
You use the `App` the start building a parser.
You use the `Command` the start building a parser.
[Example:](02_apps.rs)
```console
@ -111,7 +111,7 @@ clap [..]
```
You can use `App` methods to change the application level behavior of clap.
You can use `Command` methods to change the application level behavior of clap.
[Example:](02_app_settings.rs)
```console
@ -266,7 +266,7 @@ name: Some("bob")
### Subcommands
Subcommands are defined as `App`s that get added via `App::subcommand`. Each
Subcommands are defined as `Command`s that get added via `Command::subcommand`. Each
instance of a Subcommand can have its own version, author(s), Args, and even its own
subcommands.
@ -326,7 +326,7 @@ SUBCOMMANDS:
```
Because we set `App::propagate_version`:
Because we set `Command::propagate_version`:
```console
$ 03_04_subcommands_derive --version
clap [..]
@ -610,7 +610,7 @@ Doing work using input input.txt and config config.toml
## Tips
- Proactively check for bad `App` configurations by calling `App::debug_assert` ([example](05_01_assert.rs))
- Proactively check for bad `Command` configurations by calling `Command::debug_assert` ([example](05_01_assert.rs))
## Contributing

View file

@ -5,10 +5,10 @@ use std::ops::BitOr;
#[cfg(feature = "yaml")]
use std::str::FromStr;
#[allow(unused)]
use crate::App;
#[allow(unused)]
use crate::Arg;
#[allow(unused)]
use crate::Command;
// Third party
use bitflags::bitflags;
@ -23,31 +23,31 @@ impl Default for AppFlags {
}
}
/// Application level settings, which affect how [`App`] operates
/// Application level settings, which affect how [`Command`] operates
///
/// **NOTE:** When these settings are used, they apply only to current command, and are *not*
/// propagated down or up through child or parent subcommands
///
/// [`App`]: crate::App
/// [`Command`]: crate::Command
#[derive(Debug, PartialEq, Copy, Clone)]
#[non_exhaustive]
pub enum AppSettings {
/// Deprecated, replaced with [`App::ignore_errors`]
#[deprecated(since = "3.1.0", note = "Replaced with `App::ignore_errors`")]
/// Deprecated, replaced with [`Command::ignore_errors`]
#[deprecated(since = "3.1.0", note = "Replaced with `Command::ignore_errors`")]
IgnoreErrors,
/// Deprecated, replace
/// ```rust,no_run
/// let app = clap::App::new("app")
/// let cmd = clap::Command::new("cmd")
/// .global_setting(clap::AppSettings::WaitOnError)
/// .arg(clap::arg!(--flag));
/// let m = app.get_matches();
/// let m = cmd.get_matches();
/// ```
/// with
/// ```rust
/// let app = clap::App::new("app")
/// let cmd = clap::Command::new("cmd")
/// .arg(clap::arg!(--flag));
/// let m = match app.try_get_matches() {
/// let m = match cmd.try_get_matches() {
/// Ok(m) => m,
/// Err(err) => {
/// if err.use_stderr() {
@ -73,93 +73,93 @@ pub enum AppSettings {
)]
WaitOnError,
/// Deprecated, replaced with [`App::allow_hyphen_values`] and
/// Deprecated, replaced with [`Command::allow_hyphen_values`] and
/// [`Arg::is_allow_hyphen_values_set`]
#[deprecated(
since = "3.1.0",
note = "Replaced with `App::allow_hyphen_values` and `Arg::is_allow_hyphen_values_set`"
note = "Replaced with `Command::allow_hyphen_values` and `Arg::is_allow_hyphen_values_set`"
)]
AllowHyphenValues,
/// Deprecated, replaced with [`App::allow_negative_numbers`] and
/// [`App::is_allow_negative_numbers_set`]
/// Deprecated, replaced with [`Command::allow_negative_numbers`] and
/// [`Command::is_allow_negative_numbers_set`]
#[deprecated(
since = "3.1.0",
note = "Replaced with `App::allow_negative_numbers` and `App::is_allow_negative_numbers_set`"
note = "Replaced with `Command::allow_negative_numbers` and `Command::is_allow_negative_numbers_set`"
)]
AllowNegativeNumbers,
/// Deprecated, replaced with [`App::args_override_self`]
#[deprecated(since = "3.1.0", note = "Replaced with `App::args_override_self`")]
/// Deprecated, replaced with [`Command::args_override_self`]
#[deprecated(since = "3.1.0", note = "Replaced with `Command::args_override_self`")]
AllArgsOverrideSelf,
/// Deprecated, replaced with [`App::allow_missing_positional`] and
/// [`App::is_allow_missing_positional_set`]
/// Deprecated, replaced with [`Command::allow_missing_positional`] and
/// [`Command::is_allow_missing_positional_set`]
#[deprecated(
since = "3.1.0",
note = "Replaced with `App::allow_missing_positional` and `App::is_allow_missing_positional_set`"
note = "Replaced with `Command::allow_missing_positional` and `Command::is_allow_missing_positional_set`"
)]
AllowMissingPositional,
/// Deprecated, replaced with [`App::trailing_var_arg`] and [`App::is_trailing_var_arg_set`]
/// Deprecated, replaced with [`Command::trailing_var_arg`] and [`Command::is_trailing_var_arg_set`]
#[deprecated(
since = "3.1.0",
note = "Replaced with `App::trailing_var_arg` and `App::is_trailing_var_arg_set`"
note = "Replaced with `Command::trailing_var_arg` and `Command::is_trailing_var_arg_set`"
)]
TrailingVarArg,
/// Deprecated, replaced with [`App::dont_delimit_trailing_values`] and
/// [`App::is_dont_delimit_trailing_values_set`]
/// Deprecated, replaced with [`Command::dont_delimit_trailing_values`] and
/// [`Command::is_dont_delimit_trailing_values_set`]
#[deprecated(
since = "3.1.0",
note = "Replaced with `App::dont_delimit_trailing_values` and `App::is_dont_delimit_trailing_values_set`"
note = "Replaced with `Command::dont_delimit_trailing_values` and `Command::is_dont_delimit_trailing_values_set`"
)]
DontDelimitTrailingValues,
/// Deprecated, replaced with [`App::infer_long_args`]
#[deprecated(since = "3.1.0", note = "Replaced with `App::infer_long_args`")]
/// Deprecated, replaced with [`Command::infer_long_args`]
#[deprecated(since = "3.1.0", note = "Replaced with `Command::infer_long_args`")]
InferLongArgs,
/// Deprecated, replaced with [`App::infer_subcommands`]
#[deprecated(since = "3.1.0", note = "Replaced with `App::infer_subcommands`")]
/// Deprecated, replaced with [`Command::infer_subcommands`]
#[deprecated(since = "3.1.0", note = "Replaced with `Command::infer_subcommands`")]
InferSubcommands,
/// Deprecated, replaced with [`App::subcommand_required`] and
/// [`App::is_subcommand_required_set`]
/// Deprecated, replaced with [`Command::subcommand_required`] and
/// [`Command::is_subcommand_required_set`]
#[deprecated(
since = "3.1.0",
note = "Replaced with `App::subcommand_required` and `App::is_subcommand_required_set`"
note = "Replaced with `Command::subcommand_required` and `Command::is_subcommand_required_set`"
)]
SubcommandRequired,
/// Deprecated, replaced with [`App::subcommand_required`] combined with
/// [`App::arg_required_else_help`].
/// Deprecated, replaced with [`Command::subcommand_required`] combined with
/// [`Command::arg_required_else_help`].
#[deprecated(
since = "3.1.0",
note = "Replaced with `App::subcommand_required` combined with `App::arg_required_else_help`"
note = "Replaced with `Command::subcommand_required` combined with `Command::arg_required_else_help`"
)]
SubcommandRequiredElseHelp,
/// Deprecated, replaced with [`App::allow_external_subcommands`] and
/// [`App::is_allow_external_subcommands_set`]
/// Deprecated, replaced with [`Command::allow_external_subcommands`] and
/// [`Command::is_allow_external_subcommands_set`]
#[deprecated(
since = "3.1.0",
note = "Replaced with `App::allow_external_subcommands` and `App::is_allow_external_subcommands_set`"
note = "Replaced with `Command::allow_external_subcommands` and `Command::is_allow_external_subcommands_set`"
)]
AllowExternalSubcommands,
/// Deprecated, replaced with [`App::multicall`] and [`App::is_multicall_set`]
/// Deprecated, replaced with [`Command::multicall`] and [`Command::is_multicall_set`]
#[deprecated(
since = "3.1.0",
note = "Replaced with `App::multicall` and `App::is_multicall_set`"
note = "Replaced with `Command::multicall` and `Command::is_multicall_set`"
)]
#[cfg(feature = "unstable-multicall")]
Multicall,
/// Deprecated, replaced with [`App::allow_invalid_utf8_for_external_subcommands`] and [`App::is_allow_invalid_utf8_for_external_subcommands_set`]
/// Deprecated, replaced with [`Command::allow_invalid_utf8_for_external_subcommands`] and [`Command::is_allow_invalid_utf8_for_external_subcommands_set`]
#[deprecated(
since = "3.1.0",
note = "Replaced with `App::allow_invalid_utf8_for_external_subcommands` and `App::is_allow_invalid_utf8_for_external_subcommands_set`"
note = "Replaced with `Command::allow_invalid_utf8_for_external_subcommands` and `Command::is_allow_invalid_utf8_for_external_subcommands_set`"
)]
AllowInvalidUtf8ForExternalSubcommands,
@ -167,131 +167,131 @@ pub enum AppSettings {
#[deprecated(since = "3.1.0", note = "This is now the default")]
UseLongFormatForHelpSubcommand,
/// Deprecated, replaced with [`App::subcommand_negates_reqs`] and
/// [`App::is_subcommand_negates_reqs_set`]
/// Deprecated, replaced with [`Command::subcommand_negates_reqs`] and
/// [`Command::is_subcommand_negates_reqs_set`]
#[deprecated(
since = "3.1.0",
note = "Replaced with `App::subcommand_negates_reqs` and `App::is_subcommand_negates_reqs_set`"
note = "Replaced with `Command::subcommand_negates_reqs` and `Command::is_subcommand_negates_reqs_set`"
)]
SubcommandsNegateReqs,
/// Deprecated, replaced with [`App::args_conflicts_with_subcommands`] and
/// [`App::is_args_conflicts_with_subcommands_set`]
/// Deprecated, replaced with [`Command::args_conflicts_with_subcommands`] and
/// [`Command::is_args_conflicts_with_subcommands_set`]
#[deprecated(
since = "3.1.0",
note = "Replaced with `App::args_conflicts_with_subcommands` and `App::is_args_conflicts_with_subcommands_set`"
note = "Replaced with `Command::args_conflicts_with_subcommands` and `Command::is_args_conflicts_with_subcommands_set`"
)]
ArgsNegateSubcommands,
/// Deprecated, replaced with [`App::subcommand_precedence_over_arg`] and
/// [`App::is_subcommand_precedence_over_arg_set`]
/// Deprecated, replaced with [`Command::subcommand_precedence_over_arg`] and
/// [`Command::is_subcommand_precedence_over_arg_set`]
#[deprecated(
since = "3.1.0",
note = "Replaced with `App::subcommand_precedence_over_arg` and `App::is_subcommand_precedence_over_arg_set`"
note = "Replaced with `Command::subcommand_precedence_over_arg` and `Command::is_subcommand_precedence_over_arg_set`"
)]
SubcommandPrecedenceOverArg,
/// Deprecated, replaced with [`App::arg_required_else_help`] and
/// [`App::is_arg_required_else_help_set`]
/// Deprecated, replaced with [`Command::arg_required_else_help`] and
/// [`Command::is_arg_required_else_help_set`]
#[deprecated(
since = "3.1.0",
note = "Replaced with `App::arg_required_else_help` and `App::is_arg_required_else_help_set`"
note = "Replaced with `Command::arg_required_else_help` and `Command::is_arg_required_else_help_set`"
)]
ArgRequiredElseHelp,
/// Displays the arguments and [`subcommands`] in the help message in the order that they were
/// declared in, and not alphabetically which is the default.
///
/// To override the declaration order, see [`Arg::display_order`] and [`App::display_order`].
/// To override the declaration order, see [`Arg::display_order`] and [`Command::display_order`].
///
/// # Examples
///
/// ```no_run
/// # use clap::{App, Arg, AppSettings};
/// App::new("myprog")
/// # use clap::{Command, Arg, AppSettings};
/// Command::new("myprog")
/// .global_setting(AppSettings::DeriveDisplayOrder)
/// .get_matches();
/// ```
///
/// [`subcommands`]: crate::App::subcommand()
/// [`subcommands`]: crate::Command::subcommand()
/// [`Arg::display_order`]: crate::Arg::display_order
/// [`App::display_order`]: crate::App::display_order
/// [`Command::display_order`]: crate::Command::display_order
DeriveDisplayOrder,
/// Deprecated, replaced with [`App::dont_collapse_args_in_usage`] and
/// [`App::is_dont_collapse_args_in_usage_set`]
/// Deprecated, replaced with [`Command::dont_collapse_args_in_usage`] and
/// [`Command::is_dont_collapse_args_in_usage_set`]
#[deprecated(
since = "3.1.0",
note = "Replaced with `App::dont_collapse_args_in_usage` and `App::is_dont_collapse_args_in_usage_set`"
note = "Replaced with `Command::dont_collapse_args_in_usage` and `Command::is_dont_collapse_args_in_usage_set`"
)]
DontCollapseArgsInUsage,
/// Deprecated, replaced with [`App::next_line_help`] and [`App::is_next_line_help_set`]
/// Deprecated, replaced with [`Command::next_line_help`] and [`Command::is_next_line_help_set`]
#[deprecated(
since = "3.1.0",
note = "Replaced with `App::next_line_help` and `App::is_next_line_help_set`"
note = "Replaced with `Command::next_line_help` and `Command::is_next_line_help_set`"
)]
NextLineHelp,
/// Deprecated, replaced with [`App::disable_colored_help`] and
/// [`App::is_disable_colored_help_set`]
/// Deprecated, replaced with [`Command::disable_colored_help`] and
/// [`Command::is_disable_colored_help_set`]
#[deprecated(
since = "3.1.0",
note = "Replaced with `App::disable_colored_help` and `App::is_disable_colored_help_set`"
note = "Replaced with `Command::disable_colored_help` and `Command::is_disable_colored_help_set`"
)]
DisableColoredHelp,
/// Deprecated, replaced with [`App::disable_help_flag`] and [`App::is_disable_help_flag_set`]
/// Deprecated, replaced with [`Command::disable_help_flag`] and [`Command::is_disable_help_flag_set`]
#[deprecated(
since = "3.1.0",
note = "Replaced with `App::disable_help_flag` and `App::is_disable_help_flag_set`"
note = "Replaced with `Command::disable_help_flag` and `Command::is_disable_help_flag_set`"
)]
DisableHelpFlag,
/// Deprecated, replaced with [`App::disable_help_subcommand`] and
/// [`App::is_disable_help_subcommand_set`]
/// Deprecated, replaced with [`Command::disable_help_subcommand`] and
/// [`Command::is_disable_help_subcommand_set`]
#[deprecated(
since = "3.1.0",
note = "Replaced with `App::disable_help_subcommand` and `App::is_disable_help_subcommand_set`"
note = "Replaced with `Command::disable_help_subcommand` and `Command::is_disable_help_subcommand_set`"
)]
DisableHelpSubcommand,
/// Deprecated, replaced with [`App::disable_version_flag`] and
/// [`App::is_disable_version_flag_set`]
/// Deprecated, replaced with [`Command::disable_version_flag`] and
/// [`Command::is_disable_version_flag_set`]
#[deprecated(
since = "3.1.0",
note = "Replaced with `App::disable_version_flag` and `App::is_disable_version_flag_set`"
note = "Replaced with `Command::disable_version_flag` and `Command::is_disable_version_flag_set`"
)]
DisableVersionFlag,
/// Deprecated, replaced with [`App::propagate_version`] and [`App::is_propagate_version_set`]
/// Deprecated, replaced with [`Command::propagate_version`] and [`Command::is_propagate_version_set`]
#[deprecated(
since = "3.1.0",
note = "Replaced with `App::propagate_version` and `App::is_propagate_version_set`"
note = "Replaced with `Command::propagate_version` and `Command::is_propagate_version_set`"
)]
PropagateVersion,
/// Deprecated, replaced with [`App::hide`] and [`App::is_hide_set`]
/// Deprecated, replaced with [`Command::hide`] and [`Command::is_hide_set`]
#[deprecated(
since = "3.1.0",
note = "Replaced with `App::hide` and `App::is_hide_set`"
note = "Replaced with `Command::hide` and `Command::is_hide_set`"
)]
Hidden,
/// Deprecated, replaced with [`App::hide_possible_values`] and
/// Deprecated, replaced with [`Command::hide_possible_values`] and
/// [`Arg::is_hide_possible_values_set`]
#[deprecated(
since = "3.1.0",
note = "Replaced with `App::hide_possible_values` and `Arg::is_hide_possible_values_set`"
note = "Replaced with `Command::hide_possible_values` and `Arg::is_hide_possible_values_set`"
)]
HidePossibleValues,
/// Deprecated, replaced with [`App::help_expected`]
#[deprecated(since = "3.1.0", note = "Replaced with `App::help_expected`")]
/// Deprecated, replaced with [`Command::help_expected`]
#[deprecated(since = "3.1.0", note = "Replaced with `Command::help_expected`")]
HelpExpected,
/// Deprecated, replaced with [`App::no_binary_name`]
#[deprecated(since = "3.1.0", note = "Replaced with `App::no_binary_name`")]
/// Deprecated, replaced with [`Command::no_binary_name`]
#[deprecated(since = "3.1.0", note = "Replaced with `Command::no_binary_name`")]
NoBinaryName,
/// Treat the auto-generated `-h, --help` flags like any other flag, and *not* print the help
@ -300,8 +300,8 @@ pub enum AppSettings {
/// This allows one to handle printing of the help message manually.
///
/// ```rust
/// # use clap::{App, AppSettings};
/// let result = App::new("myprog")
/// # use clap::{Command, AppSettings};
/// let result = Command::new("myprog")
/// .setting(AppSettings::NoAutoHelp)
/// .try_get_matches_from("myprog --help".split(" "));
///
@ -321,8 +321,8 @@ pub enum AppSettings {
/// This allows one to handle printing of the version message manually.
///
/// ```rust
/// # use clap::{App, AppSettings};
/// let result = App::new("myprog")
/// # use clap::{Command, AppSettings};
/// let result = Command::new("myprog")
/// .version("3.0")
/// .setting(AppSettings::NoAutoVersion)
/// .try_get_matches_from("myprog --version".split(" "));
@ -363,18 +363,18 @@ pub enum AppSettings {
#[doc(hidden)]
ColoredHelp,
/// Deprecated, see [`App::color`][crate::App::color]
#[deprecated(since = "3.0.0", note = "Replaced with `App::color`")]
/// Deprecated, see [`Command::color`][crate::Command::color]
#[deprecated(since = "3.0.0", note = "Replaced with `Command::color`")]
#[doc(hidden)]
ColorAuto,
/// Deprecated, replaced with [`App::color`][crate::App::color]
#[deprecated(since = "3.0.0", note = "Replaced with `App::color`")]
/// Deprecated, replaced with [`Command::color`][crate::Command::color]
#[deprecated(since = "3.0.0", note = "Replaced with `Command::color`")]
#[doc(hidden)]
ColorAlways,
/// Deprecated, replaced with [`App::color`][crate::App::color]
#[deprecated(since = "3.0.0", note = "Replaced with `App::color`")]
/// Deprecated, replaced with [`Command::color`][crate::Command::color]
#[deprecated(since = "3.0.0", note = "Replaced with `Command::color`")]
#[doc(hidden)]
ColorNever,
@ -412,11 +412,11 @@ pub enum AppSettings {
#[doc(hidden)]
UnifiedHelp,
/// If the app is already built, used for caching.
/// If the cmd is already built, used for caching.
#[doc(hidden)]
Built,
/// If the app's bin name is already built, used for caching.
/// If the cmd's bin name is already built, used for caching.
#[doc(hidden)]
BinNameBuilt,
}

View file

@ -1,48 +0,0 @@
use crate::App;
#[test]
fn propagate_version() {
let mut app = App::new("test")
.propagate_version(true)
.version("1.1")
.subcommand(App::new("sub1"));
app._propagate();
assert_eq!(
app.get_subcommands().next().unwrap().get_version(),
Some("1.1")
);
}
#[test]
fn global_setting() {
let mut app = App::new("test")
.disable_version_flag(true)
.subcommand(App::new("subcmd"));
app._propagate();
assert!(app
.get_subcommands()
.find(|s| s.get_name() == "subcmd")
.unwrap()
.is_disable_version_flag_set());
}
// This test will *fail to compile* if App is not Send + Sync
#[test]
fn app_send_sync() {
fn foo<T: Send + Sync>(_: T) {}
foo(App::new("test"))
}
#[test]
fn issue_2090() {
let mut app = App::new("app")
.disable_version_flag(true)
.subcommand(App::new("sub"));
app._build();
assert!(app
.get_subcommands()
.next()
.unwrap()
.is_disable_version_flag_set());
}

File diff suppressed because it is too large Load diff

View file

@ -37,8 +37,8 @@ use yaml_rust::Yaml;
/// the arguments from the specified group is present at runtime.
///
/// ```rust
/// # use clap::{App, arg, ArgGroup, ErrorKind};
/// let result = App::new("app")
/// # use clap::{Command, arg, ArgGroup, ErrorKind};
/// let result = Command::new("cmd")
/// .arg(arg!(--"set-ver" <ver> "set the version manually").required(false))
/// .arg(arg!(--major "auto increase major"))
/// .arg(arg!(--minor "auto increase minor"))
@ -46,7 +46,7 @@ use yaml_rust::Yaml;
/// .group(ArgGroup::new("vers")
/// .args(&["set-ver", "major", "minor", "patch"])
/// .required(true))
/// .try_get_matches_from(vec!["app", "--major", "--patch"]);
/// .try_get_matches_from(vec!["cmd", "--major", "--patch"]);
/// // Because we used two args in the group it's an error
/// assert!(result.is_err());
/// let err = result.unwrap_err();
@ -55,8 +55,8 @@ use yaml_rust::Yaml;
/// This next example shows a passing parse of the same scenario
///
/// ```rust
/// # use clap::{App, arg, ArgGroup};
/// let result = App::new("app")
/// # use clap::{Command, arg, ArgGroup};
/// let result = Command::new("cmd")
/// .arg(arg!(--"set-ver" <ver> "set the version manually").required(false))
/// .arg(arg!(--major "auto increase major"))
/// .arg(arg!(--minor "auto increase minor"))
@ -64,7 +64,7 @@ use yaml_rust::Yaml;
/// .group(ArgGroup::new("vers")
/// .args(&["set-ver", "major", "minor","patch"])
/// .required(true))
/// .try_get_matches_from(vec!["app", "--major"]);
/// .try_get_matches_from(vec!["cmd", "--major"]);
/// assert!(result.is_ok());
/// let matches = result.unwrap();
/// // We may not know which of the args was used, so we can test for the group...
@ -104,7 +104,7 @@ impl<'help> ArgGroup<'help> {
/// # Examples
///
/// ```rust
/// # use clap::{App, ArgGroup};
/// # use clap::{Command, ArgGroup};
/// ArgGroup::new("config")
/// # ;
/// ```
@ -117,7 +117,7 @@ impl<'help> ArgGroup<'help> {
/// # Examples
///
/// ```rust
/// # use clap::{App, ArgGroup};
/// # use clap::{Command, ArgGroup};
/// ArgGroup::default().name("config")
/// # ;
/// ```
@ -139,8 +139,8 @@ impl<'help> ArgGroup<'help> {
/// # Examples
///
/// ```rust
/// # use clap::{App, Arg, ArgGroup};
/// let m = App::new("myprog")
/// # use clap::{Command, Arg, ArgGroup};
/// let m = Command::new("myprog")
/// .arg(Arg::new("flag")
/// .short('f'))
/// .arg(Arg::new("color")
@ -166,8 +166,8 @@ impl<'help> ArgGroup<'help> {
/// # Examples
///
/// ```rust
/// # use clap::{App, Arg, ArgGroup};
/// let m = App::new("myprog")
/// # use clap::{Command, Arg, ArgGroup};
/// let m = Command::new("myprog")
/// .arg(Arg::new("flag")
/// .short('f'))
/// .arg(Arg::new("color")
@ -197,8 +197,8 @@ impl<'help> ArgGroup<'help> {
/// group
///
/// ```rust
/// # use clap::{App, Arg, ArgGroup};
/// let m = App::new("myprog")
/// # use clap::{Command, Arg, ArgGroup};
/// let m = Command::new("myprog")
/// .arg(Arg::new("flag")
/// .short('f'))
/// .arg(Arg::new("color")
@ -214,8 +214,8 @@ impl<'help> ArgGroup<'help> {
/// an error if more than one of the args in the group was used.
///
/// ```rust
/// # use clap::{App, Arg, ArgGroup, ErrorKind};
/// let result = App::new("myprog")
/// # use clap::{Command, Arg, ArgGroup, ErrorKind};
/// let result = Command::new("myprog")
/// .arg(Arg::new("flag")
/// .short('f'))
/// .arg(Arg::new("color")
@ -242,7 +242,7 @@ impl<'help> ArgGroup<'help> {
/// This is unless conflicting with another argument. A required group will be displayed in
/// the usage string of the application in the format `<arg|arg2|arg3>`.
///
/// **NOTE:** This setting only applies to the current [`App`] / [`Subcommand`]s, and not
/// **NOTE:** This setting only applies to the current [`Command`] / [`Subcommand`]s, and not
/// globally.
///
/// **NOTE:** By default, [`ArgGroup::multiple`] is set to `false` which when combined with
@ -253,8 +253,8 @@ impl<'help> ArgGroup<'help> {
/// # Examples
///
/// ```rust
/// # use clap::{App, Arg, ArgGroup, ErrorKind};
/// let result = App::new("myprog")
/// # use clap::{Command, Arg, ArgGroup, ErrorKind};
/// let result = Command::new("myprog")
/// .arg(Arg::new("flag")
/// .short('f'))
/// .arg(Arg::new("color")
@ -271,7 +271,7 @@ impl<'help> ArgGroup<'help> {
///
/// [`Subcommand`]: crate::Subcommand
/// [`ArgGroup::multiple`]: ArgGroup::multiple()
/// [`App`]: crate::App
/// [`Command`]: crate::Command
#[inline]
#[must_use]
pub fn required(mut self, yes: bool) -> Self {
@ -290,8 +290,8 @@ impl<'help> ArgGroup<'help> {
/// # Examples
///
/// ```rust
/// # use clap::{App, Arg, ArgGroup, ErrorKind};
/// let result = App::new("myprog")
/// # use clap::{Command, Arg, ArgGroup, ErrorKind};
/// let result = Command::new("myprog")
/// .arg(Arg::new("flag")
/// .short('f'))
/// .arg(Arg::new("color")
@ -327,8 +327,8 @@ impl<'help> ArgGroup<'help> {
/// # Examples
///
/// ```rust
/// # use clap::{App, Arg, ArgGroup, ErrorKind};
/// let result = App::new("myprog")
/// # use clap::{Command, Arg, ArgGroup, ErrorKind};
/// let result = Command::new("myprog")
/// .arg(Arg::new("flag")
/// .short('f'))
/// .arg(Arg::new("color")
@ -368,8 +368,8 @@ impl<'help> ArgGroup<'help> {
/// # Examples
///
/// ```rust
/// # use clap::{App, Arg, ArgGroup, ErrorKind};
/// let result = App::new("myprog")
/// # use clap::{Command, Arg, ArgGroup, ErrorKind};
/// let result = Command::new("myprog")
/// .arg(Arg::new("flag")
/// .short('f'))
/// .arg(Arg::new("color")
@ -402,8 +402,8 @@ impl<'help> ArgGroup<'help> {
/// # Examples
///
/// ```rust
/// # use clap::{App, Arg, ArgGroup, ErrorKind};
/// let result = App::new("myprog")
/// # use clap::{Command, Arg, ArgGroup, ErrorKind};
/// let result = Command::new("myprog")
/// .arg(Arg::new("flag")
/// .short('f'))
/// .arg(Arg::new("color")

View file

@ -1,8 +0,0 @@
use crate::Arg;
// This test will *fail to compile* if Arg is not Send + Sync
#[test]
fn arg_send_sync() {
fn foo<T: Send + Sync>(_: T) {}
foo(Arg::new("test"))
}

File diff suppressed because it is too large Load diff

View file

@ -3,55 +3,55 @@ use std::cmp::Ordering;
use crate::build::arg::ArgProvider;
use crate::mkeymap::KeyType;
use crate::util::Id;
use crate::{App, AppSettings, Arg, ValueHint};
use crate::{AppSettings, Arg, Command, ValueHint};
pub(crate) fn assert_app(app: &App) {
debug!("App::_debug_asserts");
pub(crate) fn assert_app(cmd: &Command) {
debug!("Command::_debug_asserts");
let mut short_flags = vec![];
let mut long_flags = vec![];
// Invalid version flag settings
if app.get_version().is_none() && app.get_long_version().is_none() {
if cmd.get_version().is_none() && cmd.get_long_version().is_none() {
// PropagateVersion is meaningless if there is no version
assert!(
!app.is_propagate_version_set(),
"App {}: No version information via App::version or App::long_version to propagate",
app.get_name(),
!cmd.is_propagate_version_set(),
"Command {}: No version information via Command::version or Command::long_version to propagate",
cmd.get_name(),
);
// Used `App::mut_arg("version", ..) but did not provide any version information to display
let has_mutated_version = app
// Used `Command::mut_arg("version", ..) but did not provide any version information to display
let has_mutated_version = cmd
.get_arguments()
.any(|x| x.id == Id::version_hash() && x.provider == ArgProvider::GeneratedMutated);
if has_mutated_version {
assert!(app.is_set(AppSettings::NoAutoVersion),
"App {}: Used App::mut_arg(\"version\", ..) without providing App::version, App::long_version or using AppSettings::NoAutoVersion"
,app.get_name()
assert!(cmd.is_set(AppSettings::NoAutoVersion),
"Command {}: Used Command::mut_arg(\"version\", ..) without providing Command::version, Command::long_version or using AppSettings::NoAutoVersion"
,cmd.get_name()
);
}
}
for sc in app.get_subcommands() {
for sc in cmd.get_subcommands() {
if let Some(s) = sc.get_short_flag().as_ref() {
short_flags.push(Flag::App(format!("-{}", s), sc.get_name()));
short_flags.push(Flag::Command(format!("-{}", s), sc.get_name()));
}
for short_alias in sc.get_all_short_flag_aliases() {
short_flags.push(Flag::App(format!("-{}", short_alias), sc.get_name()));
short_flags.push(Flag::Command(format!("-{}", short_alias), sc.get_name()));
}
if let Some(l) = sc.get_long_flag().as_ref() {
long_flags.push(Flag::App(format!("--{}", l), sc.get_name()));
long_flags.push(Flag::Command(format!("--{}", l), sc.get_name()));
}
for long_alias in sc.get_all_long_flag_aliases() {
long_flags.push(Flag::App(format!("--{}", long_alias), sc.get_name()));
long_flags.push(Flag::Command(format!("--{}", long_alias), sc.get_name()));
}
}
for arg in app.get_arguments() {
for arg in cmd.get_arguments() {
assert_arg(arg);
if let Some(s) = arg.short.as_ref() {
@ -72,19 +72,19 @@ pub(crate) fn assert_app(app: &App) {
// Name conflicts
assert!(
app.two_args_of(|x| x.id == arg.id).is_none(),
"App {}: Argument names must be unique, but '{}' is in use by more than one argument or group",
app.get_name(),
cmd.two_args_of(|x| x.id == arg.id).is_none(),
"Command {}: Argument names must be unique, but '{}' is in use by more than one argument or group",
cmd.get_name(),
arg.name,
);
// Long conflicts
if let Some(l) = arg.long {
if let Some((first, second)) = app.two_args_of(|x| x.long == Some(l)) {
if let Some((first, second)) = cmd.two_args_of(|x| x.long == Some(l)) {
panic!(
"App {}: Long option names must be unique for each argument, \
"Command {}: Long option names must be unique for each argument, \
but '--{}' is in use by both '{}' and '{}'",
app.get_name(),
cmd.get_name(),
l,
first.name,
second.name
@ -94,11 +94,11 @@ pub(crate) fn assert_app(app: &App) {
// Short conflicts
if let Some(s) = arg.short {
if let Some((first, second)) = app.two_args_of(|x| x.short == Some(s)) {
if let Some((first, second)) = cmd.two_args_of(|x| x.short == Some(s)) {
panic!(
"App {}: Short option names must be unique for each argument, \
"Command {}: Short option names must be unique for each argument, \
but '-{}' is in use by both '{}' and '{}'",
app.get_name(),
cmd.get_name(),
s,
first.name,
second.name
@ -109,14 +109,14 @@ pub(crate) fn assert_app(app: &App) {
// Index conflicts
if let Some(idx) = arg.index {
if let Some((first, second)) =
app.two_args_of(|x| x.is_positional() && x.index == Some(idx))
cmd.two_args_of(|x| x.is_positional() && x.index == Some(idx))
{
panic!(
"App {}: Argument '{}' has the same index as '{}' \
"Command {}: Argument '{}' has the same index as '{}' \
and they are both positional arguments\n\n\t \
Use Arg::multiple_values(true) to allow one \
positional argument to take multiple values",
app.get_name(),
cmd.get_name(),
first.name,
second.name
)
@ -126,9 +126,9 @@ pub(crate) fn assert_app(app: &App) {
// requires, r_if, r_unless
for req in &arg.requires {
assert!(
app.id_exists(&req.1),
"App {}: Argument or group '{:?}' specified in 'requires*' for '{}' does not exist",
app.get_name(),
cmd.id_exists(&req.1),
"Command {}: Argument or group '{:?}' specified in 'requires*' for '{}' does not exist",
cmd.get_name(),
req.1,
arg.name,
);
@ -136,9 +136,9 @@ pub(crate) fn assert_app(app: &App) {
for req in &arg.r_ifs {
assert!(
app.id_exists(&req.0),
"App {}: Argument or group '{:?}' specified in 'required_if_eq*' for '{}' does not exist",
app.get_name(),
cmd.id_exists(&req.0),
"Command {}: Argument or group '{:?}' specified in 'required_if_eq*' for '{}' does not exist",
cmd.get_name(),
req.0,
arg.name
);
@ -146,9 +146,9 @@ pub(crate) fn assert_app(app: &App) {
for req in &arg.r_ifs_all {
assert!(
app.id_exists(&req.0),
"App {}: Argument or group '{:?}' specified in 'required_if_eq_all' for '{}' does not exist",
app.get_name(),
cmd.id_exists(&req.0),
"Command {}: Argument or group '{:?}' specified in 'required_if_eq_all' for '{}' does not exist",
cmd.get_name(),
req.0,
arg.name
);
@ -156,9 +156,9 @@ pub(crate) fn assert_app(app: &App) {
for req in &arg.r_unless {
assert!(
app.id_exists(req),
"App {}: Argument or group '{:?}' specified in 'required_unless*' for '{}' does not exist",
app.get_name(),
cmd.id_exists(req),
"Command {}: Argument or group '{:?}' specified in 'required_unless*' for '{}' does not exist",
cmd.get_name(),
req,
arg.name,
);
@ -167,9 +167,9 @@ pub(crate) fn assert_app(app: &App) {
// blacklist
for req in &arg.blacklist {
assert!(
app.id_exists(req),
"App {}: Argument or group '{:?}' specified in 'conflicts_with*' for '{}' does not exist",
app.get_name(),
cmd.id_exists(req),
"Command {}: Argument or group '{:?}' specified in 'conflicts_with*' for '{}' does not exist",
cmd.get_name(),
req,
arg.name,
);
@ -178,64 +178,64 @@ pub(crate) fn assert_app(app: &App) {
if arg.is_last_set() {
assert!(
arg.long.is_none(),
"App {}: Flags or Options cannot have last(true) set. '{}' has both a long and last(true) set.",
app.get_name(),
"Command {}: Flags or Options cannot have last(true) set. '{}' has both a long and last(true) set.",
cmd.get_name(),
arg.name
);
assert!(
arg.short.is_none(),
"App {}: Flags or Options cannot have last(true) set. '{}' has both a short and last(true) set.",
app.get_name(),
"Command {}: Flags or Options cannot have last(true) set. '{}' has both a short and last(true) set.",
cmd.get_name(),
arg.name
);
}
assert!(
!(arg.is_required_set() && arg.is_global_set()),
"App {}: Global arguments cannot be required.\n\n\t'{}' is marked as both global and required",
app.get_name(),
"Command {}: Global arguments cannot be required.\n\n\t'{}' is marked as both global and required",
cmd.get_name(),
arg.name
);
// validators
assert!(
arg.validator.is_none() || arg.validator_os.is_none(),
"App {}: Argument '{}' has both `validator` and `validator_os` set which is not allowed",
app.get_name(),
"Command {}: Argument '{}' has both `validator` and `validator_os` set which is not allowed",
cmd.get_name(),
arg.name
);
if arg.value_hint == ValueHint::CommandWithArguments {
assert!(
arg.is_positional(),
"App {}: Argument '{}' has hint CommandWithArguments and must be positional.",
app.get_name(),
"Command {}: Argument '{}' has hint CommandWithArguments and must be positional.",
cmd.get_name(),
arg.name
);
assert!(
app.is_trailing_var_arg_set(),
"App {}: Positional argument '{}' has hint CommandWithArguments, so App must have TrailingVarArg set.",
app.get_name(),
cmd.is_trailing_var_arg_set(),
"Command {}: Positional argument '{}' has hint CommandWithArguments, so Command must have TrailingVarArg set.",
cmd.get_name(),
arg.name
);
}
}
for group in app.get_groups() {
for group in cmd.get_groups() {
// Name conflicts
assert!(
app.get_groups().filter(|x| x.id == group.id).count() < 2,
"App {}: Argument group name must be unique\n\n\t'{}' is already in use",
app.get_name(),
cmd.get_groups().filter(|x| x.id == group.id).count() < 2,
"Command {}: Argument group name must be unique\n\n\t'{}' is already in use",
cmd.get_name(),
group.name,
);
// Groups should not have naming conflicts with Args
assert!(
!app.get_arguments().any(|x| x.id == group.id),
"App {}: Argument group name '{}' must not conflict with argument name",
app.get_name(),
!cmd.get_arguments().any(|x| x.id == group.id),
"Command {}: Argument group name '{}' must not conflict with argument name",
cmd.get_name(),
group.name,
);
@ -243,11 +243,11 @@ pub(crate) fn assert_app(app: &App) {
if group.required && !group.args.is_empty() {
assert!(
group.args.iter().any(|arg| {
app.get_arguments()
cmd.get_arguments()
.any(|x| x.id == *arg && x.default_vals.is_empty())
}),
"App {}: Argument group '{}' is required but all of it's arguments have a default value.",
app.get_name(),
"Command {}: Argument group '{}' is required but all of it's arguments have a default value.",
cmd.get_name(),
group.name
)
}
@ -255,9 +255,9 @@ pub(crate) fn assert_app(app: &App) {
for arg in &group.args {
// Args listed inside groups should exist
assert!(
app.get_arguments().any(|x| x.id == *arg),
"App {}: Argument group '{}' contains non-existent argument '{:?}'",
app.get_name(),
cmd.get_arguments().any(|x| x.id == *arg),
"Command {}: Argument group '{}' contains non-existent argument '{:?}'",
cmd.get_name(),
group.name,
arg
);
@ -272,30 +272,30 @@ pub(crate) fn assert_app(app: &App) {
detect_duplicate_flags(&long_flags, "long");
detect_duplicate_flags(&short_flags, "short");
_verify_positionals(app);
_verify_positionals(cmd);
if let Some(help_template) = app.get_help_template() {
if let Some(help_template) = cmd.get_help_template() {
assert!(
!help_template.contains("{flags}"),
"App {}: {}",
app.get_name(),
"Command {}: {}",
cmd.get_name(),
"`{flags}` template variable was removed in clap3, they are now included in `{options}`",
);
assert!(
!help_template.contains("{unified}"),
"App {}: {}",
app.get_name(),
"Command {}: {}",
cmd.get_name(),
"`{unified}` template variable was removed in clap3, use `{options}` instead"
);
}
app._panic_on_missing_help(app.is_help_expected_set());
assert_app_flags(app);
cmd._panic_on_missing_help(cmd.is_help_expected_set());
assert_app_flags(cmd);
}
#[derive(Eq)]
enum Flag<'a> {
App(String, &'a str),
Command(String, &'a str),
Arg(String, &'a str),
}
@ -310,10 +310,10 @@ impl PartialOrd for Flag<'_> {
use Flag::*;
match (self, other) {
(App(s1, _), App(s2, _))
(Command(s1, _), Command(s2, _))
| (Arg(s1, _), Arg(s2, _))
| (App(s1, _), Arg(s2, _))
| (Arg(s1, _), App(s2, _)) => {
| (Command(s1, _), Arg(s2, _))
| (Arg(s1, _), Command(s2, _)) => {
if s1 == s2 {
Some(Ordering::Equal)
} else {
@ -335,7 +335,7 @@ fn detect_duplicate_flags(flags: &[Flag], short_or_long: &str) {
for (one, two) in find_duplicates(flags) {
match (one, two) {
(App(flag, one), App(_, another)) if one != another => panic!(
(Command(flag, one), Command(_, another)) if one != another => panic!(
"the '{}' {} flag is specified for both '{}' and '{}' subcommands",
flag, short_or_long, one, another
),
@ -345,7 +345,7 @@ fn detect_duplicate_flags(flags: &[Flag], short_or_long: &str) {
short_or_long, flag, one, another
),
(Arg(flag, arg), App(_, sub)) | (App(flag, sub), Arg(_, arg)) => panic!(
(Arg(flag, arg), Command(_, sub)) | (Command(flag, sub), Arg(_, arg)) => panic!(
"the '{}' {} flag for the '{}' argument conflicts with the short flag \
for '{}' subcommand",
flag, short_or_long, arg, sub
@ -370,14 +370,14 @@ fn find_duplicates<T: PartialEq>(slice: &[T]) -> impl Iterator<Item = (&T, &T)>
})
}
fn assert_app_flags(app: &App) {
fn assert_app_flags(cmd: &Command) {
macro_rules! checker {
($a:ident requires $($b:ident)|+) => {
if app.$a() {
if cmd.$a() {
let mut s = String::new();
$(
if !app.$b() {
if !cmd.$b() {
s.push_str(&format!(" AppSettings::{} is required when AppSettings::{} is set.\n", std::stringify!($b), std::stringify!($a)));
}
)+
@ -388,17 +388,17 @@ fn assert_app_flags(app: &App) {
}
};
($a:ident conflicts $($b:ident)|+) => {
if app.$a() {
if cmd.$a() {
let mut s = String::new();
$(
if app.$b() {
if cmd.$b() {
s.push_str(&format!(" AppSettings::{} conflicts with AppSettings::{}.\n", std::stringify!($b), std::stringify!($a)));
}
)+
if !s.is_empty() {
panic!("{}\n{}", app.get_name(), s)
panic!("{}\n{}", cmd.get_name(), s)
}
}
};
@ -410,8 +410,8 @@ fn assert_app_flags(app: &App) {
}
#[cfg(debug_assertions)]
fn _verify_positionals(app: &App) -> bool {
debug!("App::_verify_positionals");
fn _verify_positionals(cmd: &Command) -> bool {
debug!("Command::_verify_positionals");
// Because you must wait until all arguments have been supplied, this is the first chance
// to make assertions on positional argument indexes
//
@ -419,7 +419,7 @@ fn _verify_positionals(app: &App) -> bool {
// positional arguments to verify there are no gaps (i.e. supplying an index of 1 and 3
// but no 2)
let highest_idx = app
let highest_idx = cmd
.get_keymap()
.keys()
.filter_map(|x| {
@ -432,7 +432,7 @@ fn _verify_positionals(app: &App) -> bool {
.max()
.unwrap_or(0);
let num_p = app.get_keymap().keys().filter(|x| x.is_position()).count();
let num_p = cmd.get_keymap().keys().filter(|x| x.is_position()).count();
assert!(
highest_idx == num_p,
@ -444,7 +444,7 @@ fn _verify_positionals(app: &App) -> bool {
// Next we verify that only the highest index has takes multiple arguments (if any)
let only_highest = |a: &Arg| a.is_multiple() && (a.index.unwrap_or(0) != highest_idx);
if app.get_positionals().any(only_highest) {
if cmd.get_positionals().any(only_highest) {
// First we make sure if there is a positional that allows multiple values
// the one before it (second to last) has one of these:
// * a value terminator
@ -453,8 +453,8 @@ fn _verify_positionals(app: &App) -> bool {
// We can't pass the closure (it.next()) to the macro directly because each call to
// find() (iterator, not macro) gets called repeatedly.
let last = &app.get_keymap()[&KeyType::Position(highest_idx)];
let second_to_last = &app.get_keymap()[&KeyType::Position(highest_idx - 1)];
let last = &cmd.get_keymap()[&KeyType::Position(highest_idx)];
let second_to_last = &cmd.get_keymap()[&KeyType::Position(highest_idx - 1)];
// Either the final positional is required
// Or the second to last has a terminator or .last(true) set
@ -477,7 +477,7 @@ fn _verify_positionals(app: &App) -> bool {
);
// Next we check how many have both Multiple and not a specific number of values set
let count = app
let count = cmd
.get_positionals()
.filter(|p| {
p.is_multiple_occurrences_set()
@ -498,12 +498,12 @@ fn _verify_positionals(app: &App) -> bool {
let mut found = false;
if app.is_allow_missing_positional_set() {
if cmd.is_allow_missing_positional_set() {
// Check that if a required positional argument is found, all positions with a lower
// index are also required.
let mut foundx2 = false;
for p in app.get_positionals() {
for p in cmd.get_positionals() {
if foundx2 && !p.is_required_set() {
assert!(
p.is_required_set(),
@ -533,7 +533,7 @@ fn _verify_positionals(app: &App) -> bool {
} else {
// Check that if a required positional argument is found, all positions with a lower
// index are also required
for p in (1..=num_p).rev().filter_map(|n| app.get_keymap().get(&n)) {
for p in (1..=num_p).rev().filter_map(|n| cmd.get_keymap().get(&n)) {
if found {
assert!(
p.is_required_set(),
@ -555,14 +555,14 @@ fn _verify_positionals(app: &App) -> bool {
}
}
assert!(
app.get_positionals().filter(|p| p.is_last_set()).count() < 2,
cmd.get_positionals().filter(|p| p.is_last_set()).count() < 2,
"Only one positional argument may have last(true) set. Found two."
);
if app
if cmd
.get_positionals()
.any(|p| p.is_last_set() && p.is_required_set())
&& app.has_subcommands()
&& !app.is_subcommand_negates_reqs_set()
&& cmd.has_subcommands()
&& !cmd.is_subcommand_negates_reqs_set()
{
panic!(
"Having a required positional argument with .last(true) set *and* child \

View file

@ -1,13 +1,12 @@
#[macro_use]
mod macros;
pub mod app;
pub mod arg;
mod app_settings;
mod arg;
mod arg_group;
mod arg_predicate;
mod arg_settings;
mod command;
mod possible_value;
mod usage_parser;
mod value_hint;
@ -19,18 +18,21 @@ mod regex;
mod debug_asserts;
#[cfg(test)]
mod app_tests;
#[cfg(test)]
mod arg_tests;
mod tests;
pub use app::App;
pub use app_settings::{AppFlags, AppSettings};
pub use arg::Arg;
pub use arg_group::ArgGroup;
pub(crate) use arg_predicate::ArgPredicate;
pub use arg_settings::{ArgFlags, ArgSettings};
pub use command::Command;
pub use possible_value::PossibleValue;
pub use value_hint::ValueHint;
#[allow(deprecated)]
pub use command::App;
#[cfg(feature = "regex")]
pub use self::regex::RegexRef;
pub(crate) use arg::display_arg_val;
pub(crate) use arg_predicate::ArgPredicate;

56
src/build/tests.rs Normal file
View file

@ -0,0 +1,56 @@
use crate::Arg;
use crate::Command;
#[test]
fn propagate_version() {
let mut cmd = Command::new("test")
.propagate_version(true)
.version("1.1")
.subcommand(Command::new("sub1"));
cmd._propagate();
assert_eq!(
cmd.get_subcommands().next().unwrap().get_version(),
Some("1.1")
);
}
#[test]
fn global_setting() {
let mut cmd = Command::new("test")
.disable_version_flag(true)
.subcommand(Command::new("subcmd"));
cmd._propagate();
assert!(cmd
.get_subcommands()
.find(|s| s.get_name() == "subcmd")
.unwrap()
.is_disable_version_flag_set());
}
// This test will *fail to compile* if Command is not Send + Sync
#[test]
fn app_send_sync() {
fn foo<T: Send + Sync>(_: T) {}
foo(Command::new("test"))
}
#[test]
fn issue_2090() {
let mut cmd = Command::new("cmd")
.disable_version_flag(true)
.subcommand(Command::new("sub"));
cmd._build();
assert!(cmd
.get_subcommands()
.next()
.unwrap()
.is_disable_version_flag_set());
}
// This test will *fail to compile* if Arg is not Send + Sync
#[test]
fn arg_send_sync() {
fn foo<T: Send + Sync>(_: T) {}
foo(Arg::new("test"))
}

View file

@ -1246,8 +1246,8 @@ mod test {
#[test]
fn value_names_building_num_vals_from_usage() {
use crate::App;
let m = App::new("test")
use crate::Command;
let m = Command::new("test")
.arg(Arg::from_usage("--pos <who> <what> <why>"))
.try_get_matches_from(vec!["myprog", "--pos", "val1", "val2", "val3"]);
@ -1262,9 +1262,9 @@ mod test {
#[test]
fn issue_665() {
use crate::{error::ErrorKind, App};
use crate::{error::ErrorKind, Command};
// Verify fix for "arg_from_usage(): required values not being enforced when followed by another option"
let res = App::new("tester")
let res = Command::new("tester")
.arg(Arg::from_usage("-v, --reroll-count=[N] 'Mark the patch series as PATCH vN'"))
.arg(
Arg::from_usage("--subject-prefix [Subject-Prefix] 'Use [Subject-Prefix] instead of the standard [PATCH] prefix'")

View file

@ -48,11 +48,11 @@ pub enum ValueHint {
/// common when writing shell wrappers that execute anther command, for example `sudo` or `env`.
///
/// This hint is special, the argument must be a positional argument and have
/// [`.multiple_values(true)`] and App must use [`App::trailing_var_arg(true)`]. The result is that the
/// [`.multiple_values(true)`] and Command must use [`Command::trailing_var_arg(true)`]. The result is that the
/// command line `my_app ls -la /` will be parsed as `["ls", "-la", "/"]` and clap won't try to
/// parse the `-la` argument itself.
///
/// [`App::trailing_var_arg(true)`]: crate::App::trailing_var_arg
/// [`Command::trailing_var_arg(true)`]: crate::Command::trailing_var_arg
/// [`.multiple_values(true)`]: crate::Arg::multiple_values()
CommandWithArguments,
/// Name of a local operating system user.

View file

@ -1,14 +1,14 @@
//! This module contains traits that are usable with the `#[derive(...)].`
//! macros in [`clap_derive`].
use crate::{App, ArgMatches, Error, PossibleValue};
use crate::{ArgMatches, Command, Error, PossibleValue};
use std::ffi::OsString;
/// Parse command-line arguments into `Self`.
///
/// The primary one-stop-shop trait used to create an instance of a `clap`
/// [`App`], conduct the parsing, and turn the resulting [`ArgMatches`] back
/// [`Command`], conduct the parsing, and turn the resulting [`ArgMatches`] back
/// into concrete instance of the user struct.
///
/// This trait is primarily a convenience on top of [`FromArgMatches`] +
@ -46,11 +46,11 @@ use std::ffi::OsString;
/// }
/// ```
///
/// The equivalent [`App`] struct + `From` implementation:
/// The equivalent [`Command`] struct + `From` implementation:
///
/// ```rust
/// # use clap::{App, Arg, ArgMatches};
/// App::new("demo")
/// # use clap::{Command, Arg, ArgMatches};
/// Command::new("demo")
/// .about("My super CLI")
/// .arg(Arg::new("verbose")
/// .long("verbose")
@ -154,14 +154,14 @@ pub trait Parser: FromArgMatches + IntoApp + Sized {
.map_err(format_error::<Self>)
}
/// Deprecated, `StructOpt::clap` replaced with [`IntoApp::into_app`] (derive as part of
/// Deprecated, `StructOpt::clap` replaced with [`IntoCommand::into_app`] (derive as part of
/// [`Parser`])
#[deprecated(
since = "3.0.0",
note = "`StructOpt::clap` is replaced with `IntoApp::into_app` (derived as part of `Parser`)"
note = "`StructOpt::clap` is replaced with `IntoCommand::into_app` (derived as part of `Parser`)"
)]
#[doc(hidden)]
fn clap<'help>() -> App<'help> {
fn clap<'help>() -> Command<'help> {
<Self as IntoApp>::into_app()
}
@ -226,18 +226,18 @@ pub trait Parser: FromArgMatches + IntoApp + Sized {
}
}
/// Create an [`App`] relevant for a user-defined container.
/// Create an [`Command`] relevant for a user-defined container.
///
/// Derived as part of [`Parser`].
pub trait IntoApp: Sized {
/// Build an [`App`] that can instantiate `Self`.
/// Build an [`Command`] that can instantiate `Self`.
///
/// See [`FromArgMatches::from_arg_matches`] for instantiating `Self`.
fn into_app<'help>() -> App<'help>;
/// Build an [`App`] that can update `self`.
fn into_app<'help>() -> Command<'help>;
/// Build an [`Command`] that can update `self`.
///
/// See [`FromArgMatches::update_from_arg_matches`] for updating `self`.
fn into_app_for_update<'help>() -> App<'help>;
fn into_app_for_update<'help>() -> Command<'help>;
}
/// Converts an instance of [`ArgMatches`] to a user-defined container.
@ -313,16 +313,16 @@ pub trait FromArgMatches: Sized {
/// }
/// ```
pub trait Args: FromArgMatches + Sized {
/// Append to [`App`] so it can instantiate `Self`.
/// Append to [`Command`] so it can instantiate `Self`.
///
/// See also [`IntoApp`].
fn augment_args(app: App<'_>) -> App<'_>;
/// Append to [`App`] so it can update `self`.
fn augment_args(cmd: Command<'_>) -> Command<'_>;
/// Append to [`Command`] so it can update `self`.
///
/// This is used to implement `#[clap(flatten)]`
///
/// See also [`IntoApp`].
fn augment_args_for_update(app: App<'_>) -> App<'_>;
fn augment_args_for_update(cmd: Command<'_>) -> Command<'_>;
}
/// Parse a sub-command into a user-defined enum.
@ -357,16 +357,16 @@ pub trait Args: FromArgMatches + Sized {
/// }
/// ```
pub trait Subcommand: FromArgMatches + Sized {
/// Append to [`App`] so it can instantiate `Self`.
/// Append to [`Command`] so it can instantiate `Self`.
///
/// See also [`IntoApp`].
fn augment_subcommands(app: App<'_>) -> App<'_>;
/// Append to [`App`] so it can update `self`.
fn augment_subcommands(cmd: Command<'_>) -> Command<'_>;
/// Append to [`Command`] so it can update `self`.
///
/// This is used to implement `#[clap(flatten)]`
///
/// See also [`IntoApp`].
fn augment_subcommands_for_update(app: App<'_>) -> App<'_>;
fn augment_subcommands_for_update(cmd: Command<'_>) -> Command<'_>;
/// Test whether `Self` can parse a specific subcommand
fn has_subcommand(name: &str) -> bool;
}
@ -452,10 +452,10 @@ impl<T: Parser> Parser for Box<T> {
}
impl<T: IntoApp> IntoApp for Box<T> {
fn into_app<'help>() -> App<'help> {
fn into_app<'help>() -> Command<'help> {
<T as IntoApp>::into_app()
}
fn into_app_for_update<'help>() -> App<'help> {
fn into_app_for_update<'help>() -> Command<'help> {
<T as IntoApp>::into_app_for_update()
}
}
@ -470,20 +470,20 @@ impl<T: FromArgMatches> FromArgMatches for Box<T> {
}
impl<T: Args> Args for Box<T> {
fn augment_args(app: App<'_>) -> App<'_> {
<T as Args>::augment_args(app)
fn augment_args(cmd: Command<'_>) -> Command<'_> {
<T as Args>::augment_args(cmd)
}
fn augment_args_for_update(app: App<'_>) -> App<'_> {
<T as Args>::augment_args_for_update(app)
fn augment_args_for_update(cmd: Command<'_>) -> Command<'_> {
<T as Args>::augment_args_for_update(cmd)
}
}
impl<T: Subcommand> Subcommand for Box<T> {
fn augment_subcommands(app: App<'_>) -> App<'_> {
<T as Subcommand>::augment_subcommands(app)
fn augment_subcommands(cmd: Command<'_>) -> Command<'_> {
<T as Subcommand>::augment_subcommands(cmd)
}
fn augment_subcommands_for_update(app: App<'_>) -> App<'_> {
<T as Subcommand>::augment_subcommands_for_update(app)
fn augment_subcommands_for_update(cmd: Command<'_>) -> Command<'_> {
<T as Subcommand>::augment_subcommands_for_update(cmd)
}
fn has_subcommand(name: &str) -> bool {
<T as Subcommand>::has_subcommand(name)
@ -491,6 +491,6 @@ impl<T: Subcommand> Subcommand for Box<T> {
}
fn format_error<I: IntoApp>(err: crate::Error) -> crate::Error {
let mut app = I::into_app();
err.format(&mut app)
let mut cmd = I::into_app();
err.format(&mut cmd)
}

View file

@ -8,8 +8,8 @@ pub enum ErrorKind {
/// # Examples
///
/// ```rust
/// # use clap::{App, Arg, ErrorKind};
/// let result = App::new("prog")
/// # use clap::{Command, Arg, ErrorKind};
/// let result = Command::new("prog")
/// .arg(Arg::new("speed")
/// .possible_value("fast")
/// .possible_value("slow"))
@ -24,8 +24,8 @@ pub enum ErrorKind {
/// # Examples
///
/// ```rust
/// # use clap::{App, arg, ErrorKind};
/// let result = App::new("prog")
/// # use clap::{Command, arg, ErrorKind};
/// let result = Command::new("prog")
/// .arg(arg!(--flag "some flag"))
/// .try_get_matches_from(vec!["prog", "--other"]);
/// assert!(result.is_err());
@ -42,9 +42,9 @@ pub enum ErrorKind {
///
#[cfg_attr(not(feature = "suggestions"), doc = " ```no_run")]
#[cfg_attr(feature = "suggestions", doc = " ```")]
/// # use clap::{App, Arg, ErrorKind, };
/// let result = App::new("prog")
/// .subcommand(App::new("config")
/// # use clap::{Command, Arg, ErrorKind, };
/// let result = Command::new("prog")
/// .subcommand(Command::new("config")
/// .about("Used for configuration")
/// .arg(Arg::new("config_file")
/// .help("The configuration file to use")
@ -69,9 +69,9 @@ pub enum ErrorKind {
/// # Examples
///
/// ```rust
/// # use clap::{App, Arg, ErrorKind, };
/// let result = App::new("prog")
/// .subcommand(App::new("config")
/// # use clap::{Command, Arg, ErrorKind, };
/// let result = Command::new("prog")
/// .subcommand(Command::new("config")
/// .about("Used for configuration")
/// .arg(Arg::new("config_file")
/// .help("The configuration file to use")
@ -92,8 +92,8 @@ pub enum ErrorKind {
/// # Examples
///
/// ```rust
/// # use clap::{App, Arg, ErrorKind};
/// let res = App::new("prog")
/// # use clap::{Command, Arg, ErrorKind};
/// let res = Command::new("prog")
/// .arg(Arg::new("color")
/// .takes_value(true)
/// .forbid_empty_values(true)
@ -108,8 +108,8 @@ pub enum ErrorKind {
/// sign to provide values.
///
/// ```rust
/// # use clap::{App, Arg, ErrorKind};
/// let res = App::new("prog")
/// # use clap::{Command, Arg, ErrorKind};
/// let res = Command::new("prog")
/// .arg(Arg::new("color")
/// .takes_value(true)
/// .require_equals(true)
@ -126,7 +126,7 @@ pub enum ErrorKind {
/// # Examples
///
/// ```rust
/// # use clap::{App, Arg, ErrorKind};
/// # use clap::{Command, Arg, ErrorKind};
/// fn is_numeric(val: &str) -> Result<(), String> {
/// match val.parse::<i64>() {
/// Ok(..) => Ok(()),
@ -134,7 +134,7 @@ pub enum ErrorKind {
/// }
/// }
///
/// let result = App::new("prog")
/// let result = Command::new("prog")
/// .arg(Arg::new("num")
/// .validator(is_numeric))
/// .try_get_matches_from(vec!["prog", "NotANumber"]);
@ -149,8 +149,8 @@ pub enum ErrorKind {
/// # Examples
///
/// ```rust
/// # use clap::{App, Arg, ErrorKind};
/// let result = App::new("prog")
/// # use clap::{Command, Arg, ErrorKind};
/// let result = Command::new("prog")
/// .arg(Arg::new("arg")
/// .max_values(2))
/// .try_get_matches_from(vec!["prog", "too", "many", "values"]);
@ -166,8 +166,8 @@ pub enum ErrorKind {
/// # Examples
///
/// ```rust
/// # use clap::{App, Arg, ErrorKind};
/// let result = App::new("prog")
/// # use clap::{Command, Arg, ErrorKind};
/// let result = Command::new("prog")
/// .arg(Arg::new("some_opt")
/// .long("opt")
/// .min_values(3))
@ -184,8 +184,8 @@ pub enum ErrorKind {
/// # Examples
///
/// ```rust
/// # use clap::{App, Arg, ErrorKind};
/// let result = App::new("prog")
/// # use clap::{Command, Arg, ErrorKind};
/// let result = Command::new("prog")
/// .arg(Arg::new("verbosity")
/// .short('v')
/// .max_occurrences(2))
@ -203,8 +203,8 @@ pub enum ErrorKind {
/// # Examples
///
/// ```rust
/// # use clap::{App, Arg, ErrorKind};
/// let result = App::new("prog")
/// # use clap::{Command, Arg, ErrorKind};
/// let result = Command::new("prog")
/// .arg(Arg::new("some_opt")
/// .long("opt")
/// .takes_value(true)
@ -224,8 +224,8 @@ pub enum ErrorKind {
/// # Examples
///
/// ```rust
/// # use clap::{App, Arg, ErrorKind};
/// let result = App::new("prog")
/// # use clap::{Command, Arg, ErrorKind};
/// let result = Command::new("prog")
/// .arg(Arg::new("debug")
/// .long("debug")
/// .conflicts_with("color"))
@ -242,8 +242,8 @@ pub enum ErrorKind {
/// # Examples
///
/// ```rust
/// # use clap::{App, Arg, ErrorKind};
/// let result = App::new("prog")
/// # use clap::{Command, Arg, ErrorKind};
/// let result = Command::new("prog")
/// .arg(Arg::new("debug")
/// .required(true))
/// .try_get_matches_from(vec!["prog"]);
@ -252,16 +252,16 @@ pub enum ErrorKind {
/// ```
MissingRequiredArgument,
/// Occurs when a subcommand is required (as defined by [`App::subcommand_required`]),
/// Occurs when a subcommand is required (as defined by [`Command::subcommand_required`]),
/// but the user does not provide one.
///
/// # Examples
///
/// ```rust
/// # use clap::{App, ErrorKind};
/// let err = App::new("prog")
/// # use clap::{Command, ErrorKind};
/// let err = Command::new("prog")
/// .subcommand_required(true)
/// .subcommand(App::new("test"))
/// .subcommand(Command::new("test"))
/// .try_get_matches_from(vec![
/// "myprog",
/// ]);
@ -270,7 +270,7 @@ pub enum ErrorKind {
/// # ;
/// ```
///
/// [`App::subcommand_required`]: crate::App::subcommand_required
/// [`Command::subcommand_required`]: crate::Command::subcommand_required
MissingSubcommand,
/// Occurs when the user provides multiple values to an argument which doesn't allow that.
@ -278,8 +278,8 @@ pub enum ErrorKind {
/// # Examples
///
/// ```rust
/// # use clap::{App, Arg, ErrorKind};
/// let result = App::new("prog")
/// # use clap::{Command, Arg, ErrorKind};
/// let result = Command::new("prog")
/// .arg(Arg::new("debug")
/// .long("debug")
/// .multiple_occurrences(false))
@ -293,7 +293,7 @@ pub enum ErrorKind {
///
/// To allow arbitrary data
/// - Set [`Arg::allow_invalid_utf8`] for argument values
/// - Set [`App::allow_invalid_utf8_for_external_subcommands`] for external-subcommand
/// - Set [`Command::allow_invalid_utf8_for_external_subcommands`] for external-subcommand
/// values
///
/// # Platform Specific
@ -304,10 +304,10 @@ pub enum ErrorKind {
///
#[cfg_attr(not(unix), doc = " ```ignore")]
#[cfg_attr(unix, doc = " ```")]
/// # use clap::{App, Arg, ErrorKind};
/// # use clap::{Command, Arg, ErrorKind};
/// # use std::os::unix::ffi::OsStringExt;
/// # use std::ffi::OsString;
/// let result = App::new("prog")
/// let result = Command::new("prog")
/// .arg(Arg::new("utf8")
/// .short('u')
/// .takes_value(true))
@ -319,7 +319,7 @@ pub enum ErrorKind {
/// ```
///
/// [`Arg::allow_invalid_utf8`]: crate::Arg::allow_invalid_utf8
/// [`App::allow_invalid_utf8_for_external_subcommands`]: crate::App::allow_invalid_utf8_for_external_subcommands
/// [`Command::allow_invalid_utf8_for_external_subcommands`]: crate::Command::allow_invalid_utf8_for_external_subcommands
InvalidUtf8,
/// Not a true "error" as it means `--help` or similar was used.
@ -331,8 +331,8 @@ pub enum ErrorKind {
/// # Examples
///
/// ```rust
/// # use clap::{App, Arg, ErrorKind};
/// let result = App::new("prog")
/// # use clap::{Command, Arg, ErrorKind};
/// let result = Command::new("prog")
/// .try_get_matches_from(vec!["prog", "--help"]);
/// assert!(result.is_err());
/// assert_eq!(result.unwrap_err().kind(), ErrorKind::DisplayHelp);
@ -340,16 +340,16 @@ pub enum ErrorKind {
DisplayHelp,
/// Occurs when either an argument or a [`Subcommand`] is required, as defined by
/// [`App::arg_required_else_help`] , but the user did not provide
/// [`Command::arg_required_else_help`] , but the user did not provide
/// one.
///
/// # Examples
///
/// ```rust
/// # use clap::{App, Arg, ErrorKind, };
/// let result = App::new("prog")
/// # use clap::{Command, Arg, ErrorKind, };
/// let result = Command::new("prog")
/// .arg_required_else_help(true)
/// .subcommand(App::new("config")
/// .subcommand(Command::new("config")
/// .about("Used for configuration")
/// .arg(Arg::new("config_file")
/// .help("The configuration file to use")))
@ -359,7 +359,7 @@ pub enum ErrorKind {
/// ```
///
/// [`Subcommand`]: crate::Subcommand
/// [`App::arg_required_else_help`]: crate::App::arg_required_else_help
/// [`Command::arg_required_else_help`]: crate::Command::arg_required_else_help
DisplayHelpOnMissingArgumentOrSubcommand,
/// Not a true "error" as it means `--version` or similar was used.
@ -368,8 +368,8 @@ pub enum ErrorKind {
/// # Examples
///
/// ```rust
/// # use clap::{App, Arg, ErrorKind};
/// let result = App::new("prog")
/// # use clap::{Command, Arg, ErrorKind};
/// let result = Command::new("prog")
/// .version("3.0")
/// .try_get_matches_from(vec!["prog", "--version"]);
/// assert!(result.is_err());

View file

@ -17,7 +17,7 @@ use crate::{
output::fmt::Colorizer,
parse::features::suggestions,
util::{color::ColorChoice, safe_exit, SUCCESS_CODE, USAGE_CODE},
App, AppSettings,
AppSettings, Command,
};
mod context;
@ -34,9 +34,9 @@ pub type Result<T, E = Error> = StdResult<T, E>;
/// Command Line Argument Parser Error
///
/// See [`App::error`] to create an error.
/// See [`Command::error`] to create an error.
///
/// [`App::error`]: crate::App::error
/// [`Command::error`]: crate::Command::error
#[derive(Debug)]
pub struct Error {
inner: Box<ErrorInner>,
@ -64,24 +64,24 @@ impl Error {
/// Create an unformatted error
///
/// This is for you need to pass the error up to
/// a place that has access to the `App` at which point you can call [`Error::format`].
/// a place that has access to the `Command` at which point you can call [`Error::format`].
///
/// Prefer [`App::error`] for generating errors.
/// Prefer [`Command::error`] for generating errors.
///
/// [`App::error`]: crate::App::error
/// [`Command::error`]: crate::Command::error
pub fn raw(kind: ErrorKind, message: impl std::fmt::Display) -> Self {
Self::new(kind).set_message(message.to_string())
}
/// Format the existing message with the App's context
/// Format the existing message with the Command's context
#[must_use]
pub fn format(mut self, app: &mut App) -> Self {
app._build();
let usage = app.render_usage();
pub fn format(mut self, cmd: &mut Command) -> Self {
cmd._build();
let usage = cmd.render_usage();
if let Some(message) = self.inner.message.as_mut() {
message.format(app, usage);
message.format(cmd, usage);
}
self.with_app(app)
self.with_cmd(cmd)
}
/// Type of error for programmatic processing
@ -131,9 +131,9 @@ impl Error {
///
/// # Example
/// ```no_run
/// use clap::App;
/// use clap::Command;
///
/// match App::new("App").try_get_matches() {
/// match Command::new("Command").try_get_matches() {
/// Ok(matches) => {
/// // do_something
/// },
@ -147,10 +147,10 @@ impl Error {
self.formatted().print()
}
/// Deprecated, replaced with [`App::error`]
/// Deprecated, replaced with [`Command::error`]
///
/// [`App::error`]: crate::App::error
#[deprecated(since = "3.0.0", note = "Replaced with `App::error`")]
/// [`Command::error`]: crate::Command::error
#[deprecated(since = "3.0.0", note = "Replaced with `Command::error`")]
#[doc(hidden)]
pub fn with_description(description: String, kind: ErrorKind) -> Self {
Error::raw(kind, description)
@ -174,17 +174,17 @@ impl Error {
}
#[inline(never)]
fn for_app(kind: ErrorKind, app: &App, colorizer: Colorizer, info: Vec<String>) -> Self {
fn for_app(kind: ErrorKind, cmd: &Command, colorizer: Colorizer, info: Vec<String>) -> Self {
Self::new(kind)
.set_message(colorizer)
.with_app(app)
.with_cmd(cmd)
.set_info(info)
}
pub(crate) fn with_app(self, app: &App) -> Self {
self.set_wait_on_exit(app.is_set(AppSettings::WaitOnError))
.set_color(app.get_color())
.set_help_flag(get_help_flag(app))
pub(crate) fn with_cmd(self, cmd: &Command) -> Self {
self.set_wait_on_exit(cmd.is_set(AppSettings::WaitOnError))
.set_color(cmd.get_color())
.set_help_flag(get_help_flag(cmd))
}
pub(crate) fn set_message(mut self, message: impl Into<Message>) -> Self {
@ -246,25 +246,25 @@ impl Error {
.find_map(|(k, v)| (*k == kind).then(|| v))
}
pub(crate) fn display_help(app: &App, colorizer: Colorizer) -> Self {
Self::for_app(ErrorKind::DisplayHelp, app, colorizer, vec![])
pub(crate) fn display_help(cmd: &Command, colorizer: Colorizer) -> Self {
Self::for_app(ErrorKind::DisplayHelp, cmd, colorizer, vec![])
}
pub(crate) fn display_help_error(app: &App, colorizer: Colorizer) -> Self {
pub(crate) fn display_help_error(cmd: &Command, colorizer: Colorizer) -> Self {
Self::for_app(
ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand,
app,
cmd,
colorizer,
vec![],
)
}
pub(crate) fn display_version(app: &App, colorizer: Colorizer) -> Self {
Self::for_app(ErrorKind::DisplayVersion, app, colorizer, vec![])
pub(crate) fn display_version(cmd: &Command, colorizer: Colorizer) -> Self {
Self::for_app(ErrorKind::DisplayVersion, cmd, colorizer, vec![])
}
pub(crate) fn argument_conflict(
app: &App,
cmd: &Command,
arg: &Arg,
mut others: Vec<String>,
usage: String,
@ -276,7 +276,7 @@ impl Error {
_ => ContextValue::Strings(others),
};
Self::new(ErrorKind::ArgumentConflict)
.with_app(app)
.with_cmd(cmd)
.set_info(info)
.extend_context_unchecked([
(
@ -288,10 +288,10 @@ impl Error {
])
}
pub(crate) fn empty_value(app: &App, good_vals: &[&str], arg: &Arg, usage: String) -> Self {
pub(crate) fn empty_value(cmd: &Command, good_vals: &[&str], arg: &Arg, usage: String) -> Self {
let info = vec![arg.to_string()];
let mut err = Self::new(ErrorKind::EmptyValue)
.with_app(app)
.with_cmd(cmd)
.set_info(info)
.extend_context_unchecked([
(
@ -309,10 +309,10 @@ impl Error {
err
}
pub(crate) fn no_equals(app: &App, arg: String, usage: String) -> Self {
pub(crate) fn no_equals(cmd: &Command, arg: String, usage: String) -> Self {
let info = vec![arg.to_string()];
Self::new(ErrorKind::NoEquals)
.with_app(app)
.with_cmd(cmd)
.set_info(info)
.extend_context_unchecked([
(ContextKind::InvalidArg, ContextValue::String(arg)),
@ -321,7 +321,7 @@ impl Error {
}
pub(crate) fn invalid_value(
app: &App,
cmd: &Command,
bad_val: String,
good_vals: &[&str],
arg: &Arg,
@ -332,7 +332,7 @@ impl Error {
let suggestion = suggestions::did_you_mean(&bad_val, good_vals.iter()).pop();
let mut err = Self::new(ErrorKind::InvalidValue)
.with_app(app)
.with_cmd(cmd)
.set_info(info)
.extend_context_unchecked([
(
@ -356,7 +356,7 @@ impl Error {
}
pub(crate) fn invalid_subcommand(
app: &App,
cmd: &Command,
subcmd: String,
did_you_mean: String,
name: String,
@ -365,7 +365,7 @@ impl Error {
let info = vec![subcmd.clone()];
let suggestion = format!("{} -- {}", name, subcmd);
Self::new(ErrorKind::InvalidSubcommand)
.with_app(app)
.with_cmd(cmd)
.set_info(info)
.extend_context_unchecked([
(ContextKind::InvalidSubcommand, ContextValue::String(subcmd)),
@ -381,11 +381,11 @@ impl Error {
])
}
pub(crate) fn unrecognized_subcommand(app: &App, subcmd: String, name: String) -> Self {
pub(crate) fn unrecognized_subcommand(cmd: &Command, subcmd: String, name: String) -> Self {
let info = vec![subcmd.clone()];
let usage = format!("USAGE:\n {} <subcommands>", name);
Self::new(ErrorKind::UnrecognizedSubcommand)
.with_app(app)
.with_cmd(cmd)
.set_info(info)
.extend_context_unchecked([
(ContextKind::InvalidSubcommand, ContextValue::String(subcmd)),
@ -394,13 +394,13 @@ impl Error {
}
pub(crate) fn missing_required_argument(
app: &App,
cmd: &Command,
required: Vec<String>,
usage: String,
) -> Self {
let info = required.clone();
Self::new(ErrorKind::MissingRequiredArgument)
.with_app(app)
.with_cmd(cmd)
.set_info(info)
.extend_context_unchecked([
(ContextKind::InvalidArg, ContextValue::Strings(required)),
@ -408,10 +408,10 @@ impl Error {
])
}
pub(crate) fn missing_subcommand(app: &App, name: String, usage: String) -> Self {
pub(crate) fn missing_subcommand(cmd: &Command, name: String, usage: String) -> Self {
let info = vec![];
Self::new(ErrorKind::MissingSubcommand)
.with_app(app)
.with_cmd(cmd)
.set_info(info)
.extend_context_unchecked([
(ContextKind::InvalidSubcommand, ContextValue::String(name)),
@ -419,16 +419,16 @@ impl Error {
])
}
pub(crate) fn invalid_utf8(app: &App, usage: String) -> Self {
pub(crate) fn invalid_utf8(cmd: &Command, usage: String) -> Self {
let info = vec![];
Self::new(ErrorKind::InvalidUtf8)
.with_app(app)
.with_cmd(cmd)
.set_info(info)
.extend_context_unchecked([(ContextKind::Usage, ContextValue::String(usage))])
}
pub(crate) fn too_many_occurrences(
app: &App,
cmd: &Command,
arg: &Arg,
max_occurs: usize,
curr_occurs: usize,
@ -440,7 +440,7 @@ impl Error {
max_occurs.to_string(),
];
Self::new(ErrorKind::TooManyOccurrences)
.with_app(app)
.with_cmd(cmd)
.set_info(info)
.extend_context_unchecked([
(
@ -459,10 +459,10 @@ impl Error {
])
}
pub(crate) fn too_many_values(app: &App, val: String, arg: String, usage: String) -> Self {
pub(crate) fn too_many_values(cmd: &Command, val: String, arg: String, usage: String) -> Self {
let info = vec![arg.to_string(), val.clone()];
Self::new(ErrorKind::TooManyValues)
.with_app(app)
.with_cmd(cmd)
.set_info(info)
.extend_context_unchecked([
(ContextKind::InvalidArg, ContextValue::String(arg)),
@ -472,7 +472,7 @@ impl Error {
}
pub(crate) fn too_few_values(
app: &App,
cmd: &Command,
arg: &Arg,
min_vals: usize,
curr_vals: usize,
@ -480,7 +480,7 @@ impl Error {
) -> Self {
let info = vec![arg.to_string(), curr_vals.to_string(), min_vals.to_string()];
Self::new(ErrorKind::TooFewValues)
.with_app(app)
.with_cmd(cmd)
.set_info(info)
.extend_context_unchecked([
(
@ -515,7 +515,7 @@ impl Error {
}
pub(crate) fn wrong_number_of_values(
app: &App,
cmd: &Command,
arg: &Arg,
num_vals: usize,
curr_vals: usize,
@ -523,7 +523,7 @@ impl Error {
) -> Self {
let info = vec![arg.to_string(), curr_vals.to_string(), num_vals.to_string()];
Self::new(ErrorKind::WrongNumberOfValues)
.with_app(app)
.with_cmd(cmd)
.set_info(info)
.extend_context_unchecked([
(
@ -542,10 +542,10 @@ impl Error {
])
}
pub(crate) fn unexpected_multiple_usage(app: &App, arg: &Arg, usage: String) -> Self {
pub(crate) fn unexpected_multiple_usage(cmd: &Command, arg: &Arg, usage: String) -> Self {
let info = vec![arg.to_string()];
Self::new(ErrorKind::UnexpectedMultipleUsage)
.with_app(app)
.with_cmd(cmd)
.set_info(info)
.extend_context_unchecked([
(
@ -557,14 +557,14 @@ impl Error {
}
pub(crate) fn unknown_argument(
app: &App,
cmd: &Command,
arg: String,
did_you_mean: Option<(String, Option<String>)>,
usage: String,
) -> Self {
let info = vec![arg.to_string()];
let mut err = Self::new(ErrorKind::UnknownArgument)
.with_app(app)
.with_cmd(cmd)
.set_info(info)
.extend_context_unchecked([
(ContextKind::InvalidArg, ContextValue::String(arg)),
@ -585,10 +585,10 @@ impl Error {
err
}
pub(crate) fn unnecessary_double_dash(app: &App, arg: String, usage: String) -> Self {
pub(crate) fn unnecessary_double_dash(cmd: &Command, arg: String, usage: String) -> Self {
let info = vec![arg.to_string()];
Self::new(ErrorKind::UnknownArgument)
.with_app(app)
.with_cmd(cmd)
.set_info(info)
.extend_context_unchecked([
(ContextKind::InvalidArg, ContextValue::String(arg)),
@ -1046,10 +1046,10 @@ fn put_usage(c: &mut Colorizer, usage: impl Into<String>) {
c.none(usage);
}
fn get_help_flag(app: &App) -> Option<&'static str> {
if !app.is_disable_help_flag_set() {
fn get_help_flag(cmd: &Command) -> Option<&'static str> {
if !cmd.is_disable_help_flag_set() {
Some("--help")
} else if app.has_subcommands() && !app.is_disable_help_subcommand_set() {
} else if cmd.has_subcommands() && !cmd.is_disable_help_subcommand_set() {
Some("help")
} else {
None
@ -1087,17 +1087,17 @@ pub(crate) enum Message {
}
impl Message {
fn format(&mut self, app: &App, usage: String) {
fn format(&mut self, cmd: &Command, usage: String) {
match self {
Message::Raw(s) => {
let mut c = Colorizer::new(true, app.get_color());
let mut c = Colorizer::new(true, cmd.get_color());
let mut message = String::new();
std::mem::swap(s, &mut message);
start_error(&mut c);
c.none(message);
put_usage(&mut c, usage);
try_help(&mut c, get_help_flag(app));
try_help(&mut c, get_help_flag(cmd));
*self = Self::Formatted(c);
}
Message::Formatted(_) => {}

View file

@ -26,8 +26,9 @@
#[cfg(not(feature = "std"))]
compile_error!("`std` feature is currently required to build `clap`");
pub use crate::build::Command;
pub use crate::build::{
App, AppFlags, AppSettings, Arg, ArgFlags, ArgGroup, ArgSettings, PossibleValue, ValueHint,
AppFlags, AppSettings, Arg, ArgFlags, ArgGroup, ArgSettings, PossibleValue, ValueHint,
};
pub use crate::error::Error;
pub use crate::parse::{ArgMatches, Indices, OsValues, ValueSource, Values};
@ -38,6 +39,9 @@ pub use crate::derive::{ArgEnum, Args, FromArgMatches, IntoApp, Parser, Subcomma
pub use crate::error::{ErrorKind, Result};
#[allow(deprecated)]
pub use crate::build::App;
#[cfg(feature = "yaml")]
#[doc(hidden)]
#[deprecated(
@ -81,10 +85,10 @@ const INTERNAL_ERROR_MSG: &str = "Fatal internal error. Please consider filing a
report at https://github.com/clap-rs/clap/issues";
const INVALID_UTF8: &str = "unexpected invalid UTF-8 code point";
/// Deprecated, replaced with [`App::new`], unless you were looking for [Subcommand]
/// Deprecated, replaced with [`Command::new`], unless you were looking for [Subcommand]
#[deprecated(
since = "3.0.0",
note = "Replaced with `App::new` unless you intended the `Subcommand` trait"
note = "Replaced with `Command::new` unless you intended the `Subcommand` trait"
)]
#[doc(hidden)]
#[derive(Debug, Copy, Clone)]
@ -92,12 +96,12 @@ pub struct SubCommand {}
#[allow(deprecated)]
impl SubCommand {
/// Deprecated, replaced with [`App::new`].
/// Deprecated, replaced with [`Command::new`].
/// Did you mean Subcommand (lower-case c)?
#[deprecated(since = "3.0.0", note = "Replaced with `App::new`")]
#[deprecated(since = "3.0.0", note = "Replaced with `Command::new`")]
#[doc(hidden)]
pub fn with_name<'help>(name: &str) -> App<'help> {
App::new(name)
Command::new(name)
}
/// Deprecated in [Issue #3087](https://github.com/clap-rs/clap/issues/3087), maybe [`clap::Parser`][crate::Parser] would fit your use case?
@ -109,6 +113,6 @@ impl SubCommand {
#[doc(hidden)]
pub fn from_yaml(yaml: &yaml_rust::Yaml) -> App {
#![allow(deprecated)]
App::from_yaml(yaml)
Command::from_yaml(yaml)
}
}

View file

@ -186,9 +186,9 @@ macro_rules! arg_enum {
/// ```no_run
/// # #[macro_use]
/// # extern crate clap;
/// # use clap::App;
/// # use clap::Command;
/// # fn main() {
/// let m = App::new("app")
/// let m = Command::new("cmd")
/// .version(crate_version!())
/// .get_matches();
/// # }
@ -201,7 +201,7 @@ macro_rules! crate_version {
};
}
/// Allows you to pull the authors for the app from your Cargo.toml at
/// Allows you to pull the authors for the command from your Cargo.toml at
/// compile time in the form:
/// `"author1 lastname <author1@example.com>:author2 lastname <author2@example.com>"`
///
@ -215,9 +215,9 @@ macro_rules! crate_version {
/// ```no_run
/// # #[macro_use]
/// # extern crate clap;
/// # use clap::App;
/// # use clap::Command;
/// # fn main() {
/// let m = App::new("app")
/// let m = Command::new("cmd")
/// .author(crate_authors!("\n"))
/// .get_matches();
/// # }
@ -245,9 +245,9 @@ macro_rules! crate_authors {
/// ```no_run
/// # #[macro_use]
/// # extern crate clap;
/// # use clap::App;
/// # use clap::Command;
/// # fn main() {
/// let m = App::new("app")
/// let m = Command::new("cmd")
/// .about(crate_description!())
/// .get_matches();
/// # }
@ -267,9 +267,9 @@ macro_rules! crate_description {
/// ```no_run
/// # #[macro_use]
/// # extern crate clap;
/// # use clap::App;
/// # use clap::Command;
/// # fn main() {
/// let m = App::new(crate_name!())
/// let m = Command::new(crate_name!())
/// .get_matches();
/// # }
/// ```
@ -281,7 +281,7 @@ macro_rules! crate_name {
};
}
/// Allows you to build the `App` instance from your Cargo.toml at compile time.
/// Allows you to build the `Command` instance from your Cargo.toml at compile time.
///
/// Equivalent to using the `crate_*!` macros with their respective fields.
///
@ -308,34 +308,34 @@ macro_rules! crate_name {
#[macro_export]
macro_rules! app_from_crate {
() => {{
let mut app = $crate::App::new($crate::crate_name!()).version($crate::crate_version!());
let mut cmd = $crate::Command::new($crate::crate_name!()).version($crate::crate_version!());
let author = $crate::crate_authors!(", ");
if !author.is_empty() {
app = app.author(author)
cmd = cmd.author(author)
}
let about = $crate::crate_description!();
if !about.is_empty() {
app = app.about(about)
cmd = cmd.about(about)
}
app
cmd
}};
($sep:expr) => {{
let mut app = $crate::App::new($crate::crate_name!()).version($crate::crate_version!());
let mut cmd = $crate::Command::new($crate::crate_name!()).version($crate::crate_version!());
let author = $crate::crate_authors!($sep);
if !author.is_empty() {
app = app.author(author)
cmd = cmd.author(author)
}
let about = $crate::crate_description!();
if !about.is_empty() {
app = app.about(about)
cmd = cmd.about(about)
}
app
cmd
}};
}
@ -607,8 +607,8 @@ macro_rules! arg_impl {
/// # Examples
///
/// ```rust
/// # use clap::{App, Arg, arg};
/// App::new("prog")
/// # use clap::{Command, Arg, arg};
/// Command::new("prog")
/// .args(&[
/// arg!(--config <FILE> "a required file for the configuration and no short"),
/// arg!(-d --debug ... "turns on debugging information and allows multiples"),
@ -688,7 +688,7 @@ macro_rules! clap_app {
(@app ($builder:expr) (@subcommand $name:ident => $($tail:tt)*) $($tt:tt)*) => {
$crate::clap_app!{ @app
($builder.subcommand(
$crate::clap_app!{ @app ($crate::App::new(stringify!($name))) $($tail)* }
$crate::clap_app!{ @app ($crate::Command::new(stringify!($name))) $($tail)* }
))
$($tt)*
}
@ -780,15 +780,15 @@ macro_rules! clap_app {
// Build a subcommand outside of an app.
(@subcommand $name:ident => $($tail:tt)*) => {
$crate::clap_app!{ @app ($crate::App::new(stringify!($name))) $($tail)* }
$crate::clap_app!{ @app ($crate::Command::new(stringify!($name))) $($tail)* }
};
// Start the magic
(($name:expr) => $($tail:tt)*) => {{
$crate::clap_app!{ @app ($crate::App::new($name)) $($tail)*}
$crate::clap_app!{ @app ($crate::Command::new($name)) $($tail)*}
}};
($name:ident => $($tail:tt)*) => {{
$crate::clap_app!{ @app ($crate::App::new(stringify!($name))) $($tail)*}
$crate::clap_app!{ @app ($crate::Command::new(stringify!($name))) $($tail)*}
}};
}

View file

@ -9,7 +9,7 @@ use std::{
// Internal
use crate::{
build::{arg::display_arg_val, App, Arg},
build::{display_arg_val, Arg, Command},
output::{fmt::Colorizer, Usage},
};
@ -20,17 +20,17 @@ use textwrap::core::display_width;
/// `clap` Help Writer.
///
/// Wraps a writer stream providing different methods to generate help for `clap` objects.
pub(crate) struct Help<'help, 'app, 'writer> {
pub(crate) struct Help<'help, 'cmd, 'writer> {
writer: HelpWriter<'writer>,
app: &'app App<'help>,
usage: &'app Usage<'help, 'app>,
cmd: &'cmd Command<'help>,
usage: &'cmd Usage<'help, 'cmd>,
next_line_help: bool,
term_w: usize,
use_long: bool,
}
// Public Functions
impl<'help, 'app, 'writer> Help<'help, 'app, 'writer> {
impl<'help, 'cmd, 'writer> Help<'help, 'cmd, 'writer> {
const DEFAULT_TEMPLATE: &'static str = "\
{before-help}{bin} {version}\n\
{author-with-newline}{about-with-newline}\n\
@ -48,27 +48,27 @@ impl<'help, 'app, 'writer> Help<'help, 'app, 'writer> {
/// Create a new `Help` instance.
pub(crate) fn new(
writer: HelpWriter<'writer>,
app: &'app App<'help>,
usage: &'app Usage<'help, 'app>,
cmd: &'cmd Command<'help>,
usage: &'cmd Usage<'help, 'cmd>,
use_long: bool,
) -> Self {
debug!("Help::new");
let term_w = match app.get_term_width() {
let term_w = match cmd.get_term_width() {
Some(0) => usize::MAX,
Some(w) => w,
None => cmp::min(
dimensions().map_or(100, |(w, _)| w),
match app.get_max_term_width() {
match cmd.get_max_term_width() {
None | Some(0) => usize::MAX,
Some(mw) => mw,
},
),
};
let next_line_help = app.is_next_line_help_set();
let next_line_help = cmd.is_next_line_help_set();
Help {
writer,
app,
cmd,
usage,
next_line_help,
term_w,
@ -80,20 +80,20 @@ impl<'help, 'app, 'writer> Help<'help, 'app, 'writer> {
pub(crate) fn write_help(&mut self) -> io::Result<()> {
debug!("Help::write_help");
if let Some(h) = self.app.get_override_help() {
if let Some(h) = self.cmd.get_override_help() {
self.none(h)?;
} else if let Some(tmpl) = self.app.get_help_template() {
} else if let Some(tmpl) = self.cmd.get_help_template() {
self.write_templated_help(tmpl)?;
} else {
let pos = self
.app
.cmd
.get_positionals()
.any(|arg| should_show_arg(self.use_long, arg));
let non_pos = self
.app
.cmd
.get_non_positionals()
.any(|arg| should_show_arg(self.use_long, arg));
let subcmds = self.app.has_visible_subcommands();
let subcmds = self.cmd.has_visible_subcommands();
if non_pos || pos || subcmds {
self.write_templated_help(Self::DEFAULT_TEMPLATE)?;
@ -121,7 +121,7 @@ macro_rules! write_method {
}
// Methods to write Arg help.
impl<'help, 'app, 'writer> Help<'help, 'app, 'writer> {
impl<'help, 'cmd, 'writer> Help<'help, 'cmd, 'writer> {
#[inline(never)]
fn good<T: Into<String> + AsRef<[u8]>>(&mut self, msg: T) -> io::Result<()> {
write_method!(self, msg, good)
@ -353,11 +353,11 @@ impl<'help, 'app, 'writer> Help<'help, 'app, 'writer> {
fn write_before_help(&mut self) -> io::Result<()> {
debug!("Help::write_before_help");
let before_help = if self.use_long {
self.app
self.cmd
.get_before_long_help()
.or_else(|| self.app.get_before_help())
.or_else(|| self.cmd.get_before_help())
} else {
self.app.get_before_help()
self.cmd.get_before_help()
};
if let Some(output) = before_help {
self.none(text_wrapper(&output.replace("{n}", "\n"), self.term_w))?;
@ -369,11 +369,11 @@ impl<'help, 'app, 'writer> Help<'help, 'app, 'writer> {
fn write_after_help(&mut self) -> io::Result<()> {
debug!("Help::write_after_help");
let after_help = if self.use_long {
self.app
self.cmd
.get_after_long_help()
.or_else(|| self.app.get_after_help())
.or_else(|| self.cmd.get_after_help())
} else {
self.app.get_after_help()
self.cmd.get_after_help()
};
if let Some(output) = after_help {
self.none("\n\n")?;
@ -610,9 +610,9 @@ impl<'help, 'app, 'writer> Help<'help, 'app, 'writer> {
fn write_about(&mut self, before_new_line: bool, after_new_line: bool) -> io::Result<()> {
let about = if self.use_long {
self.app.get_long_about().or_else(|| self.app.get_about())
self.cmd.get_long_about().or_else(|| self.cmd.get_about())
} else {
self.app.get_about()
self.cmd.get_about()
};
if let Some(output) = about {
if before_new_line {
@ -627,7 +627,7 @@ impl<'help, 'app, 'writer> Help<'help, 'app, 'writer> {
}
fn write_author(&mut self, before_new_line: bool, after_new_line: bool) -> io::Result<()> {
if let Some(author) = self.app.get_author() {
if let Some(author) = self.cmd.get_author() {
if before_new_line {
self.none("\n")?;
}
@ -641,9 +641,9 @@ impl<'help, 'app, 'writer> Help<'help, 'app, 'writer> {
fn write_version(&mut self) -> io::Result<()> {
let version = self
.app
.cmd
.get_version()
.or_else(|| self.app.get_long_version());
.or_else(|| self.cmd.get_long_version());
if let Some(output) = version {
self.none(text_wrapper(output, self.term_w))?;
}
@ -652,28 +652,28 @@ impl<'help, 'app, 'writer> Help<'help, 'app, 'writer> {
}
/// Methods to write a single subcommand
impl<'help, 'app, 'writer> Help<'help, 'app, 'writer> {
impl<'help, 'cmd, 'writer> Help<'help, 'cmd, 'writer> {
fn write_subcommand(
&mut self,
sc_str: &str,
app: &App<'help>,
cmd: &Command<'help>,
next_line_help: bool,
longest: usize,
) -> io::Result<()> {
debug!("Help::write_subcommand");
let spec_vals = &self.sc_spec_vals(app);
let spec_vals = &self.sc_spec_vals(cmd);
let about = app
let about = cmd
.get_about()
.or_else(|| app.get_long_about())
.or_else(|| cmd.get_long_about())
.unwrap_or("");
self.subcmd(sc_str, next_line_help, longest)?;
self.help(false, about, spec_vals, next_line_help, longest)
}
fn sc_spec_vals(&self, a: &App) -> String {
fn sc_spec_vals(&self, a: &Command) -> String {
debug!("Help::sc_spec_vals: a={}", a.get_name());
let mut spec_vals = vec![];
if 0 < a.get_all_aliases().count() || 0 < a.get_all_short_flag_aliases().count() {
@ -704,13 +704,18 @@ impl<'help, 'app, 'writer> Help<'help, 'app, 'writer> {
spec_vals.join(" ")
}
fn subcommand_next_line_help(&self, app: &App<'help>, spec_vals: &str, longest: usize) -> bool {
fn subcommand_next_line_help(
&self,
cmd: &Command<'help>,
spec_vals: &str,
longest: usize,
) -> bool {
if self.next_line_help | self.use_long {
// setting_next_line
true
} else {
// force_next_line
let h = app.get_about().unwrap_or("");
let h = cmd.get_about().unwrap_or("");
let h_w = display_width(h) + display_width(spec_vals);
let taken = longest + 12;
self.term_w >= taken
@ -732,25 +737,25 @@ impl<'help, 'app, 'writer> Help<'help, 'app, 'writer> {
}
// Methods to write Parser help.
impl<'help, 'app, 'writer> Help<'help, 'app, 'writer> {
impl<'help, 'cmd, 'writer> Help<'help, 'cmd, 'writer> {
/// Writes help for all arguments (options, flags, args, subcommands)
/// including titles of a Parser Object to the wrapped stream.
pub(crate) fn write_all_args(&mut self) -> io::Result<()> {
debug!("Help::write_all_args");
let pos = self
.app
.cmd
.get_positionals_with_no_heading()
.filter(|arg| should_show_arg(self.use_long, arg))
.collect::<Vec<_>>();
let non_pos = self
.app
.cmd
.get_non_positionals_with_no_heading()
.filter(|arg| should_show_arg(self.use_long, arg))
.collect::<Vec<_>>();
let subcmds = self.app.has_visible_subcommands();
let subcmds = self.cmd.has_visible_subcommands();
let custom_headings = self
.app
.cmd
.get_arguments()
.filter_map(|arg| arg.get_help_heading())
.collect::<IndexSet<_>>();
@ -775,7 +780,7 @@ impl<'help, 'app, 'writer> Help<'help, 'app, 'writer> {
if !custom_headings.is_empty() {
for heading in custom_headings {
let args = self
.app
.cmd
.get_arguments()
.filter(|a| {
if let Some(help_heading) = a.get_help_heading() {
@ -803,13 +808,13 @@ impl<'help, 'app, 'writer> Help<'help, 'app, 'writer> {
}
self.warning(
self.app
self.cmd
.get_subcommand_help_heading()
.unwrap_or("SUBCOMMANDS"),
)?;
self.warning(":\n")?;
self.write_subcommands(self.app)?;
self.write_subcommands(self.cmd)?;
}
Ok(())
@ -818,7 +823,7 @@ impl<'help, 'app, 'writer> Help<'help, 'app, 'writer> {
/// Will use next line help on writing subcommands.
fn will_subcommands_wrap<'a>(
&self,
subcommands: impl IntoIterator<Item = &'a App<'help>>,
subcommands: impl IntoIterator<Item = &'a Command<'help>>,
longest: usize,
) -> bool
where
@ -834,12 +839,12 @@ impl<'help, 'app, 'writer> Help<'help, 'app, 'writer> {
}
/// Writes help for subcommands of a Parser Object to the wrapped stream.
fn write_subcommands(&mut self, app: &App<'help>) -> io::Result<()> {
fn write_subcommands(&mut self, cmd: &Command<'help>) -> io::Result<()> {
debug!("Help::write_subcommands");
// The shortest an arg can legally be is 2 (i.e. '-x')
let mut longest = 2;
let mut ord_v = Vec::new();
for subcommand in app
for subcommand in cmd
.get_subcommands()
.filter(|subcommand| should_show_subcommand(subcommand))
{
@ -858,7 +863,7 @@ impl<'help, 'app, 'writer> Help<'help, 'app, 'writer> {
debug!("Help::write_subcommands longest = {}", longest);
let next_line_help = self.will_subcommands_wrap(app.get_subcommands(), longest);
let next_line_help = self.will_subcommands_wrap(cmd.get_subcommands(), longest);
let mut first = true;
for (_, sc_str, sc) in &ord_v {
@ -876,15 +881,15 @@ impl<'help, 'app, 'writer> Help<'help, 'app, 'writer> {
fn write_bin_name(&mut self) -> io::Result<()> {
debug!("Help::write_bin_name");
let bin_name = if let Some(bn) = self.app.get_bin_name() {
let bin_name = if let Some(bn) = self.cmd.get_bin_name() {
if bn.contains(' ') {
// In case we're dealing with subcommands i.e. git mv is translated to git-mv
bn.replace(' ', "-")
} else {
text_wrapper(&self.app.get_name().replace("{n}", "\n"), self.term_w)
text_wrapper(&self.cmd.get_name().replace("{n}", "\n"), self.term_w)
}
} else {
text_wrapper(&self.app.get_name().replace("{n}", "\n"), self.term_w)
text_wrapper(&self.cmd.get_name().replace("{n}", "\n"), self.term_w)
};
self.good(&bin_name)?;
Ok(())
@ -892,12 +897,12 @@ impl<'help, 'app, 'writer> Help<'help, 'app, 'writer> {
}
// Methods to write Parser help using templates.
impl<'help, 'app, 'writer> Help<'help, 'app, 'writer> {
impl<'help, 'cmd, 'writer> Help<'help, 'cmd, 'writer> {
/// Write help to stream for the parser in the format defined by the template.
///
/// For details about the template language see [`App::help_template`].
/// For details about the template language see [`Command::help_template`].
///
/// [`App::help_template`]: App::help_template()
/// [`Command::help_template`]: Command::help_template()
fn write_templated_help(&mut self, template: &str) -> io::Result<()> {
debug!("Help::write_templated_help");
@ -975,13 +980,13 @@ impl<'help, 'app, 'writer> Help<'help, 'app, 'writer> {
"options" => {
// Include even those with a heading as we don't have a good way of
// handling help_heading in the template.
self.write_args(&self.app.get_non_positionals().collect::<Vec<_>>())?;
self.write_args(&self.cmd.get_non_positionals().collect::<Vec<_>>())?;
}
"positionals" => {
self.write_args(&self.app.get_positionals().collect::<Vec<_>>())?;
self.write_args(&self.cmd.get_positionals().collect::<Vec<_>>())?;
}
"subcommands" => {
self.write_subcommands(self.app)?;
self.write_subcommands(self.cmd)?;
}
"after-help" => {
self.write_after_help()?;
@ -1022,7 +1027,7 @@ fn should_show_arg(use_long: bool, arg: &Arg) -> bool {
|| arg.is_next_line_help_set()
}
fn should_show_subcommand(subcommand: &App) -> bool {
fn should_show_subcommand(subcommand: &Command) -> bool {
!subcommand.is_hide_set()
}

View file

@ -2,26 +2,26 @@ use indexmap::IndexSet;
// Internal
use crate::build::AppSettings as AS;
use crate::build::{App, Arg, ArgPredicate};
use crate::build::{Arg, ArgPredicate, Command};
use crate::parse::ArgMatcher;
use crate::util::ChildGraph;
use crate::util::Id;
use crate::INTERNAL_ERROR_MSG;
pub(crate) struct Usage<'help, 'app> {
app: &'app App<'help>,
required: Option<&'app ChildGraph<Id>>,
pub(crate) struct Usage<'help, 'cmd> {
cmd: &'cmd Command<'help>,
required: Option<&'cmd ChildGraph<Id>>,
}
impl<'help, 'app> Usage<'help, 'app> {
pub(crate) fn new(app: &'app App<'help>) -> Self {
impl<'help, 'cmd> Usage<'help, 'cmd> {
pub(crate) fn new(cmd: &'cmd Command<'help>) -> Self {
Usage {
app,
cmd,
required: None,
}
}
pub(crate) fn required(mut self, required: &'app ChildGraph<Id>) -> Self {
pub(crate) fn required(mut self, required: &'cmd ChildGraph<Id>) -> Self {
self.required = Some(required);
self
}
@ -39,7 +39,7 @@ impl<'help, 'app> Usage<'help, 'app> {
// Creates a usage string (*without title*) if one was not provided by the user manually.
pub(crate) fn create_usage_no_title(&self, used: &[Id]) -> String {
debug!("Usage::create_usage_no_title");
if let Some(u) = self.app.get_override_usage() {
if let Some(u) = self.cmd.get_override_usage() {
String::from(&*u)
} else if used.is_empty() {
self.create_help_usage(true)
@ -53,10 +53,10 @@ impl<'help, 'app> Usage<'help, 'app> {
debug!("Usage::create_help_usage; incl_reqs={:?}", incl_reqs);
let mut usage = String::with_capacity(75);
let name = self
.app
.cmd
.get_usage_name()
.or_else(|| self.app.get_bin_name())
.unwrap_or_else(|| self.app.get_name());
.or_else(|| self.cmd.get_bin_name())
.unwrap_or_else(|| self.cmd.get_name());
usage.push_str(name);
let req_string = if incl_reqs {
self.get_required_usage_from(&[], None, false)
@ -70,27 +70,27 @@ impl<'help, 'app> Usage<'help, 'app> {
usage.push_str(" [OPTIONS]");
}
let allow_missing_positional = self.app.is_allow_missing_positional_set();
let allow_missing_positional = self.cmd.is_allow_missing_positional_set();
if !allow_missing_positional {
usage.push_str(&req_string);
}
let has_last = self.app.get_positionals().any(|p| p.is_last_set());
let has_last = self.cmd.get_positionals().any(|p| p.is_last_set());
// places a '--' in the usage string if there are args and options
// supporting multiple values
if self
.app
.cmd
.get_non_positionals()
.any(|o| o.is_multiple_values_set())
&& self.app.get_positionals().any(|p| !p.is_required_set())
&& !(self.app.has_visible_subcommands() || self.app.is_allow_external_subcommands_set())
&& self.cmd.get_positionals().any(|p| !p.is_required_set())
&& !(self.cmd.has_visible_subcommands() || self.cmd.is_allow_external_subcommands_set())
&& !has_last
{
usage.push_str(" [--]");
}
let not_req_or_hidden =
|p: &Arg| (!p.is_required_set() || p.is_last_set()) && !p.is_hide_set();
if self.app.get_positionals().any(not_req_or_hidden) {
if self.cmd.get_positionals().any(not_req_or_hidden) {
if let Some(args_tag) = self.get_args_tag(incl_reqs) {
usage.push_str(&*args_tag);
} else {
@ -98,13 +98,13 @@ impl<'help, 'app> Usage<'help, 'app> {
}
if has_last && incl_reqs {
let pos = self
.app
.cmd
.get_positionals()
.find(|p| p.is_last_set())
.expect(INTERNAL_ERROR_MSG);
debug!("Usage::create_help_usage: '{}' has .last(true)", pos.name);
let req = pos.is_required_set();
if req && self.app.get_positionals().any(|p| !p.is_required_set()) {
if req && self.cmd.get_positionals().any(|p| !p.is_required_set()) {
usage.push_str(" -- <");
} else if req {
usage.push_str(" [--] <");
@ -125,16 +125,16 @@ impl<'help, 'app> Usage<'help, 'app> {
}
// incl_reqs is only false when this function is called recursively
if self.app.has_visible_subcommands() && incl_reqs
|| self.app.is_allow_external_subcommands_set()
if self.cmd.has_visible_subcommands() && incl_reqs
|| self.cmd.is_allow_external_subcommands_set()
{
let placeholder = self.app.get_subcommand_value_name().unwrap_or("SUBCOMMAND");
let placeholder = self.cmd.get_subcommand_value_name().unwrap_or("SUBCOMMAND");
#[allow(deprecated)]
if self.app.is_subcommand_negates_reqs_set()
|| self.app.is_args_conflicts_with_subcommands_set()
if self.cmd.is_subcommand_negates_reqs_set()
|| self.cmd.is_args_conflicts_with_subcommands_set()
{
usage.push_str("\n ");
if !self.app.is_args_conflicts_with_subcommands_set() {
if !self.cmd.is_args_conflicts_with_subcommands_set() {
usage.push_str(&*self.create_help_usage(false));
} else {
usage.push_str(&*name);
@ -142,8 +142,8 @@ impl<'help, 'app> Usage<'help, 'app> {
usage.push_str(" <");
usage.push_str(placeholder);
usage.push('>');
} else if self.app.is_subcommand_required_set()
|| self.app.is_set(AS::SubcommandRequiredElseHelp)
} else if self.cmd.is_subcommand_required_set()
|| self.cmd.is_set(AS::SubcommandRequiredElseHelp)
{
usage.push_str(" <");
usage.push_str(placeholder);
@ -171,15 +171,15 @@ impl<'help, 'app> Usage<'help, 'app> {
.fold(String::new(), |acc, s| acc + " " + s);
usage.push_str(
self.app
self.cmd
.get_usage_name()
.or_else(|| self.app.get_bin_name())
.unwrap_or_else(|| self.app.get_name()),
.or_else(|| self.cmd.get_bin_name())
.unwrap_or_else(|| self.cmd.get_name()),
);
usage.push_str(&*r_string);
if self.app.is_subcommand_required_set() {
if self.cmd.is_subcommand_required_set() {
usage.push_str(" <");
usage.push_str(self.app.get_subcommand_value_name().unwrap_or("SUBCOMMAND"));
usage.push_str(self.cmd.get_subcommand_value_name().unwrap_or("SUBCOMMAND"));
usage.push('>');
}
usage.shrink_to_fit();
@ -191,17 +191,17 @@ impl<'help, 'app> Usage<'help, 'app> {
debug!("Usage::get_args_tag; incl_reqs = {:?}", incl_reqs);
let mut count = 0;
for pos in self
.app
.cmd
.get_positionals()
.filter(|pos| !pos.is_required_set())
.filter(|pos| !pos.is_hide_set())
.filter(|pos| !pos.is_last_set())
{
debug!("Usage::get_args_tag:iter:{}", pos.name);
let required = self.app.groups_for_arg(&pos.id).any(|grp_s| {
let required = self.cmd.groups_for_arg(&pos.id).any(|grp_s| {
debug!("Usage::get_args_tag:iter:{:?}:iter:{:?}", pos.name, grp_s);
// if it's part of a required group we don't want to count it
self.app.get_groups().any(|g| g.required && (g.id == grp_s))
self.cmd.get_groups().any(|g| g.required && (g.id == grp_s))
});
if !required {
count += 1;
@ -212,23 +212,23 @@ impl<'help, 'app> Usage<'help, 'app> {
}
}
if !self.app.is_dont_collapse_args_in_usage_set() && count > 1 {
if !self.cmd.is_dont_collapse_args_in_usage_set() && count > 1 {
debug!("Usage::get_args_tag:iter: More than one, returning [ARGS]");
// [ARGS]
None
} else if count == 1 && incl_reqs {
let pos = self
.app
.cmd
.get_positionals()
.find(|pos| {
!pos.is_required_set()
&& !pos.is_hide_set()
&& !pos.is_last_set()
&& !self.app.groups_for_arg(&pos.id).any(|grp_s| {
&& !self.cmd.groups_for_arg(&pos.id).any(|grp_s| {
debug!("Usage::get_args_tag:iter:{:?}:iter:{:?}", pos.name, grp_s);
// if it's part of a required group we don't want to count it
self.app.get_groups().any(|g| g.required && (g.id == grp_s))
self.cmd.get_groups().any(|g| g.required && (g.id == grp_s))
})
})
.expect(INTERNAL_ERROR_MSG);
@ -243,13 +243,13 @@ impl<'help, 'app> Usage<'help, 'app> {
pos.name_no_brackets(),
pos.multiple_str()
))
} else if self.app.is_dont_collapse_args_in_usage_set()
&& self.app.has_positionals()
} else if self.cmd.is_dont_collapse_args_in_usage_set()
&& self.cmd.has_positionals()
&& incl_reqs
{
debug!("Usage::get_args_tag:iter: Don't collapse returning all");
Some(
self.app
self.cmd
.get_positionals()
.filter(|pos| !pos.is_required_set())
.filter(|pos| !pos.is_hide_set())
@ -261,7 +261,7 @@ impl<'help, 'app> Usage<'help, 'app> {
} else if !incl_reqs {
debug!("Usage::get_args_tag:iter: incl_reqs=false, building secondary usage string");
let highest_req_pos = self
.app
.cmd
.get_positionals()
.filter_map(|pos| {
if pos.is_required_set() && !pos.is_last_set() {
@ -271,9 +271,9 @@ impl<'help, 'app> Usage<'help, 'app> {
}
})
.max()
.unwrap_or_else(|| Some(self.app.get_positionals().count()));
.unwrap_or_else(|| Some(self.cmd.get_positionals().count()));
Some(
self.app
self.cmd
.get_positionals()
.filter(|pos| pos.index <= highest_req_pos)
.filter(|pos| !pos.is_required_set())
@ -291,7 +291,7 @@ impl<'help, 'app> Usage<'help, 'app> {
// Determines if we need the `[OPTIONS]` tag in the usage string
fn needs_options_tag(&self) -> bool {
debug!("Usage::needs_options_tag");
'outer: for f in self.app.get_non_positionals() {
'outer: for f in self.cmd.get_non_positionals() {
debug!("Usage::needs_options_tag:iter: f={}", f.name);
// Don't print `[OPTIONS]` just for help or version
@ -308,9 +308,9 @@ impl<'help, 'app> Usage<'help, 'app> {
debug!("Usage::needs_options_tag:iter Option is required");
continue;
}
for grp_s in self.app.groups_for_arg(&f.id) {
for grp_s in self.cmd.groups_for_arg(&f.id) {
debug!("Usage::needs_options_tag:iter:iter: grp_s={:?}", grp_s);
if self.app.get_groups().any(|g| g.id == grp_s && g.required) {
if self.cmd.get_groups().any(|g| g.id == grp_s && g.required) {
debug!("Usage::needs_options_tag:iter:iter: Group is required");
continue 'outer;
}
@ -348,7 +348,7 @@ impl<'help, 'app> Usage<'help, 'app> {
let required = if let Some(required) = self.required {
required
} else {
required_owned = self.app.required_graph();
required_owned = self.cmd.required_graph();
&required_owned
};
@ -367,7 +367,7 @@ impl<'help, 'app> Usage<'help, 'app> {
required.then(|| req_arg.clone())
};
for aa in self.app.unroll_arg_requires(is_relevant, a) {
for aa in self.cmd.unroll_arg_requires(is_relevant, a) {
// if we don't check for duplicates here this causes duplicate error messages
// see https://github.com/clap-rs/clap/issues/2770
unrolled_reqs.insert(aa);
@ -383,33 +383,33 @@ impl<'help, 'app> Usage<'help, 'app> {
);
let args_in_groups = self
.app
.cmd
.get_groups()
.filter(|gn| required.contains(&gn.id))
.flat_map(|g| self.app.unroll_args_in_group(&g.id))
.flat_map(|g| self.cmd.unroll_args_in_group(&g.id))
.collect::<Vec<_>>();
for a in unrolled_reqs
.iter()
.chain(incls.iter())
.filter(|name| !self.app.get_positionals().any(|p| &&p.id == name))
.filter(|name| !self.app.get_groups().any(|g| &&g.id == name))
.filter(|name| !self.cmd.get_positionals().any(|p| &&p.id == name))
.filter(|name| !self.cmd.get_groups().any(|g| &&g.id == name))
.filter(|name| !args_in_groups.contains(name))
.filter(|name| !(matcher.is_some() && matcher.as_ref().unwrap().contains(name)))
{
debug!("Usage::get_required_usage_from:iter:{:?}", a);
let arg = self.app.find(a).expect(INTERNAL_ERROR_MSG).to_string();
let arg = self.cmd.find(a).expect(INTERNAL_ERROR_MSG).to_string();
ret_val.push(arg);
}
let mut g_vec: Vec<String> = vec![];
for g in unrolled_reqs
.iter()
.filter(|n| self.app.get_groups().any(|g| g.id == **n))
.filter(|n| self.cmd.get_groups().any(|g| g.id == **n))
{
// don't print requirement for required groups that have an arg.
if let Some(m) = matcher {
let have_group_entry = self
.app
.cmd
.unroll_args_in_group(g)
.iter()
.any(|arg| m.contains(arg));
@ -418,7 +418,7 @@ impl<'help, 'app> Usage<'help, 'app> {
}
}
let elem = self.app.format_group(g);
let elem = self.cmd.format_group(g);
if !g_vec.contains(&elem) {
g_vec.push(elem);
}
@ -428,9 +428,9 @@ impl<'help, 'app> Usage<'help, 'app> {
let mut pvec = unrolled_reqs
.iter()
.chain(incls.iter())
.filter(|a| self.app.get_positionals().any(|p| &&p.id == a))
.filter(|a| self.cmd.get_positionals().any(|p| &&p.id == a))
.filter(|&pos| matcher.map_or(true, |m| !m.contains(pos)))
.filter_map(|pos| self.app.find(pos))
.filter_map(|pos| self.cmd.find(pos))
.filter(|&pos| incl_last || !pos.is_last_set())
.filter(|pos| !args_in_groups.contains(&pos.id))
.map(|pos| (pos.index.unwrap(), pos))

View file

@ -3,7 +3,7 @@ use std::{collections::HashMap, ffi::OsString, mem, ops::Deref};
// Internal
use crate::{
build::{App, Arg, ArgPredicate},
build::{Arg, ArgPredicate, Command},
parse::{ArgMatches, MatchedArg, SubCommand, ValueSource},
util::Id,
};
@ -15,22 +15,22 @@ use indexmap::map::Entry;
pub(crate) struct ArgMatcher(ArgMatches);
impl ArgMatcher {
pub(crate) fn new(_app: &App) -> Self {
pub(crate) fn new(_cmd: &Command) -> Self {
ArgMatcher(ArgMatches {
#[cfg(debug_assertions)]
valid_args: {
let args = _app.get_arguments().map(|a| a.id.clone());
let groups = _app.get_groups().map(|g| g.id.clone());
let args = _cmd.get_arguments().map(|a| a.id.clone());
let groups = _cmd.get_groups().map(|g| g.id.clone());
args.chain(groups).collect()
},
#[cfg(debug_assertions)]
valid_subcommands: _app.get_subcommands().map(|sc| sc.get_id()).collect(),
valid_subcommands: _cmd.get_subcommands().map(|sc| sc.get_id()).collect(),
// HACK: Allow an external subcommand's ArgMatches be a stand-in for any ArgMatches
// since users can't detect it and avoid the asserts.
//
// See clap-rs/clap#3263
#[cfg(debug_assertions)]
disable_asserts: _app.is_allow_external_subcommands_set(),
disable_asserts: _cmd.is_allow_external_subcommands_set(),
..Default::default()
})
}

View file

@ -2,7 +2,7 @@
use std::cmp::Ordering;
// Internal
use crate::build::App;
use crate::build::Command;
/// Produces multiple strings from a given list of possible values which are similar
/// to the passed in value `v` within a certain confidence by least confidence.
@ -37,7 +37,7 @@ pub(crate) fn did_you_mean_flag<'a, 'help, I, T>(
arg: &str,
remaining_args: &[&str],
longs: I,
subcommands: impl IntoIterator<Item = &'a mut App<'help>>,
subcommands: impl IntoIterator<Item = &'a mut Command<'help>>,
) -> Option<(String, Option<String>)>
where
'help: 'a,

View file

@ -20,14 +20,14 @@ use crate::{Error, INVALID_UTF8};
/// Container for parse results.
///
/// 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
/// the user. New instances of this struct are obtained by using the [`Command::get_matches`] family of
/// methods.
///
/// # Examples
///
/// ```no_run
/// # use clap::{App, Arg};
/// let matches = App::new("MyApp")
/// # use clap::{Command, Arg};
/// let matches = Command::new("MyApp")
/// .arg(Arg::new("out")
/// .long("output")
/// .required(true)
@ -65,7 +65,7 @@ use crate::{Error, INVALID_UTF8};
/// }
/// }
/// ```
/// [`App::get_matches`]: crate::App::get_matches()
/// [`Command::get_matches`]: crate::Command::get_matches()
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ArgMatches {
#[cfg(debug_assertions)]
@ -84,17 +84,17 @@ impl ArgMatches {
/// # Examples
///
/// ```rust
/// # use clap::{App, Arg};
/// let mut app = App::new("myapp")
/// # use clap::{Command, Arg};
/// let mut cmd = Command::new("myapp")
/// .arg(Arg::new("output")
/// .takes_value(true));
///
/// let m = app
/// let m = cmd
/// .try_get_matches_from_mut(vec!["myapp", "something"])
/// .unwrap();
/// assert!(m.args_present());
///
/// let m = app
/// let m = cmd
/// .try_get_matches_from_mut(vec!["myapp"])
/// .unwrap();
/// assert!(! m.args_present());
@ -125,8 +125,8 @@ impl ArgMatches {
/// # Examples
///
/// ```rust
/// # use clap::{App, Arg};
/// let m = App::new("myapp")
/// # use clap::{Command, Arg};
/// let m = Command::new("myapp")
/// .arg(Arg::new("output")
/// .takes_value(true))
/// .get_matches_from(vec!["myapp", "something"]);
@ -172,11 +172,11 @@ impl ArgMatches {
///
#[cfg_attr(not(unix), doc = " ```ignore")]
#[cfg_attr(unix, doc = " ```")]
/// # use clap::{App, arg};
/// # use clap::{Command, arg};
/// use std::ffi::OsString;
/// use std::os::unix::ffi::{OsStrExt,OsStringExt};
///
/// let m = App::new("utf8")
/// let m = Command::new("utf8")
/// .arg(arg!(<arg> "some arg")
/// .allow_invalid_utf8(true))
/// .get_matches_from(vec![OsString::from("myprog"),
@ -223,11 +223,11 @@ impl ArgMatches {
///
#[cfg_attr(not(unix), doc = " ```ignore")]
#[cfg_attr(unix, doc = " ```")]
/// # use clap::{App, arg};
/// # use clap::{Command, arg};
/// use std::ffi::OsString;
/// use std::os::unix::ffi::{OsStrExt,OsStringExt};
///
/// let m = App::new("utf8")
/// let m = Command::new("utf8")
/// .arg(arg!(<arg> "some arg")
/// .allow_invalid_utf8(true))
/// .get_matches_from(vec![OsString::from("myprog"),
@ -263,8 +263,8 @@ impl ArgMatches {
/// # Examples
///
/// ```rust
/// # use clap::{App, Arg};
/// let m = App::new("myprog")
/// # use clap::{Command, Arg};
/// let m = Command::new("myprog")
/// .arg(Arg::new("output")
/// .multiple_occurrences(true)
/// .short('o')
@ -325,11 +325,11 @@ impl ArgMatches {
///
#[cfg_attr(not(unix), doc = " ```ignore")]
#[cfg_attr(unix, doc = " ```")]
/// # use clap::{App, arg};
/// # use clap::{Command, arg};
/// use std::ffi::OsString;
/// use std::os::unix::ffi::OsStringExt;
///
/// let m = App::new("utf8")
/// let m = Command::new("utf8")
/// .arg(arg!(<arg> ... "some arg")
/// .allow_invalid_utf8(true))
/// .get_matches_from(vec![OsString::from("myprog"),
@ -374,11 +374,11 @@ impl ArgMatches {
///
#[cfg_attr(not(unix), doc = " ```ignore")]
#[cfg_attr(unix, doc = " ```")]
/// # use clap::{App, arg};
/// # use clap::{Command, arg};
/// use std::ffi::{OsStr,OsString};
/// use std::os::unix::ffi::{OsStrExt,OsStringExt};
///
/// let m = App::new("utf8")
/// let m = Command::new("utf8")
/// .arg(arg!(<arg> ... "some arg")
/// .allow_invalid_utf8(true))
/// .get_matches_from(vec![OsString::from("myprog"),
@ -430,8 +430,8 @@ impl ArgMatches {
/// # Examples
///
/// ```
/// # use clap::{App, arg};
/// let matches = App::new("myapp")
/// # use clap::{Command, arg};
/// let matches = Command::new("myapp")
/// .arg(arg!([length] "Set the length to use as a pos whole num i.e. 20"))
/// .get_matches_from(&["test", "12"]);
///
@ -480,8 +480,8 @@ impl ArgMatches {
/// # Examples
///
/// ```
/// # use clap::{App, arg};
/// let matches = App::new("myapp")
/// # use clap::{Command, arg};
/// let matches = Command::new("myapp")
/// .arg(arg!([length] "Set the length to use as a pos whole num i.e. 20"))
/// .get_matches_from(&["test", "12"]);
///
@ -523,8 +523,8 @@ impl ArgMatches {
/// # Examples
///
/// ```
/// # use clap::{App, arg};
/// let matches = App::new("myapp")
/// # use clap::{Command, arg};
/// let matches = Command::new("myapp")
/// .arg(arg!([length] ... "A sequence of integers because integers are neat!"))
/// .get_matches_from(&["test", "12", "77", "40"]);
///
@ -570,8 +570,8 @@ impl ArgMatches {
/// # Examples
///
/// ```
/// # use clap::{App, arg};
/// let matches = App::new("myapp")
/// # use clap::{Command, arg};
/// let matches = Command::new("myapp")
/// .arg(arg!([length] ... "A sequence of integers because integers are neat!"))
/// .get_matches_from(&["test", "12", "77", "40"]);
///
@ -604,8 +604,8 @@ impl ArgMatches {
/// # Examples
///
/// ```rust
/// # use clap::{App, Arg};
/// let m = App::new("myprog")
/// # use clap::{Command, Arg};
/// let m = Command::new("myprog")
/// .arg(Arg::new("debug")
/// .short('d'))
/// .get_matches_from(vec![
@ -638,8 +638,8 @@ impl ArgMatches {
/// # Examples
///
/// ```rust
/// # use clap::{App, Arg};
/// let m = App::new("myprog")
/// # use clap::{Command, Arg};
/// let m = Command::new("myprog")
/// .arg(Arg::new("debug")
/// .short('d'))
/// .get_matches_from(vec![
@ -674,8 +674,8 @@ impl ArgMatches {
/// # Examples
///
/// ```rust
/// # use clap::{App, Arg};
/// let m = App::new("myprog")
/// # use clap::{Command, Arg};
/// let m = Command::new("myprog")
/// .arg(Arg::new("debug")
/// .short('d')
/// .multiple_occurrences(true))
@ -689,8 +689,8 @@ impl ArgMatches {
/// This next example shows that counts actual uses of the argument, not just `-`'s
///
/// ```rust
/// # use clap::{App, Arg};
/// let m = App::new("myprog")
/// # use clap::{Command, Arg};
/// let m = Command::new("myprog")
/// .arg(Arg::new("debug")
/// .short('d')
/// .multiple_occurrences(true))
@ -737,8 +737,8 @@ impl ArgMatches {
/// in an `ArgMatches` struct for querying.
///
/// ```rust
/// # use clap::{App, Arg};
/// let m = App::new("myapp")
/// # use clap::{Command, Arg};
/// let m = Command::new("myapp")
/// .arg(Arg::new("flag")
/// .short('f'))
/// .arg(Arg::new("option")
@ -755,8 +755,8 @@ impl ArgMatches {
/// Now notice, if we use one of the other styles of options:
///
/// ```rust
/// # use clap::{App, Arg};
/// let m = App::new("myapp")
/// # use clap::{Command, Arg};
/// let m = Command::new("myapp")
/// .arg(Arg::new("flag")
/// .short('f'))
/// .arg(Arg::new("option")
@ -774,8 +774,8 @@ impl ArgMatches {
/// flags. Let's also throw in the final option style for good measure.
///
/// ```rust
/// # use clap::{App, Arg};
/// let m = App::new("myapp")
/// # use clap::{Command, Arg};
/// let m = Command::new("myapp")
/// .arg(Arg::new("flag")
/// .short('f'))
/// .arg(Arg::new("flag2")
@ -800,8 +800,8 @@ impl ArgMatches {
/// One final combination of flags/options to see how they combine:
///
/// ```rust
/// # use clap::{App, Arg};
/// let m = App::new("myapp")
/// # use clap::{Command, Arg};
/// let m = Command::new("myapp")
/// .arg(Arg::new("flag")
/// .short('f'))
/// .arg(Arg::new("flag2")
@ -826,8 +826,8 @@ impl ArgMatches {
/// The last part to mention is when values are sent in multiple groups with a [delimiter].
///
/// ```rust
/// # use clap::{App, Arg};
/// let m = App::new("myapp")
/// # use clap::{Command, Arg};
/// let m = Command::new("myapp")
/// .arg(Arg::new("option")
/// .short('o')
/// .use_value_delimiter(true)
@ -867,8 +867,8 @@ impl ArgMatches {
/// # Examples
///
/// ```rust
/// # use clap::{App, Arg};
/// let m = App::new("myapp")
/// # use clap::{Command, Arg};
/// let m = Command::new("myapp")
/// .arg(Arg::new("option")
/// .short('o')
/// .use_value_delimiter(true)
@ -885,8 +885,8 @@ impl ArgMatches {
/// Another quick example is when flags and options are used together
///
/// ```rust
/// # use clap::{App, Arg};
/// let m = App::new("myapp")
/// # use clap::{Command, Arg};
/// let m = Command::new("myapp")
/// .arg(Arg::new("option")
/// .short('o')
/// .takes_value(true)
@ -908,8 +908,8 @@ impl ArgMatches {
/// index.
///
/// ```rust
/// # use clap::{App, Arg};
/// let m = App::new("myapp")
/// # use clap::{Command, Arg};
/// let m = Command::new("myapp")
/// .arg(Arg::new("option")
/// .short('o')
/// .takes_value(true)
@ -942,11 +942,11 @@ impl ArgMatches {
/// # Examples
///
/// ```no_run
/// # use clap::{App, Arg, };
/// let app_m = App::new("git")
/// .subcommand(App::new("clone"))
/// .subcommand(App::new("push"))
/// .subcommand(App::new("commit"))
/// # use clap::{Command, Arg, };
/// let app_m = Command::new("git")
/// .subcommand(Command::new("clone"))
/// .subcommand(Command::new("push"))
/// .subcommand(Command::new("commit"))
/// .get_matches();
///
/// match app_m.subcommand() {
@ -962,9 +962,9 @@ impl ArgMatches {
/// with pattern matching!
///
/// ```rust
/// # use clap::App;
/// # use clap::Command;
/// // Assume there is an external subcommand named "subcmd"
/// let app_m = App::new("myprog")
/// let app_m = Command::new("myprog")
/// .allow_external_subcommands(true)
/// .get_matches_from(vec![
/// "myprog", "subcmd", "--option", "value", "-fff", "--flag"
@ -981,7 +981,7 @@ impl ArgMatches {
/// _ => {},
/// }
/// ```
/// [subcommand]: crate::App::subcommand
/// [subcommand]: crate::Command::subcommand
#[inline]
pub fn subcommand(&self) -> Option<(&str, &ArgMatches)> {
self.subcommand.as_ref().map(|sc| (&*sc.name, &sc.matches))
@ -1000,11 +1000,11 @@ impl ArgMatches {
/// # Examples
///
/// ```rust
/// # use clap::{App, Arg, };
/// let app_m = App::new("myprog")
/// # use clap::{Command, Arg, };
/// let app_m = Command::new("myprog")
/// .arg(Arg::new("debug")
/// .short('d'))
/// .subcommand(App::new("test")
/// .subcommand(Command::new("test")
/// .arg(Arg::new("opt")
/// .long("option")
/// .takes_value(true)))
@ -1022,8 +1022,8 @@ impl ArgMatches {
/// }
/// ```
///
/// [subcommand]: crate::App::subcommand
/// [`App`]: crate::App
/// [subcommand]: crate::Command::subcommand
/// [`Command`]: crate::Command
pub fn subcommand_matches<T: Key>(&self, id: T) -> Option<&ArgMatches> {
self.get_subcommand(&id.into()).map(|sc| &sc.matches)
}
@ -1035,11 +1035,11 @@ impl ArgMatches {
/// # Examples
///
/// ```no_run
/// # use clap::{App, Arg, };
/// let app_m = App::new("git")
/// .subcommand(App::new("clone"))
/// .subcommand(App::new("push"))
/// .subcommand(App::new("commit"))
/// # use clap::{Command, Arg, };
/// let app_m = Command::new("git")
/// .subcommand(Command::new("clone"))
/// .subcommand(Command::new("push"))
/// .subcommand(Command::new("commit"))
/// .get_matches();
///
/// match app_m.subcommand_name() {
@ -1049,8 +1049,8 @@ impl ArgMatches {
/// _ => {}, // Either no subcommand or one not tested for...
/// }
/// ```
/// [subcommand]: crate::App::subcommand
/// [`App`]: crate::App
/// [subcommand]: crate::Command::subcommand
/// [`Command`]: crate::Command
#[inline]
pub fn subcommand_name(&self) -> Option<&str> {
self.subcommand.as_ref().map(|sc| &*sc.name)
@ -1167,8 +1167,8 @@ pub(crate) struct SubCommand {
/// # Examples
///
/// ```rust
/// # use clap::{App, Arg};
/// let m = App::new("myapp")
/// # use clap::{Command, Arg};
/// let m = Command::new("myapp")
/// .arg(Arg::new("output")
/// .short('o')
/// .multiple_occurrences(true)
@ -1264,11 +1264,11 @@ impl<'a> Default for GroupedValues<'a> {
///
#[cfg_attr(not(unix), doc = " ```ignore")]
#[cfg_attr(unix, doc = " ```")]
/// # use clap::{App, arg};
/// # use clap::{Command, arg};
/// use std::ffi::OsString;
/// use std::os::unix::ffi::{OsStrExt,OsStringExt};
///
/// let m = App::new("utf8")
/// let m = Command::new("utf8")
/// .arg(arg!(<arg> "some arg")
/// .allow_invalid_utf8(true))
/// .get_matches_from(vec![OsString::from("myprog"),
@ -1320,8 +1320,8 @@ impl Default for OsValues<'_> {
/// # Examples
///
/// ```rust
/// # use clap::{App, Arg};
/// let m = App::new("myapp")
/// # use clap::{Command, Arg};
/// let m = Command::new("myapp")
/// .arg(Arg::new("output")
/// .short('o')
/// .multiple_values(true)
@ -1438,7 +1438,7 @@ mod tests {
#[test]
fn values_exact_size() {
let l = crate::App::new("test")
let l = crate::Command::new("test")
.arg(
crate::Arg::new("POTATO")
.takes_value(true)
@ -1455,7 +1455,7 @@ mod tests {
#[test]
fn os_values_exact_size() {
let l = crate::App::new("test")
let l = crate::Command::new("test")
.arg(
crate::Arg::new("POTATO")
.takes_value(true)
@ -1473,7 +1473,7 @@ mod tests {
#[test]
fn indices_exact_size() {
let l = crate::App::new("test")
let l = crate::Command::new("test")
.arg(
crate::Arg::new("POTATO")
.takes_value(true)

View file

@ -9,7 +9,7 @@ use os_str_bytes::RawOsStr;
// Internal
use crate::build::AppSettings as AS;
use crate::build::{App, Arg};
use crate::build::{Arg, Command};
use crate::error::Error as ClapError;
use crate::error::Result as ClapResult;
use crate::mkeymap::KeyType;
@ -20,8 +20,8 @@ use crate::parse::{Validator, ValueSource};
use crate::util::{color::ColorChoice, Id};
use crate::{INTERNAL_ERROR_MSG, INVALID_UTF8};
pub(crate) struct Parser<'help, 'app> {
pub(crate) app: &'app mut App<'help>,
pub(crate) struct Parser<'help, 'cmd> {
pub(crate) cmd: &'cmd mut Command<'help>,
pub(crate) overridden: RefCell<Vec<Id>>,
seen: Vec<Id>,
cur_idx: Cell<usize>,
@ -33,10 +33,10 @@ pub(crate) struct Parser<'help, 'app> {
}
// Initializing Methods
impl<'help, 'app> Parser<'help, 'app> {
pub(crate) fn new(app: &'app mut App<'help>) -> Self {
impl<'help, 'cmd> Parser<'help, 'cmd> {
pub(crate) fn new(cmd: &'cmd mut Command<'help>) -> Self {
Parser {
app,
cmd,
overridden: Default::default(),
seen: Vec::new(),
cur_idx: Cell::new(0),
@ -48,16 +48,16 @@ impl<'help, 'app> Parser<'help, 'app> {
// Should we color the help?
pub(crate) fn color_help(&self) -> ColorChoice {
#[cfg(feature = "color")]
if self.app.is_disable_colored_help_set() {
if self.cmd.is_disable_colored_help_set() {
return ColorChoice::Never;
}
self.app.get_color()
self.cmd.get_color()
}
}
// Parsing Methods
impl<'help, 'app> Parser<'help, 'app> {
impl<'help, 'cmd> Parser<'help, 'cmd> {
// The actual parsing function
#[allow(clippy::cognitive_complexity)]
pub(crate) fn get_matches_with(
@ -80,17 +80,17 @@ impl<'help, 'app> Parser<'help, 'app> {
// Count of positional args
let positional_count = self
.app
.cmd
.get_keymap()
.keys()
.filter(|x| x.is_position())
.count();
// If any arg sets .last(true)
let contains_last = self.app.get_arguments().any(|x| x.is_last_set());
let contains_last = self.cmd.get_arguments().any(|x| x.is_last_set());
while let Some((arg_os, remaining_args)) = it.next() {
// Recover the replaced items if any.
if let Some(replaced_items) = self.app.get_replacement(arg_os) {
if let Some(replaced_items) = self.cmd.get_replacement(arg_os) {
debug!(
"Parser::get_matches_with: found replacer: {:?}, target: {:?}",
arg_os, replaced_items
@ -114,16 +114,16 @@ impl<'help, 'app> Parser<'help, 'app> {
// argument may be set to .multiple_values(true) or `.multiple_occurrences(true)`
let low_index_mults = is_second_to_last
&& self
.app
.cmd
.get_positionals()
.any(|a| a.is_multiple() && (positional_count != a.index.unwrap_or(0)))
&& self
.app
.cmd
.get_positionals()
.last()
.map_or(false, |p_name| !p_name.is_last_set());
let missing_pos = self.app.is_allow_missing_positional_set()
let missing_pos = self.cmd.is_allow_missing_positional_set()
&& is_second_to_last
&& !trailing_values;
@ -139,7 +139,7 @@ impl<'help, 'app> Parser<'help, 'app> {
if low_index_mults || missing_pos {
let skip_current = if let Some(n) = remaining_args.get(0) {
if let Some(p) = self
.app
.cmd
.get_positionals()
.find(|p| p.index == Some(pos_counter))
{
@ -165,7 +165,7 @@ impl<'help, 'app> Parser<'help, 'app> {
pos_counter
}
} else if trailing_values
&& (self.app.is_allow_missing_positional_set() || contains_last)
&& (self.cmd.is_allow_missing_positional_set() || contains_last)
{
// Came to -- and one positional has .last(true) set, so we go immediately
// to the last (highest index) positional
@ -178,7 +178,7 @@ impl<'help, 'app> Parser<'help, 'app> {
// Has the user already passed '--'? Meaning only positional args follow
if !trailing_values {
if self.app.is_subcommand_precedence_over_arg_set()
if self.cmd.is_subcommand_precedence_over_arg_set()
|| !matches!(parse_state, ParseState::Opt(_) | ParseState::Pos(_))
{
// Does the arg match a subcommand name, or any of its aliases (if defined)
@ -187,7 +187,7 @@ impl<'help, 'app> Parser<'help, 'app> {
if let Some(sc_name) = sc_name {
if sc_name == "help"
&& !self.is_set(AS::NoAutoHelp)
&& !self.app.is_disable_help_subcommand_set()
&& !self.cmd.is_disable_help_subcommand_set()
{
self.parse_help_subcommand(remaining_args)?;
}
@ -232,9 +232,9 @@ impl<'help, 'app> Parser<'help, 'app> {
}
ParseResult::EqualsNotProvided { arg } => {
return Err(ClapError::no_equals(
self.app,
self.cmd,
arg,
Usage::new(self.app).create_usage_with_title(&[]),
Usage::new(self.cmd).create_usage_with_title(&[]),
));
}
ParseResult::NoMatchingArg { arg } => {
@ -246,10 +246,10 @@ impl<'help, 'app> Parser<'help, 'app> {
}
ParseResult::UnneededAttachedValue { rest, used, arg } => {
return Err(ClapError::too_many_values(
self.app,
self.cmd,
rest,
arg,
Usage::new(self.app).create_usage_no_title(&used),
Usage::new(self.cmd).create_usage_no_title(&used),
))
}
ParseResult::HelpFlag => {
@ -321,17 +321,17 @@ impl<'help, 'app> Parser<'help, 'app> {
}
ParseResult::EqualsNotProvided { arg } => {
return Err(ClapError::no_equals(
self.app,
self.cmd,
arg,
Usage::new(self.app).create_usage_with_title(&[]),
Usage::new(self.cmd).create_usage_with_title(&[]),
))
}
ParseResult::NoMatchingArg { arg } => {
return Err(ClapError::unknown_argument(
self.app,
self.cmd,
arg,
None,
Usage::new(self.app).create_usage_with_title(&[]),
Usage::new(self.cmd).create_usage_with_title(&[]),
));
}
ParseResult::HelpFlag => {
@ -353,7 +353,7 @@ impl<'help, 'app> Parser<'help, 'app> {
// get the option so we can check the settings
let parse_result = self.add_val_to_arg(
&self.app[id],
&self.cmd[id],
&arg_os,
matcher,
ValueSource::CommandLine,
@ -370,17 +370,17 @@ impl<'help, 'app> Parser<'help, 'app> {
}
}
if let Some(p) = self.app.get_keymap().get(&pos_counter) {
if let Some(p) = self.cmd.get_keymap().get(&pos_counter) {
if p.is_last_set() && !trailing_values {
return Err(ClapError::unknown_argument(
self.app,
self.cmd,
arg_os.to_str_lossy().into_owned(),
None,
Usage::new(self.app).create_usage_with_title(&[]),
Usage::new(self.cmd).create_usage_with_title(&[]),
));
}
if self.app.is_trailing_var_arg_set() && pos_counter == positional_count {
if self.cmd.is_trailing_var_arg_set() && pos_counter == positional_count {
trailing_values = true;
}
@ -410,29 +410,29 @@ impl<'help, 'app> Parser<'help, 'app> {
parse_state = ParseState::Pos(p.id.clone());
}
valid_arg_found = true;
} else if self.app.is_allow_external_subcommands_set() {
} else if self.cmd.is_allow_external_subcommands_set() {
// Get external subcommand name
let sc_name = match arg_os.to_str() {
Some(s) => s.to_string(),
None => {
return Err(ClapError::invalid_utf8(
self.app,
Usage::new(self.app).create_usage_with_title(&[]),
self.cmd,
Usage::new(self.cmd).create_usage_with_title(&[]),
));
}
};
// Collect the external subcommand args
let mut sc_m = ArgMatcher::new(self.app);
let mut sc_m = ArgMatcher::new(self.cmd);
while let Some((v, _)) = it.next() {
let allow_invalid_utf8 = self
.app
.cmd
.is_allow_invalid_utf8_for_external_subcommands_set();
if !allow_invalid_utf8 && v.to_str().is_none() {
return Err(ClapError::invalid_utf8(
self.app,
Usage::new(self.app).create_usage_with_title(&[]),
self.cmd,
Usage::new(self.cmd).create_usage_with_title(&[]),
));
}
sc_m.add_val_to(
@ -461,7 +461,7 @@ impl<'help, 'app> Parser<'help, 'app> {
if let Some(ref pos_sc_name) = subcmd_name {
let sc_name = self
.app
.cmd
.find_subcommand(pos_sc_name)
.expect(INTERNAL_ERROR_MSG)
.get_name()
@ -483,14 +483,14 @@ impl<'help, 'app> Parser<'help, 'app> {
// If the arg matches a subcommand name, or any of its aliases (if defined)
if self.possible_subcommand(arg_os, valid_arg_found).is_some() {
return ClapError::unnecessary_double_dash(
self.app,
self.cmd,
arg_os.to_str_lossy().into_owned(),
Usage::new(self.app).create_usage_with_title(&[]),
Usage::new(self.cmd).create_usage_with_title(&[]),
);
}
}
let candidates =
suggestions::did_you_mean(&arg_os.to_str_lossy(), self.app.all_subcommand_names());
suggestions::did_you_mean(&arg_os.to_str_lossy(), self.cmd.all_subcommand_names());
// If the argument looks like a subcommand.
if !candidates.is_empty() {
let candidates: Vec<_> = candidates
@ -498,33 +498,33 @@ impl<'help, 'app> Parser<'help, 'app> {
.map(|candidate| format!("'{}'", candidate))
.collect();
return ClapError::invalid_subcommand(
self.app,
self.cmd,
arg_os.to_str_lossy().into_owned(),
candidates.join(" or "),
self.app
self.cmd
.get_bin_name()
.unwrap_or_else(|| self.app.get_name())
.unwrap_or_else(|| self.cmd.get_name())
.to_owned(),
Usage::new(self.app).create_usage_with_title(&[]),
Usage::new(self.cmd).create_usage_with_title(&[]),
);
}
// If the argument must be a subcommand.
if !self.app.has_args() || self.app.is_infer_subcommands_set() && self.app.has_subcommands()
if !self.cmd.has_args() || self.cmd.is_infer_subcommands_set() && self.cmd.has_subcommands()
{
return ClapError::unrecognized_subcommand(
self.app,
self.cmd,
arg_os.to_str_lossy().into_owned(),
self.app
self.cmd
.get_bin_name()
.unwrap_or_else(|| self.app.get_name())
.unwrap_or_else(|| self.cmd.get_name())
.to_owned(),
);
}
ClapError::unknown_argument(
self.app,
self.cmd,
arg_os.to_str_lossy().into_owned(),
None,
Usage::new(self.app).create_usage_with_title(&[]),
Usage::new(self.cmd).create_usage_with_title(&[]),
)
}
@ -532,12 +532,12 @@ impl<'help, 'app> Parser<'help, 'app> {
fn possible_subcommand(&self, arg_os: &RawOsStr, valid_arg_found: bool) -> Option<&str> {
debug!("Parser::possible_subcommand: arg={:?}", arg_os);
if !(self.app.is_args_conflicts_with_subcommands_set() && valid_arg_found) {
if self.app.is_infer_subcommands_set() {
if !(self.cmd.is_args_conflicts_with_subcommands_set() && valid_arg_found) {
if self.cmd.is_infer_subcommands_set() {
// For subcommand `test`, we accepts it's prefix: `t`, `te`,
// `tes` and `test`.
let v = self
.app
.cmd
.all_subcommand_names()
.filter(|s| RawOsStr::from_str(s).starts_with_os(arg_os))
.collect::<Vec<_>>();
@ -549,7 +549,7 @@ impl<'help, 'app> Parser<'help, 'app> {
// If there is any ambiguity, fallback to non-infer subcommand
// search.
}
if let Some(sc) = self.app.find_subcommand(arg_os) {
if let Some(sc) = self.cmd.find_subcommand(arg_os) {
return Some(sc.get_name());
}
}
@ -559,9 +559,9 @@ impl<'help, 'app> Parser<'help, 'app> {
// Checks if the arg matches a long flag subcommand name, or any of its aliases (if defined)
fn possible_long_flag_subcommand(&self, arg_os: &RawOsStr) -> Option<&str> {
debug!("Parser::possible_long_flag_subcommand: arg={:?}", arg_os);
if self.app.is_infer_subcommands_set() {
if self.cmd.is_infer_subcommands_set() {
let options = self
.app
.cmd
.get_subcommands()
.fold(Vec::new(), |mut options, sc| {
if let Some(long) = sc.get_long_flag() {
@ -584,7 +584,7 @@ impl<'help, 'app> Parser<'help, 'app> {
return Some(sc);
}
}
} else if let Some(sc_name) = self.app.find_long_subcmd(arg_os) {
} else if let Some(sc_name) = self.cmd.find_long_subcmd(arg_os) {
return Some(sc_name);
}
None
@ -594,13 +594,13 @@ impl<'help, 'app> Parser<'help, 'app> {
debug!("Parser::parse_help_subcommand");
let mut bin_name = self
.app
.cmd
.get_bin_name()
.unwrap_or_else(|| self.app.get_name())
.unwrap_or_else(|| self.cmd.get_name())
.to_owned();
let mut sc = {
let mut sc = self.app.clone();
let mut sc = self.cmd.clone();
for cmd in cmds.iter() {
sc = if let Some(c) = sc.find_subcommand(cmd) {
@ -609,11 +609,11 @@ impl<'help, 'app> Parser<'help, 'app> {
c
} else {
return Err(ClapError::unrecognized_subcommand(
self.app,
self.cmd,
cmd.to_string_lossy().into_owned(),
self.app
self.cmd
.get_bin_name()
.unwrap_or_else(|| self.app.get_name())
.unwrap_or_else(|| self.cmd.get_name())
.to_owned(),
));
}
@ -639,9 +639,9 @@ impl<'help, 'app> Parser<'help, 'app> {
next, current_positional.name
);
if self.app.is_allow_hyphen_values_set()
|| self.app[&current_positional.id].is_allow_hyphen_values_set()
|| (self.app.is_allow_negative_numbers_set()
if self.cmd.is_allow_hyphen_values_set()
|| self.cmd[&current_positional.id].is_allow_hyphen_values_set()
|| (self.cmd.is_allow_negative_numbers_set()
&& next.to_str_lossy().parse::<f64>().is_ok())
{
// If allow hyphen, this isn't a new arg.
@ -672,9 +672,9 @@ impl<'help, 'app> Parser<'help, 'app> {
) -> ClapResult<()> {
debug!("Parser::parse_subcommand");
let partial_parsing_enabled = self.app.is_ignore_errors_set();
let partial_parsing_enabled = self.cmd.is_ignore_errors_set();
if let Some(sc) = self.app._build_subcommand(sc_name) {
if let Some(sc) = self.cmd._build_subcommand(sc_name) {
let mut sc_matcher = ArgMatcher::new(sc);
debug!(
@ -720,9 +720,9 @@ impl<'help, 'app> Parser<'help, 'app> {
arg
);
if let Some(help) = self.app.find(&Id::help_hash()) {
if let Some(help) = self.cmd.find(&Id::help_hash()) {
if let Some(h) = help.long {
if arg == h && !self.is_set(AS::NoAutoHelp) && !self.app.is_disable_help_flag_set()
if arg == h && !self.is_set(AS::NoAutoHelp) && !self.cmd.is_disable_help_flag_set()
{
debug!("Help");
return Some(ParseResult::HelpFlag);
@ -730,11 +730,11 @@ impl<'help, 'app> Parser<'help, 'app> {
}
}
if let Some(version) = self.app.find(&Id::version_hash()) {
if let Some(version) = self.cmd.find(&Id::version_hash()) {
if let Some(v) = version.long {
if arg == v
&& !self.is_set(AS::NoAutoVersion)
&& !self.app.is_disable_version_flag_set()
&& !self.cmd.is_disable_version_flag_set()
{
debug!("Version");
return Some(ParseResult::VersionFlag);
@ -753,9 +753,9 @@ impl<'help, 'app> Parser<'help, 'app> {
arg
);
if let Some(help) = self.app.find(&Id::help_hash()) {
if let Some(help) = self.cmd.find(&Id::help_hash()) {
if let Some(h) = help.short {
if arg == h && !self.is_set(AS::NoAutoHelp) && !self.app.is_disable_help_flag_set()
if arg == h && !self.is_set(AS::NoAutoHelp) && !self.cmd.is_disable_help_flag_set()
{
debug!("Help");
return Some(ParseResult::HelpFlag);
@ -763,11 +763,11 @@ impl<'help, 'app> Parser<'help, 'app> {
}
}
if let Some(version) = self.app.find(&Id::version_hash()) {
if let Some(version) = self.cmd.find(&Id::version_hash()) {
if let Some(v) = version.short {
if arg == v
&& !self.is_set(AS::NoAutoVersion)
&& !self.app.is_disable_version_flag_set()
&& !self.cmd.is_disable_version_flag_set()
{
debug!("Version");
return Some(ParseResult::VersionFlag);
@ -791,10 +791,10 @@ impl<'help, 'app> Parser<'help, 'app> {
// Subcommands aren't checked because we prefer short help for them, deferring to
// `cmd subcmd --help` for more.
self.app.get_long_about().is_some()
|| self.app.get_before_long_help().is_some()
|| self.app.get_after_long_help().is_some()
|| self.app.get_arguments().any(should_long)
self.cmd.get_long_about().is_some()
|| self.cmd.get_before_long_help().is_some()
|| self.cmd.get_after_long_help().is_some()
|| self.cmd.get_arguments().any(should_long)
}
fn parse_long_arg(
@ -809,7 +809,7 @@ impl<'help, 'app> Parser<'help, 'app> {
debug!("Parser::parse_long_arg");
if matches!(parse_state, ParseState::Opt(opt) | ParseState::Pos(opt) if
self.app[opt].is_allow_hyphen_values_set())
self.cmd[opt].is_allow_hyphen_values_set())
{
return ParseResult::MaybeHyphenValue;
}
@ -831,15 +831,15 @@ impl<'help, 'app> Parser<'help, 'app> {
(long_arg, None)
};
let opt = if let Some(opt) = self.app.get_keymap().get(&*arg.to_os_str()) {
let opt = if let Some(opt) = self.cmd.get_keymap().get(&*arg.to_os_str()) {
debug!(
"Parser::parse_long_arg: Found valid opt or flag '{}'",
opt.to_string()
);
Some(opt)
} else if self.app.is_infer_long_args_set() {
} else if self.cmd.is_infer_long_args_set() {
let arg_str = arg.to_str_lossy();
self.app.get_arguments().find(|a| {
self.cmd.get_arguments().find(|a| {
a.long.map_or(false, |long| long.starts_with(&*arg_str))
|| a.aliases
.iter()
@ -859,12 +859,12 @@ impl<'help, 'app> Parser<'help, 'app> {
);
self.parse_opt(val, opt, matcher, trailing_values)
} else if let Some(rest) = val {
let required = self.app.required_graph();
let required = self.cmd.required_graph();
debug!("Parser::parse_long_arg: Got invalid literal `{:?}`", rest);
let used: Vec<Id> = matcher
.arg_names()
.filter(|&n| {
self.app
self.cmd
.find(n)
.map_or(true, |a| !(a.is_hide_set() || required.contains(&a.id)))
})
@ -884,7 +884,7 @@ impl<'help, 'app> Parser<'help, 'app> {
}
} else if let Some(sc_name) = self.possible_long_flag_subcommand(arg) {
ParseResult::FlagSubCommand(sc_name.to_string())
} else if self.app.is_allow_hyphen_values_set() {
} else if self.cmd.is_allow_hyphen_values_set() {
ParseResult::MaybeHyphenValue
} else {
ParseResult::NoMatchingArg {
@ -907,21 +907,21 @@ impl<'help, 'app> Parser<'help, 'app> {
let arg = short_arg.to_str_lossy();
#[allow(clippy::blocks_in_if_conditions)]
if self.app.is_allow_negative_numbers_set() && arg.parse::<f64>().is_ok() {
if self.cmd.is_allow_negative_numbers_set() && arg.parse::<f64>().is_ok() {
debug!("Parser::parse_short_arg: negative number");
return ParseResult::MaybeHyphenValue;
} else if self.app.is_allow_hyphen_values_set()
&& arg.chars().any(|c| !self.app.contains_short(c))
} else if self.cmd.is_allow_hyphen_values_set()
&& arg.chars().any(|c| !self.cmd.contains_short(c))
{
debug!("Parser::parse_short_args: contains non-short flag");
return ParseResult::MaybeHyphenValue;
} else if matches!(parse_state, ParseState::Opt(opt) | ParseState::Pos(opt)
if self.app[opt].is_allow_hyphen_values_set())
if self.cmd[opt].is_allow_hyphen_values_set())
{
debug!("Parser::parse_short_args: prior arg accepts hyphenated values",);
return ParseResult::MaybeHyphenValue;
} else if self
.app
.cmd
.get_keymap()
.get(&pos_counter)
.map_or(false, |arg| {
@ -954,7 +954,7 @@ impl<'help, 'app> Parser<'help, 'app> {
// concatenated value: -oval
// Option: -o
// Value: val
if let Some(opt) = self.app.get_keymap().get(&c) {
if let Some(opt) = self.cmd.get_keymap().get(&c) {
debug!(
"Parser::parse_short_arg:iter:{}: Found valid opt or flag",
c
@ -990,7 +990,7 @@ impl<'help, 'app> Parser<'help, 'app> {
}
}
return if let Some(sc_name) = self.app.find_short_subcmd(c) {
return if let Some(sc_name) = self.cmd.find_short_subcmd(c) {
debug!("Parser::parse_short_arg:iter:{}: subcommand={}", c, sc_name);
let name = sc_name.to_string();
let done_short_args = {
@ -1082,7 +1082,7 @@ impl<'help, 'app> Parser<'help, 'app> {
debug!("Parser::parse_opt: More arg vals required...");
self.inc_occurrence_of_arg(matcher, opt);
matcher.new_val_group(&opt.id);
for group in self.app.groups_for_arg(&opt.id) {
for group in self.cmd.groups_for_arg(&opt.id) {
matcher.new_val_group(&group);
}
ParseResult::Opt(opt.id.clone())
@ -1102,9 +1102,9 @@ impl<'help, 'app> Parser<'help, 'app> {
debug!(
"Parser::add_val_to_arg; trailing_values={:?}, DontDelimTrailingVals={:?}",
trailing_values,
self.app.is_dont_delimit_trailing_values_set()
self.cmd.is_dont_delimit_trailing_values_set()
);
if !(trailing_values && self.app.is_dont_delimit_trailing_values_set()) {
if !(trailing_values && self.cmd.is_dont_delimit_trailing_values_set()) {
if let Some(delim) = arg.val_delim {
let terminator = arg.terminator.map(OsStr::new);
let vals = val
@ -1149,7 +1149,7 @@ impl<'help, 'app> Parser<'help, 'app> {
// If not appending, create a new val group and then append vals in.
if !append {
matcher.new_val_group(&arg.id);
for group in self.app.groups_for_arg(&arg.id) {
for group in self.cmd.groups_for_arg(&arg.id) {
matcher.new_val_group(&group);
}
}
@ -1176,7 +1176,7 @@ impl<'help, 'app> Parser<'help, 'app> {
);
// Increment or create the group "args"
for group in self.app.groups_for_arg(&arg.id) {
for group in self.cmd.groups_for_arg(&arg.id) {
matcher.add_val_to(&group, val.clone(), ty, append);
}
@ -1208,7 +1208,7 @@ impl<'help, 'app> Parser<'help, 'app> {
// Override anything that can override us
let mut transitive = Vec::new();
for arg_id in matcher.arg_names() {
if let Some(overrider) = self.app.find(arg_id) {
if let Some(overrider) = self.cmd.find(arg_id) {
if overrider.overrides.contains(&arg.id) {
transitive.push(&overrider.id);
}
@ -1224,12 +1224,12 @@ impl<'help, 'app> Parser<'help, 'app> {
pub(crate) fn add_defaults(&mut self, matcher: &mut ArgMatcher, trailing_values: bool) {
debug!("Parser::add_defaults");
for o in self.app.get_opts() {
for o in self.cmd.get_opts() {
debug!("Parser::add_defaults:iter:{}:", o.name);
self.add_value(o, matcher, ValueSource::DefaultValue, trailing_values);
}
for p in self.app.get_positionals() {
for p in self.cmd.get_positionals() {
debug!("Parser::add_defaults:iter:{}:", p.name);
self.add_value(p, matcher, ValueSource::DefaultValue, trailing_values);
}
@ -1362,7 +1362,7 @@ impl<'help, 'app> Parser<'help, 'app> {
) -> ClapResult<()> {
use crate::util::str_to_bool;
self.app.get_arguments().try_for_each(|a| {
self.cmd.get_arguments().try_for_each(|a| {
// Use env only if the arg was absent among command line args,
// early return if this is not the case.
if matcher
@ -1424,14 +1424,14 @@ impl<'help, 'app> Parser<'help, 'app> {
matcher.inc_occurrence_of_arg(arg);
// Increment or create the group "args"
for group in self.app.groups_for_arg(&arg.id) {
for group in self.cmd.groups_for_arg(&arg.id) {
matcher.inc_occurrence_of_group(&group);
}
}
}
// Error, Help, and Version Methods
impl<'help, 'app> Parser<'help, 'app> {
impl<'help, 'cmd> Parser<'help, 'cmd> {
/// Is only used for the long flag(which is the only one needs fuzzy searching)
fn did_you_mean_error(
&mut self,
@ -1442,7 +1442,7 @@ impl<'help, 'app> Parser<'help, 'app> {
debug!("Parser::did_you_mean_error: arg={}", arg);
// Didn't match a flag or option
let longs = self
.app
.cmd
.get_keymap()
.keys()
.filter_map(|x| match x {
@ -1456,21 +1456,21 @@ impl<'help, 'app> Parser<'help, 'app> {
arg,
remaining_args,
longs.iter().map(|x| &x[..]),
self.app.get_subcommands_mut(),
self.cmd.get_subcommands_mut(),
);
// Add the arg to the matches to build a proper usage string
if let Some((name, _)) = did_you_mean.as_ref() {
if let Some(opt) = self.app.get_keymap().get(&name.as_ref()) {
if let Some(opt) = self.cmd.get_keymap().get(&name.as_ref()) {
self.inc_occurrence_of_arg(matcher, opt);
}
}
let required = self.app.required_graph();
let required = self.cmd.required_graph();
let used: Vec<Id> = matcher
.arg_names()
.filter(|n| {
self.app
self.cmd
.find(n)
.map_or(true, |a| !(required.contains(&a.id) || a.is_hide_set()))
})
@ -1478,19 +1478,19 @@ impl<'help, 'app> Parser<'help, 'app> {
.collect();
ClapError::unknown_argument(
self.app,
self.cmd,
format!("--{}", arg),
did_you_mean,
Usage::new(self.app)
Usage::new(self.cmd)
.required(&required)
.create_usage_with_title(&*used),
)
}
pub(crate) fn write_help_err(&self) -> ClapResult<Colorizer> {
let usage = Usage::new(self.app);
let usage = Usage::new(self.cmd);
let mut c = Colorizer::new(true, self.color_help());
Help::new(HelpWriter::Buffer(&mut c), self.app, &usage, false).write_help()?;
Help::new(HelpWriter::Buffer(&mut c), self.cmd, &usage, false).write_help()?;
Ok(c)
}
@ -1501,29 +1501,29 @@ impl<'help, 'app> Parser<'help, 'app> {
);
use_long = use_long && self.use_long_help();
let usage = Usage::new(self.app);
let usage = Usage::new(self.cmd);
let mut c = Colorizer::new(false, self.color_help());
match Help::new(HelpWriter::Buffer(&mut c), self.app, &usage, use_long).write_help() {
match Help::new(HelpWriter::Buffer(&mut c), self.cmd, &usage, use_long).write_help() {
Err(e) => e.into(),
_ => ClapError::display_help(self.app, c),
_ => ClapError::display_help(self.cmd, c),
}
}
fn version_err(&self, use_long: bool) -> ClapError {
debug!("Parser::version_err");
let msg = self.app._render_version(use_long);
let msg = self.cmd._render_version(use_long);
let mut c = Colorizer::new(false, self.color_help());
c.none(msg);
ClapError::display_version(self.app, c)
ClapError::display_version(self.cmd, c)
}
}
// Query Methods
impl<'help, 'app> Parser<'help, 'app> {
impl<'help, 'cmd> Parser<'help, 'cmd> {
pub(crate) fn is_set(&self, s: AS) -> bool {
self.app.is_set(s)
self.cmd.is_set(s)
}
}

View file

@ -1,5 +1,5 @@
// Internal
use crate::build::{App, AppSettings, Arg, ArgPredicate, PossibleValue};
use crate::build::{AppSettings, Arg, ArgPredicate, Command, PossibleValue};
use crate::error::{Error, Result as ClapResult};
use crate::output::Usage;
use crate::parse::{ArgMatcher, MatchedArg, ParseState, Parser};
@ -7,14 +7,14 @@ use crate::util::ChildGraph;
use crate::util::Id;
use crate::{INTERNAL_ERROR_MSG, INVALID_UTF8};
pub(crate) struct Validator<'help, 'app, 'parser> {
p: &'parser mut Parser<'help, 'app>,
pub(crate) struct Validator<'help, 'cmd, 'parser> {
p: &'parser mut Parser<'help, 'cmd>,
required: ChildGraph<Id>,
}
impl<'help, 'app, 'parser> Validator<'help, 'app, 'parser> {
pub(crate) fn new(p: &'parser mut Parser<'help, 'app>) -> Self {
let required = p.app.required_graph();
impl<'help, 'cmd, 'parser> Validator<'help, 'cmd, 'parser> {
pub(crate) fn new(p: &'parser mut Parser<'help, 'cmd>) -> Self {
let required = p.cmd.required_graph();
Validator { p, required }
}
@ -35,7 +35,7 @@ impl<'help, 'app, 'parser> Validator<'help, 'app, 'parser> {
if let ParseState::Opt(a) = parse_state {
debug!("Validator::validate: needs_val_of={:?}", a);
let o = &self.p.app[&a];
let o = &self.p.cmd[&a];
let should_err = if let Some(v) = matcher.args.get(&o.id) {
v.all_val_groups_empty() && !(o.min_vals.is_some() && o.min_vals.unwrap() == 0)
} else {
@ -43,51 +43,51 @@ impl<'help, 'app, 'parser> Validator<'help, 'app, 'parser> {
};
if should_err {
return Err(Error::empty_value(
self.p.app,
self.p.cmd,
&o.possible_vals
.iter()
.filter_map(PossibleValue::get_visible_name)
.collect::<Vec<_>>(),
o,
Usage::new(self.p.app)
Usage::new(self.p.cmd)
.required(&self.required)
.create_usage_with_title(&[]),
));
}
}
if !has_subcmd && self.p.app.is_arg_required_else_help_set() {
if !has_subcmd && self.p.cmd.is_arg_required_else_help_set() {
let num_user_values = matcher
.arg_names()
.filter(|arg_id| matcher.check_explicit(arg_id, ArgPredicate::IsPresent))
.count();
if num_user_values == 0 {
let message = self.p.write_help_err()?;
return Err(Error::display_help_error(self.p.app, message));
return Err(Error::display_help_error(self.p.cmd, message));
}
}
#[allow(deprecated)]
if !has_subcmd && self.p.app.is_subcommand_required_set() {
if !has_subcmd && self.p.cmd.is_subcommand_required_set() {
let bn = self
.p
.app
.cmd
.get_bin_name()
.unwrap_or_else(|| self.p.app.get_name());
.unwrap_or_else(|| self.p.cmd.get_name());
return Err(Error::missing_subcommand(
self.p.app,
self.p.cmd,
bn.to_string(),
Usage::new(self.p.app)
Usage::new(self.p.cmd)
.required(&self.required)
.create_usage_with_title(&[]),
));
} else if !has_subcmd && self.p.app.is_set(AppSettings::SubcommandRequiredElseHelp) {
} else if !has_subcmd && self.p.cmd.is_set(AppSettings::SubcommandRequiredElseHelp) {
debug!("Validator::new::get_matches_with: SubcommandRequiredElseHelp=true");
let message = self.p.write_help_err()?;
return Err(Error::display_help_error(self.p.app, message));
return Err(Error::display_help_error(self.p.cmd, message));
}
self.validate_conflicts(matcher)?;
if !(self.p.app.is_subcommand_negates_reqs_set() && has_subcmd) {
if !(self.p.cmd.is_subcommand_negates_reqs_set() && has_subcmd) {
self.validate_required(matcher)?;
}
self.validate_matched_args(matcher)?;
@ -109,8 +109,8 @@ impl<'help, 'app, 'parser> Validator<'help, 'app, 'parser> {
val
);
return Err(Error::invalid_utf8(
self.p.app,
Usage::new(self.p.app)
self.p.cmd,
Usage::new(self.p.cmd)
.required(&self.required)
.create_usage_with_title(&[]),
));
@ -130,21 +130,21 @@ impl<'help, 'app, 'parser> Validator<'help, 'app, 'parser> {
.arg_names()
.filter(|arg_id| matcher.check_explicit(arg_id, ArgPredicate::IsPresent))
.filter(|&n| {
self.p.app.find(n).map_or(true, |a| {
self.p.cmd.find(n).map_or(true, |a| {
!(a.is_hide_set() || self.required.contains(&a.id))
})
})
.cloned()
.collect();
return Err(Error::invalid_value(
self.p.app,
self.p.cmd,
val_str.into_owned(),
&arg.possible_vals
.iter()
.filter_map(PossibleValue::get_visible_name)
.collect::<Vec<_>>(),
arg,
Usage::new(self.p.app)
Usage::new(self.p.cmd)
.required(&self.required)
.create_usage_with_title(&used),
));
@ -153,13 +153,13 @@ impl<'help, 'app, 'parser> Validator<'help, 'app, 'parser> {
if arg.is_forbid_empty_values_set() && val.is_empty() && matcher.contains(&arg.id) {
debug!("Validator::validate_arg_values: illegal empty val found");
return Err(Error::empty_value(
self.p.app,
self.p.cmd,
&arg.possible_vals
.iter()
.filter_map(PossibleValue::get_visible_name)
.collect::<Vec<_>>(),
arg,
Usage::new(self.p.app)
Usage::new(self.p.cmd)
.required(&self.required)
.create_usage_with_title(&[]),
));
@ -175,7 +175,7 @@ impl<'help, 'app, 'parser> Validator<'help, 'app, 'parser> {
val.to_string_lossy().into_owned(),
e,
)
.with_app(self.p.app));
.with_cmd(self.p.cmd));
} else {
debug!("good");
}
@ -190,7 +190,7 @@ impl<'help, 'app, 'parser> Validator<'help, 'app, 'parser> {
val.to_string_lossy().into(),
e,
)
.with_app(self.p.app));
.with_cmd(self.p.cmd));
} else {
debug!("good");
}
@ -208,10 +208,10 @@ impl<'help, 'app, 'parser> Validator<'help, 'app, 'parser> {
for arg_id in matcher
.arg_names()
.filter(|arg_id| matcher.check_explicit(arg_id, ArgPredicate::IsPresent))
.filter(|arg_id| self.p.app.find(arg_id).is_some())
.filter(|arg_id| self.p.cmd.find(arg_id).is_some())
{
debug!("Validator::validate_conflicts::iter: id={:?}", arg_id);
let conflicts = conflicts.gather_conflicts(self.p.app, matcher, arg_id);
let conflicts = conflicts.gather_conflicts(self.p.cmd, matcher, arg_id);
self.build_conflict_err(arg_id, &conflicts, matcher)?;
}
@ -227,7 +227,7 @@ impl<'help, 'app, 'parser> Validator<'help, 'app, 'parser> {
.filter_map(|name| {
debug!("Validator::validate_exclusive:iter:{:?}", name);
self.p
.app
.cmd
.find(name)
// Find `arg`s which are exclusive but also appear with other args.
.filter(|&arg| arg.is_exclusive_set() && args_count > 1)
@ -235,10 +235,10 @@ impl<'help, 'app, 'parser> Validator<'help, 'app, 'parser> {
// Throw an error for the first conflict found.
.try_for_each(|arg| {
Err(Error::argument_conflict(
self.p.app,
self.p.cmd,
arg,
Vec::new(),
Usage::new(self.p.app)
Usage::new(self.p.cmd)
.required(&self.required)
.create_usage_with_title(&[]),
))
@ -260,24 +260,24 @@ impl<'help, 'app, 'parser> Validator<'help, 'app, 'parser> {
let conflicts = conflict_ids
.iter()
.flat_map(|c_id| {
if self.p.app.find_group(c_id).is_some() {
self.p.app.unroll_args_in_group(c_id)
if self.p.cmd.find_group(c_id).is_some() {
self.p.cmd.unroll_args_in_group(c_id)
} else {
vec![c_id.clone()]
}
})
.filter_map(|c_id| {
seen.insert(c_id.clone()).then(|| {
let c_arg = self.p.app.find(&c_id).expect(INTERNAL_ERROR_MSG);
let c_arg = self.p.cmd.find(&c_id).expect(INTERNAL_ERROR_MSG);
c_arg.to_string()
})
})
.collect();
let former_arg = self.p.app.find(name).expect(INTERNAL_ERROR_MSG);
let former_arg = self.p.cmd.find(name).expect(INTERNAL_ERROR_MSG);
let usg = self.build_conflict_err_usage(matcher, conflict_ids);
Err(Error::argument_conflict(
self.p.app, former_arg, conflicts, usg,
self.p.cmd, former_arg, conflicts, usg,
))
}
@ -290,13 +290,13 @@ impl<'help, 'app, 'parser> Validator<'help, 'app, 'parser> {
.collect();
let required: Vec<Id> = used_filtered
.iter()
.filter_map(|key| self.p.app.find(key))
.filter_map(|key| self.p.cmd.find(key))
.flat_map(|arg| arg.requires.iter().map(|item| &item.1))
.filter(|key| !used_filtered.contains(key) && !conflicting_keys.contains(key))
.chain(used_filtered.iter())
.cloned()
.collect();
Usage::new(self.p.app)
Usage::new(self.p.cmd)
.required(&self.required)
.create_usage_with_title(&required)
}
@ -308,16 +308,16 @@ impl<'help, 'app, 'parser> Validator<'help, 'app, 'parser> {
.filter(|arg_id| matcher.check_explicit(arg_id, ArgPredicate::IsPresent))
{
debug!("Validator::gather_requires:iter:{:?}", name);
if let Some(arg) = self.p.app.find(name) {
if let Some(arg) = self.p.cmd.find(name) {
let is_relevant = |(val, req_arg): &(ArgPredicate<'_>, Id)| -> Option<Id> {
let required = matcher.check_explicit(&arg.id, *val);
required.then(|| req_arg.clone())
};
for req in self.p.app.unroll_arg_requires(is_relevant, &arg.id) {
for req in self.p.cmd.unroll_arg_requires(is_relevant, &arg.id) {
self.required.insert(req);
}
} else if let Some(g) = self.p.app.find_group(name) {
} else if let Some(g) = self.p.cmd.find_group(name) {
debug!("Validator::gather_requires:iter:{:?}:group", name);
for r in &g.requires {
self.required.insert(r.clone());
@ -334,7 +334,7 @@ impl<'help, 'app, 'parser> Validator<'help, 'app, 'parser> {
name,
ma.vals_flatten()
);
if let Some(arg) = self.p.app.find(name) {
if let Some(arg) = self.p.cmd.find(name) {
self.validate_arg_num_vals(arg, ma)?;
self.validate_arg_values(arg, ma, matcher)?;
self.validate_arg_num_occurs(arg, ma)?;
@ -354,9 +354,9 @@ impl<'help, 'app, 'parser> Validator<'help, 'app, 'parser> {
if ma.get_occurrences() > 1 && !a.is_multiple_occurrences_set() && !a.is_positional() {
// Not the first time, and we don't allow multiples
return Err(Error::unexpected_multiple_usage(
self.p.app,
self.p.cmd,
a,
Usage::new(self.p.app)
Usage::new(self.p.cmd)
.required(&self.required)
.create_usage_with_title(&[]),
));
@ -369,11 +369,11 @@ impl<'help, 'app, 'parser> Validator<'help, 'app, 'parser> {
let occurs = ma.get_occurrences() as usize;
if occurs > max_occurs {
return Err(Error::too_many_occurrences(
self.p.app,
self.p.cmd,
a,
max_occurs,
occurs,
Usage::new(self.p.app)
Usage::new(self.p.cmd)
.required(&self.required)
.create_usage_with_title(&[]),
));
@ -396,7 +396,7 @@ impl<'help, 'app, 'parser> Validator<'help, 'app, 'parser> {
if should_err {
debug!("Validator::validate_arg_num_vals: Sending error WrongNumberOfValues");
return Err(Error::wrong_number_of_values(
self.p.app,
self.p.cmd,
a,
num,
if a.is_multiple_occurrences_set() {
@ -404,7 +404,7 @@ impl<'help, 'app, 'parser> Validator<'help, 'app, 'parser> {
} else {
total_num
},
Usage::new(self.p.app)
Usage::new(self.p.cmd)
.required(&self.required)
.create_usage_with_title(&[]),
));
@ -415,7 +415,7 @@ impl<'help, 'app, 'parser> Validator<'help, 'app, 'parser> {
if ma.num_vals() > num {
debug!("Validator::validate_arg_num_vals: Sending error TooManyValues");
return Err(Error::too_many_values(
self.p.app,
self.p.cmd,
ma.vals_flatten()
.last()
.expect(INTERNAL_ERROR_MSG)
@ -423,7 +423,7 @@ impl<'help, 'app, 'parser> Validator<'help, 'app, 'parser> {
.expect(INVALID_UTF8)
.to_string(),
a.to_string(),
Usage::new(self.p.app)
Usage::new(self.p.cmd)
.required(&self.required)
.create_usage_with_title(&[]),
));
@ -434,11 +434,11 @@ impl<'help, 'app, 'parser> Validator<'help, 'app, 'parser> {
if ma.num_vals() < num && num != 0 {
debug!("Validator::validate_arg_num_vals: Sending error TooFewValues");
return Err(Error::too_few_values(
self.p.app,
self.p.cmd,
a,
num,
ma.num_vals(),
Usage::new(self.p.app)
Usage::new(self.p.cmd)
.required(&self.required)
.create_usage_with_title(&[]),
));
@ -451,13 +451,13 @@ impl<'help, 'app, 'parser> Validator<'help, 'app, 'parser> {
// Issue 1105 (https://github.com/clap-rs/clap/issues/1105)
if a.is_takes_value_set() && !min_vals_zero && ma.all_val_groups_empty() {
return Err(Error::empty_value(
self.p.app,
self.p.cmd,
&a.possible_vals
.iter()
.filter_map(PossibleValue::get_visible_name)
.collect::<Vec<_>>(),
a,
Usage::new(self.p.app)
Usage::new(self.p.cmd)
.required(&self.required)
.create_usage_with_title(&[]),
));
@ -471,16 +471,16 @@ impl<'help, 'app, 'parser> Validator<'help, 'app, 'parser> {
for arg_or_group in self.required.iter().filter(|r| !matcher.contains(r)) {
debug!("Validator::validate_required:iter:aog={:?}", arg_or_group);
if let Some(arg) = self.p.app.find(arg_or_group) {
if let Some(arg) = self.p.cmd.find(arg_or_group) {
debug!("Validator::validate_required:iter: This is an arg");
if !self.is_missing_required_ok(arg, matcher) {
return self.missing_required_error(matcher, vec![]);
}
} else if let Some(group) = self.p.app.find_group(arg_or_group) {
} else if let Some(group) = self.p.cmd.find_group(arg_or_group) {
debug!("Validator::validate_required:iter: This is a group");
if !self
.p
.app
.cmd
.unroll_args_in_group(&group.id)
.iter()
.any(|a| matcher.contains(a))
@ -491,7 +491,7 @@ impl<'help, 'app, 'parser> Validator<'help, 'app, 'parser> {
}
// Validate the conditionally required args
for a in self.p.app.get_arguments() {
for a in self.p.cmd.get_arguments() {
for (other, val) in &a.r_ifs {
if matcher.check_explicit(other, ArgPredicate::Equals(std::ffi::OsStr::new(*val)))
&& !matcher.contains(&a.id)
@ -524,7 +524,7 @@ impl<'help, 'app, 'parser> Validator<'help, 'app, 'parser> {
matcher.contains(conf)
|| self
.p
.app
.cmd
.find_group(conf)
.map_or(false, |g| g.args.iter().any(|arg| matcher.contains(arg)))
})
@ -534,7 +534,7 @@ impl<'help, 'app, 'parser> Validator<'help, 'app, 'parser> {
debug!("Validator::validate_required_unless");
let failed_args: Vec<_> = self
.p
.app
.cmd
.get_arguments()
.filter(|&a| {
(!a.r_unless.is_empty() || !a.r_unless_all.is_empty())
@ -567,7 +567,7 @@ impl<'help, 'app, 'parser> Validator<'help, 'app, 'parser> {
self.required
);
let usg = Usage::new(self.p.app).required(&self.required);
let usg = Usage::new(self.p.cmd).required(&self.required);
let req_args = usg.get_required_usage_from(&incl, Some(matcher), true);
@ -582,7 +582,7 @@ impl<'help, 'app, 'parser> Validator<'help, 'app, 'parser> {
.filter(|n| {
// Filter out the args we don't want to specify.
self.p
.app
.cmd
.find(n)
.map_or(true, |a| !a.is_hide_set() && !self.required.contains(&a.id))
})
@ -591,7 +591,7 @@ impl<'help, 'app, 'parser> Validator<'help, 'app, 'parser> {
.collect();
Err(Error::missing_required_argument(
self.p.app,
self.p.cmd,
req_args,
usg.create_usage_with_title(&used),
))
@ -608,7 +608,7 @@ impl Conflicts {
Self::default()
}
fn gather_conflicts(&mut self, app: &App, matcher: &ArgMatcher, arg_id: &Id) -> Vec<Id> {
fn gather_conflicts(&mut self, cmd: &Command, matcher: &ArgMatcher, arg_id: &Id) -> Vec<Id> {
debug!("Conflicts::gather_conflicts");
let mut conflicts = Vec::new();
for other_arg_id in matcher
@ -620,13 +620,13 @@ impl Conflicts {
}
if self
.gather_direct_conflicts(app, arg_id)
.gather_direct_conflicts(cmd, arg_id)
.contains(other_arg_id)
{
conflicts.push(other_arg_id.clone());
}
if self
.gather_direct_conflicts(app, other_arg_id)
.gather_direct_conflicts(cmd, other_arg_id)
.contains(arg_id)
{
conflicts.push(other_arg_id.clone());
@ -635,12 +635,12 @@ impl Conflicts {
conflicts
}
fn gather_direct_conflicts(&mut self, app: &App, arg_id: &Id) -> &[Id] {
fn gather_direct_conflicts(&mut self, cmd: &Command, arg_id: &Id) -> &[Id] {
self.potential.entry(arg_id.clone()).or_insert_with(|| {
let conf = if let Some(arg) = app.find(arg_id) {
let conf = if let Some(arg) = cmd.find(arg_id) {
let mut conf = arg.blacklist.clone();
for group_id in app.groups_for_arg(arg_id) {
let group = app.find_group(&group_id).expect(INTERNAL_ERROR_MSG);
for group_id in cmd.groups_for_arg(arg_id) {
let group = cmd.find_group(&group_id).expect(INTERNAL_ERROR_MSG);
conf.extend(group.conflicts.iter().cloned());
if !group.multiple {
for member_id in &group.args {
@ -651,7 +651,7 @@ impl Conflicts {
}
}
conf
} else if let Some(group) = app.find_group(arg_id) {
} else if let Some(group) = cmd.find_group(arg_id) {
group.conflicts.clone()
} else {
debug_assert!(false, "id={:?} is unknown", arg_id);

View file

@ -13,8 +13,8 @@ pub enum ColorChoice {
///
#[cfg_attr(not(feature = "color"), doc = " ```ignore")]
#[cfg_attr(feature = "color", doc = " ```no_run")]
/// # use clap::{App, ColorChoice};
/// App::new("myprog")
/// # use clap::{Command, ColorChoice};
/// Command::new("myprog")
/// .color(ColorChoice::Auto)
/// .get_matches();
/// ```
@ -30,8 +30,8 @@ pub enum ColorChoice {
///
#[cfg_attr(not(feature = "color"), doc = " ```ignore")]
#[cfg_attr(feature = "color", doc = " ```no_run")]
/// # use clap::{App, ColorChoice};
/// App::new("myprog")
/// # use clap::{Command, ColorChoice};
/// Command::new("myprog")
/// .color(ColorChoice::Always)
/// .get_matches();
/// ```
@ -47,8 +47,8 @@ pub enum ColorChoice {
///
#[cfg_attr(not(feature = "color"), doc = " ```ignore")]
#[cfg_attr(feature = "color", doc = " ```no_run")]
/// # use clap::{App, ColorChoice};
/// App::new("myprog")
/// # use clap::{Command, ColorChoice};
/// Command::new("myprog")
/// .color(ColorChoice::Never)
/// .get_matches();
/// ```

View file

@ -1,6 +1,6 @@
use crate::utils;
use clap::{arg, error::ErrorKind, App, AppSettings, Arg};
use clap::{arg, error::ErrorKind, AppSettings, Arg, Command};
static ALLOW_EXT_SC: &str = "clap-test v1.4.8
@ -82,21 +82,21 @@ SUBCOMMANDS:
#[test]
fn setting() {
#![allow(deprecated)]
let m = App::new("setting").args_override_self(true);
let m = Command::new("setting").args_override_self(true);
assert!(m.is_set(AppSettings::AllArgsOverrideSelf));
}
#[test]
fn global_setting() {
#![allow(deprecated)]
let m = App::new("global_setting").args_override_self(true);
let m = Command::new("global_setting").args_override_self(true);
assert!(m.is_set(AppSettings::AllArgsOverrideSelf));
}
#[test]
fn unset_setting() {
#![allow(deprecated)]
let m = App::new("unset_setting").args_override_self(true);
let m = Command::new("unset_setting").args_override_self(true);
assert!(m.is_set(AppSettings::AllArgsOverrideSelf));
let m = m.args_override_self(false);
@ -106,7 +106,7 @@ fn unset_setting() {
#[test]
fn unset_global_setting() {
#![allow(deprecated)]
let m = App::new("unset_global_setting").args_override_self(true);
let m = Command::new("unset_global_setting").args_override_self(true);
assert!(m.is_set(AppSettings::AllArgsOverrideSelf));
let m = m.args_override_self(false);
@ -116,7 +116,7 @@ fn unset_global_setting() {
#[test]
fn setting_bitor() {
#![allow(deprecated)]
let m = App::new("setting_bitor").setting(
let m = Command::new("setting_bitor").setting(
AppSettings::InferSubcommands | AppSettings::Hidden | AppSettings::DisableHelpSubcommand,
);
@ -128,7 +128,7 @@ fn setting_bitor() {
#[test]
fn unset_setting_bitor() {
#![allow(deprecated)]
let m = App::new("unset_setting_bitor")
let m = Command::new("unset_setting_bitor")
.setting(AppSettings::InferSubcommands)
.setting(AppSettings::Hidden)
.setting(AppSettings::DisableHelpSubcommand);
@ -147,20 +147,20 @@ fn unset_setting_bitor() {
#[test]
fn sub_command_negate_required() {
App::new("sub_command_negate")
Command::new("sub_command_negate")
.subcommand_negates_reqs(true)
.arg(Arg::new("test").required(true).index(1))
.subcommand(App::new("sub1"))
.subcommand(Command::new("sub1"))
.try_get_matches_from(vec!["myprog", "sub1"])
.unwrap();
}
#[test]
fn sub_command_negate_required_2() {
let result = App::new("sub_command_negate")
let result = Command::new("sub_command_negate")
.subcommand_negates_reqs(true)
.arg(Arg::new("test").required(true).index(1))
.subcommand(App::new("sub1"))
.subcommand(Command::new("sub1"))
.try_get_matches_from(vec![""]);
assert!(result.is_err());
let err = result.err().unwrap();
@ -169,9 +169,9 @@ fn sub_command_negate_required_2() {
#[test]
fn sub_command_required() {
let result = App::new("sc_required")
let result = Command::new("sc_required")
.subcommand_required(true)
.subcommand(App::new("sub1"))
.subcommand(Command::new("sub1"))
.try_get_matches_from(vec![""]);
assert!(result.is_err());
let err = result.err().unwrap();
@ -180,7 +180,7 @@ fn sub_command_required() {
#[test]
fn arg_required_else_help() {
let result = App::new("arg_required")
let result = Command::new("arg_required")
.arg_required_else_help(true)
.arg(Arg::new("test").index(1))
.try_get_matches_from(vec![""]);
@ -195,7 +195,7 @@ fn arg_required_else_help() {
#[test]
fn arg_required_else_help_over_req_arg() {
let result = App::new("arg_required")
let result = Command::new("arg_required")
.arg_required_else_help(true)
.arg(Arg::new("test").index(1).required(true))
.try_get_matches_from(vec![""]);
@ -210,10 +210,10 @@ fn arg_required_else_help_over_req_arg() {
#[test]
fn arg_required_else_help_over_req_subcommand() {
let result = App::new("sub_required")
let result = Command::new("sub_required")
.arg_required_else_help(true)
.subcommand_required(true)
.subcommand(App::new("sub1"))
.subcommand(Command::new("sub1"))
.try_get_matches_from(vec![""]);
assert!(result.is_err());
@ -226,7 +226,7 @@ fn arg_required_else_help_over_req_subcommand() {
#[test]
fn arg_required_else_help_with_default() {
let result = App::new("arg_required")
let result = Command::new("arg_required")
.arg_required_else_help(true)
.arg(arg!(--input <PATH>).required(false).default_value("-"))
.try_get_matches_from(vec![""]);
@ -241,7 +241,7 @@ fn arg_required_else_help_with_default() {
#[test]
fn arg_required_else_help_error_message() {
let app = App::new("test")
let cmd = Command::new("test")
.arg_required_else_help(true)
.version("1.0")
.arg(
@ -251,7 +251,7 @@ fn arg_required_else_help_error_message() {
.long("info"),
);
assert!(utils::compare_output(
app,
cmd,
"test",
ARG_REQUIRED_ELSE_HELP,
true // Unlike normal displaying of help, we should provide a fatal exit code
@ -261,9 +261,9 @@ fn arg_required_else_help_error_message() {
#[test]
fn subcommand_required_else_help() {
#![allow(deprecated)]
let result = App::new("test")
let result = Command::new("test")
.setting(AppSettings::SubcommandRequiredElseHelp)
.subcommand(App::new("info"))
.subcommand(Command::new("info"))
.try_get_matches_from(&[""]);
assert!(result.is_err());
@ -277,12 +277,12 @@ fn subcommand_required_else_help() {
#[test]
fn subcommand_required_else_help_error_message() {
#![allow(deprecated)]
let app = App::new("test")
let cmd = Command::new("test")
.setting(AppSettings::SubcommandRequiredElseHelp)
.version("1.0")
.subcommand(App::new("info").arg(Arg::new("filename")));
.subcommand(Command::new("info").arg(Arg::new("filename")));
assert!(utils::compare_output(
app,
cmd,
"test",
SUBCOMMAND_REQUIRED_ELSE_HELP,
true // Unlike normal displaying of help, we should provide a fatal exit code
@ -292,10 +292,10 @@ fn subcommand_required_else_help_error_message() {
#[cfg(not(feature = "suggestions"))]
#[test]
fn infer_subcommands_fail_no_args() {
let m = App::new("prog")
let m = Command::new("prog")
.infer_subcommands(true)
.subcommand(App::new("test"))
.subcommand(App::new("temp"))
.subcommand(Command::new("test"))
.subcommand(Command::new("temp"))
.try_get_matches_from(vec!["prog", "te"]);
assert!(m.is_err(), "{:#?}", m.unwrap());
assert_eq!(m.unwrap_err().kind(), ErrorKind::UnrecognizedSubcommand);
@ -304,10 +304,10 @@ fn infer_subcommands_fail_no_args() {
#[cfg(feature = "suggestions")]
#[test]
fn infer_subcommands_fail_no_args() {
let m = App::new("prog")
let m = Command::new("prog")
.infer_subcommands(true)
.subcommand(App::new("test"))
.subcommand(App::new("temp"))
.subcommand(Command::new("test"))
.subcommand(Command::new("temp"))
.try_get_matches_from(vec!["prog", "te"]);
assert!(m.is_err(), "{:#?}", m.unwrap());
assert_eq!(m.unwrap_err().kind(), ErrorKind::InvalidSubcommand);
@ -315,11 +315,11 @@ fn infer_subcommands_fail_no_args() {
#[test]
fn infer_subcommands_fail_with_args() {
let m = App::new("prog")
let m = Command::new("prog")
.infer_subcommands(true)
.arg(Arg::new("some"))
.subcommand(App::new("test"))
.subcommand(App::new("temp"))
.subcommand(Command::new("test"))
.subcommand(Command::new("temp"))
.try_get_matches_from(vec!["prog", "t"]);
assert!(m.is_ok(), "{:?}", m.unwrap_err().kind());
assert_eq!(m.unwrap().value_of("some"), Some("t"));
@ -327,11 +327,11 @@ fn infer_subcommands_fail_with_args() {
#[test]
fn infer_subcommands_fail_with_args2() {
let m = App::new("prog")
let m = Command::new("prog")
.infer_subcommands(true)
.arg(Arg::new("some"))
.subcommand(App::new("test"))
.subcommand(App::new("temp"))
.subcommand(Command::new("test"))
.subcommand(Command::new("temp"))
.try_get_matches_from(vec!["prog", "te"]);
assert!(m.is_ok(), "{:?}", m.unwrap_err().kind());
assert_eq!(m.unwrap().value_of("some"), Some("te"));
@ -339,9 +339,9 @@ fn infer_subcommands_fail_with_args2() {
#[test]
fn infer_subcommands_pass() {
let m = App::new("prog")
let m = Command::new("prog")
.infer_subcommands(true)
.subcommand(App::new("test"))
.subcommand(Command::new("test"))
.try_get_matches_from(vec!["prog", "te"])
.unwrap();
assert_eq!(m.subcommand_name(), Some("test"));
@ -349,10 +349,10 @@ fn infer_subcommands_pass() {
#[test]
fn infer_subcommands_pass_close() {
let m = App::new("prog")
let m = Command::new("prog")
.infer_subcommands(true)
.subcommand(App::new("test"))
.subcommand(App::new("temp"))
.subcommand(Command::new("test"))
.subcommand(Command::new("temp"))
.try_get_matches_from(vec!["prog", "tes"])
.unwrap();
assert_eq!(m.subcommand_name(), Some("test"));
@ -360,11 +360,11 @@ fn infer_subcommands_pass_close() {
#[test]
fn infer_subcommands_pass_exact_match() {
let m = App::new("prog")
let m = Command::new("prog")
.infer_subcommands(true)
.subcommand(App::new("test"))
.subcommand(App::new("testa"))
.subcommand(App::new("testb"))
.subcommand(Command::new("test"))
.subcommand(Command::new("testa"))
.subcommand(Command::new("testb"))
.try_get_matches_from(vec!["prog", "test"])
.unwrap();
assert_eq!(m.subcommand_name(), Some("test"));
@ -373,10 +373,10 @@ fn infer_subcommands_pass_exact_match() {
#[cfg(feature = "suggestions")]
#[test]
fn infer_subcommands_fail_suggestions() {
let m = App::new("prog")
let m = Command::new("prog")
.infer_subcommands(true)
.subcommand(App::new("test"))
.subcommand(App::new("temp"))
.subcommand(Command::new("test"))
.subcommand(Command::new("temp"))
.try_get_matches_from(vec!["prog", "temps"]);
assert!(m.is_err(), "{:#?}", m.unwrap());
assert_eq!(m.unwrap_err().kind(), ErrorKind::InvalidSubcommand);
@ -385,10 +385,10 @@ fn infer_subcommands_fail_suggestions() {
#[cfg(not(feature = "suggestions"))]
#[test]
fn infer_subcommands_fail_suggestions() {
let m = App::new("prog")
let m = Command::new("prog")
.infer_subcommands(true)
.subcommand(App::new("test"))
.subcommand(App::new("temp"))
.subcommand(Command::new("test"))
.subcommand(Command::new("temp"))
.try_get_matches_from(vec!["prog", "temps"]);
assert!(m.is_err(), "{:#?}", m.unwrap());
assert_eq!(m.unwrap_err().kind(), ErrorKind::UnrecognizedSubcommand);
@ -396,7 +396,7 @@ fn infer_subcommands_fail_suggestions() {
#[test]
fn no_bin_name() {
let result = App::new("arg_required")
let result = Command::new("arg_required")
.no_binary_name(true)
.arg(Arg::new("test").required(true).index(1))
.try_get_matches_from(vec!["testing"]);
@ -407,7 +407,7 @@ fn no_bin_name() {
#[test]
fn skip_possible_values() {
let app = App::new("test")
let cmd = Command::new("test")
.author("Kevin K.")
.about("tests stuff")
.version("1.3")
@ -420,7 +420,7 @@ fn skip_possible_values() {
]);
assert!(utils::compare_output(
app,
cmd,
"test --help",
SKIP_POS_VALS,
false
@ -429,7 +429,7 @@ fn skip_possible_values() {
#[test]
fn stop_delim_values_only_pos_follows() {
let r = App::new("onlypos")
let r = Command::new("onlypos")
.dont_delimit_trailing_values(true)
.args(&[
arg!(f: -f <flag> "some opt").required(false),
@ -448,7 +448,7 @@ fn stop_delim_values_only_pos_follows() {
#[test]
fn dont_delim_values_trailingvararg() {
let m = App::new("positional")
let m = Command::new("positional")
.trailing_var_arg(true)
.dont_delimit_trailing_values(true)
.arg(arg!([opt] ... "some pos"))
@ -463,7 +463,7 @@ fn dont_delim_values_trailingvararg() {
#[test]
fn delim_values_only_pos_follows() {
let r = App::new("onlypos")
let r = Command::new("onlypos")
.args(&[arg!(f: -f [flag] "some opt"), arg!([arg] ... "some arg")])
.try_get_matches_from(vec!["", "--", "-f", "-g,x"]);
assert!(r.is_ok(), "{}", r.unwrap_err());
@ -478,7 +478,7 @@ fn delim_values_only_pos_follows() {
#[test]
fn delim_values_trailingvararg() {
let m = App::new("positional")
let m = Command::new("positional")
.trailing_var_arg(true)
.arg(arg!([opt] ... "some pos"))
.try_get_matches_from(vec!["", "test", "--foo", "-Wl,-bar"])
@ -492,7 +492,7 @@ fn delim_values_trailingvararg() {
#[test]
fn delim_values_only_pos_follows_with_delim() {
let r = App::new("onlypos")
let r = Command::new("onlypos")
.args(&[
arg!(f: -f [flag] "some opt"),
arg!([arg] ... "some arg").use_value_delimiter(true),
@ -510,7 +510,7 @@ fn delim_values_only_pos_follows_with_delim() {
#[test]
fn delim_values_trailingvararg_with_delim() {
let m = App::new("positional")
let m = Command::new("positional")
.trailing_var_arg(true)
.arg(arg!([opt] ... "some pos").use_value_delimiter(true))
.try_get_matches_from(vec!["", "test", "--foo", "-Wl,-bar"])
@ -524,7 +524,7 @@ fn delim_values_trailingvararg_with_delim() {
#[test]
fn leading_hyphen_short() {
let res = App::new("leadhy")
let res = Command::new("leadhy")
.allow_hyphen_values(true)
.arg(Arg::new("some"))
.arg(Arg::new("other").short('o'))
@ -538,7 +538,7 @@ fn leading_hyphen_short() {
#[test]
fn leading_hyphen_long() {
let res = App::new("leadhy")
let res = Command::new("leadhy")
.allow_hyphen_values(true)
.arg(Arg::new("some"))
.arg(Arg::new("other").short('o'))
@ -552,7 +552,7 @@ fn leading_hyphen_long() {
#[test]
fn leading_hyphen_opt() {
let res = App::new("leadhy")
let res = Command::new("leadhy")
.allow_hyphen_values(true)
.arg(Arg::new("some").takes_value(true).long("opt"))
.arg(Arg::new("other").short('o'))
@ -566,7 +566,7 @@ fn leading_hyphen_opt() {
#[test]
fn allow_negative_numbers() {
let res = App::new("negnum")
let res = Command::new("negnum")
.allow_negative_numbers(true)
.arg(Arg::new("panum"))
.arg(Arg::new("onum").short('o').takes_value(true))
@ -579,7 +579,7 @@ fn allow_negative_numbers() {
#[test]
fn allow_negative_numbers_fail() {
let res = App::new("negnum")
let res = Command::new("negnum")
.allow_negative_numbers(true)
.arg(Arg::new("panum"))
.arg(Arg::new("onum").short('o').takes_value(true))
@ -590,7 +590,7 @@ fn allow_negative_numbers_fail() {
#[test]
fn leading_double_hyphen_trailingvararg() {
let m = App::new("positional")
let m = Command::new("positional")
.trailing_var_arg(true)
.allow_hyphen_values(true)
.arg(arg!([opt] ... "some pos"))
@ -605,9 +605,9 @@ fn leading_double_hyphen_trailingvararg() {
#[test]
fn disable_help_subcommand() {
let result = App::new("disablehelp")
let result = Command::new("disablehelp")
.disable_help_subcommand(true)
.subcommand(App::new("sub1"))
.subcommand(Command::new("sub1"))
.try_get_matches_from(vec!["", "help"]);
assert!(result.is_err());
let err = result.err().unwrap();
@ -616,7 +616,7 @@ fn disable_help_subcommand() {
#[test]
fn dont_collapse_args() {
let app = App::new("clap-test")
let cmd = Command::new("clap-test")
.version("v1.4.8")
.dont_collapse_args_in_usage(true)
.args(&[
@ -625,7 +625,7 @@ fn dont_collapse_args() {
Arg::new("arg3").help("some"),
]);
assert!(utils::compare_output(
app,
cmd,
"clap-test --help",
DONT_COLLAPSE_ARGS,
false
@ -634,7 +634,7 @@ fn dont_collapse_args() {
#[test]
fn require_eq() {
let app = App::new("clap-test").version("v1.4.8").arg(
let cmd = Command::new("clap-test").version("v1.4.8").arg(
Arg::new("opt")
.long("opt")
.short('o')
@ -644,7 +644,7 @@ fn require_eq() {
.help("some"),
);
assert!(utils::compare_output(
app,
cmd,
"clap-test --help",
REQUIRE_EQUALS,
false
@ -653,12 +653,14 @@ fn require_eq() {
#[test]
fn args_negate_subcommands_one_level() {
let res = App::new("disablehelp")
let res = Command::new("disablehelp")
.args_conflicts_with_subcommands(true)
.subcommand_negates_reqs(true)
.arg(arg!(<arg1> "some arg"))
.arg(arg!(<arg2> "some arg"))
.subcommand(App::new("sub1").subcommand(App::new("sub2").subcommand(App::new("sub3"))))
.subcommand(
Command::new("sub1").subcommand(Command::new("sub2").subcommand(Command::new("sub3"))),
)
.try_get_matches_from(vec!["", "pickles", "sub1"]);
assert!(res.is_ok(), "error: {:?}", res.unwrap_err().kind());
let m = res.unwrap();
@ -667,18 +669,18 @@ fn args_negate_subcommands_one_level() {
#[test]
fn args_negate_subcommands_two_levels() {
let res = App::new("disablehelp")
let res = Command::new("disablehelp")
.args_conflicts_with_subcommands(true)
.subcommand_negates_reqs(true)
.arg(arg!(<arg1> "some arg"))
.arg(arg!(<arg2> "some arg"))
.subcommand(
App::new("sub1")
Command::new("sub1")
.args_conflicts_with_subcommands(true)
.subcommand_negates_reqs(true)
.arg(arg!(<arg> "some"))
.arg(arg!(<arg2> "some"))
.subcommand(App::new("sub2").subcommand(App::new("sub3"))),
.subcommand(Command::new("sub2").subcommand(Command::new("sub3"))),
)
.try_get_matches_from(vec!["", "sub1", "arg", "sub2"]);
assert!(res.is_ok(), "error: {:?}", res.unwrap_err().kind());
@ -691,9 +693,9 @@ fn args_negate_subcommands_two_levels() {
#[test]
fn propagate_vals_down() {
let m = App::new("myprog")
let m = Command::new("myprog")
.arg(arg!([cmd] "command to run").global(true))
.subcommand(App::new("foo"))
.subcommand(Command::new("foo"))
.try_get_matches_from(vec!["myprog", "set", "foo"]);
assert!(m.is_ok(), "{:?}", m.unwrap_err().kind());
let m = m.unwrap();
@ -704,7 +706,7 @@ fn propagate_vals_down() {
#[test]
fn allow_missing_positional() {
let m = App::new("test")
let m = Command::new("test")
.allow_missing_positional(true)
.arg(arg!([src] "some file").default_value("src"))
.arg(arg!(<dest> "some file"))
@ -717,7 +719,7 @@ fn allow_missing_positional() {
#[test]
fn allow_missing_positional_no_default() {
let m = App::new("test")
let m = Command::new("test")
.allow_missing_positional(true)
.arg(arg!([src] "some file"))
.arg(arg!(<dest> "some file"))
@ -730,7 +732,7 @@ fn allow_missing_positional_no_default() {
#[test]
fn missing_positional_no_hyphen() {
let r = App::new("bench")
let r = Command::new("bench")
.allow_missing_positional(true)
.arg(arg!([BENCH] "some bench"))
.arg(arg!([ARGS] ... "some args"))
@ -751,7 +753,7 @@ fn missing_positional_no_hyphen() {
#[test]
fn missing_positional_hyphen() {
let r = App::new("bench")
let r = Command::new("bench")
.allow_missing_positional(true)
.arg(arg!([BENCH] "some bench"))
.arg(arg!([ARGS] ... "some args"))
@ -772,7 +774,7 @@ fn missing_positional_hyphen() {
#[test]
fn missing_positional_hyphen_far_back() {
let r = App::new("bench")
let r = Command::new("bench")
.allow_missing_positional(true)
.arg(arg!([BENCH1] "some bench"))
.arg(arg!([BENCH2] "some bench"))
@ -799,7 +801,7 @@ fn missing_positional_hyphen_far_back() {
#[test]
fn missing_positional_hyphen_req_error() {
let r = App::new("bench")
let r = Command::new("bench")
.allow_missing_positional(true)
.arg(arg!([BENCH1] "some bench"))
.arg(arg!(<BENCH2> "some bench"))
@ -811,7 +813,7 @@ fn missing_positional_hyphen_req_error() {
#[test]
fn issue_1066_allow_leading_hyphen_and_unknown_args() {
let res = App::new("prog")
let res = Command::new("prog")
.allow_hyphen_values(true)
.arg(arg!(--"some-argument"))
.try_get_matches_from(vec!["prog", "hello"]);
@ -822,7 +824,7 @@ fn issue_1066_allow_leading_hyphen_and_unknown_args() {
#[test]
fn issue_1066_allow_leading_hyphen_and_unknown_args_no_vals() {
let res = App::new("prog")
let res = Command::new("prog")
.allow_hyphen_values(true)
.arg(arg!(--"some-argument"))
.try_get_matches_from(vec!["prog", "--hello"]);
@ -833,7 +835,7 @@ fn issue_1066_allow_leading_hyphen_and_unknown_args_no_vals() {
#[test]
fn issue_1066_allow_leading_hyphen_and_unknown_args_option() {
let res = App::new("prog")
let res = Command::new("prog")
.allow_hyphen_values(true)
.arg(arg!(--"some-argument" <val>))
.try_get_matches_from(vec!["prog", "-hello"]);
@ -844,7 +846,7 @@ fn issue_1066_allow_leading_hyphen_and_unknown_args_option() {
#[test]
fn issue_1437_allow_hyphen_values_for_positional_arg() {
let m = App::new("tmp")
let m = Command::new("tmp")
.arg(
Arg::new("pat")
.allow_hyphen_values(true)
@ -858,11 +860,11 @@ fn issue_1437_allow_hyphen_values_for_positional_arg() {
#[test]
fn issue_1093_allow_ext_sc() {
let app = App::new("clap-test")
let cmd = Command::new("clap-test")
.version("v1.4.8")
.allow_external_subcommands(true);
assert!(utils::compare_output(
app,
cmd,
"clap-test --help",
ALLOW_EXT_SC,
false
@ -871,7 +873,7 @@ fn issue_1093_allow_ext_sc() {
#[test]
fn allow_ext_sc_when_sc_required() {
let res = App::new("clap-test")
let res = Command::new("clap-test")
.version("v1.4.8")
.allow_external_subcommands(true)
.allow_invalid_utf8_for_external_subcommands(true)
@ -891,11 +893,11 @@ fn allow_ext_sc_when_sc_required() {
#[test]
fn external_subcommand_looks_like_built_in() {
let res = App::new("cargo")
let res = Command::new("cargo")
.version("1.26.0")
.allow_external_subcommands(true)
.allow_invalid_utf8_for_external_subcommands(true)
.subcommand(App::new("install"))
.subcommand(Command::new("install"))
.try_get_matches_from(vec!["cargo", "install-update", "foo"]);
assert!(res.is_ok(), "{}", res.unwrap_err());
let m = res.unwrap();
@ -911,7 +913,7 @@ fn external_subcommand_looks_like_built_in() {
#[test]
fn aaos_flags() {
// flags
let res = App::new("posix")
let res = Command::new("posix")
.args_override_self(true)
.arg(arg!(--flag "some flag"))
.try_get_matches_from(vec!["", "--flag", "--flag"]);
@ -924,7 +926,7 @@ fn aaos_flags() {
#[test]
fn aaos_flags_mult() {
// flags with multiple
let res = App::new("posix")
let res = Command::new("posix")
.args_override_self(true)
.arg(arg!(--flag ... "some flag"))
.try_get_matches_from(vec!["", "--flag", "--flag", "--flag", "--flag"]);
@ -937,7 +939,7 @@ fn aaos_flags_mult() {
#[test]
fn aaos_opts() {
// opts
let res = App::new("posix")
let res = Command::new("posix")
.args_override_self(true)
.arg(arg!(--opt <val> "some option"))
.try_get_matches_from(vec!["", "--opt=some", "--opt=other"]);
@ -951,7 +953,7 @@ fn aaos_opts() {
#[test]
fn aaos_opts_w_other_overrides() {
// opts with other overrides
let res = App::new("posix")
let res = Command::new("posix")
.args_override_self(true)
.arg(arg!(--opt <val> "some option").required(false))
.arg(
@ -971,7 +973,7 @@ fn aaos_opts_w_other_overrides() {
#[test]
fn aaos_opts_w_other_overrides_rev() {
// opts with other overrides, rev
let res = App::new("posix")
let res = Command::new("posix")
.args_override_self(true)
.arg(arg!(--opt <val> "some option").required(true))
.arg(
@ -990,7 +992,7 @@ fn aaos_opts_w_other_overrides_rev() {
#[test]
fn aaos_opts_w_other_overrides_2() {
// opts with other overrides
let res = App::new("posix")
let res = Command::new("posix")
.args_override_self(true)
.arg(
arg!(--opt <val> "some option")
@ -1010,7 +1012,7 @@ fn aaos_opts_w_other_overrides_2() {
#[test]
fn aaos_opts_w_other_overrides_rev_2() {
// opts with other overrides, rev
let res = App::new("posix")
let res = Command::new("posix")
.args_override_self(true)
.arg(
arg!(--opt <val> "some option")
@ -1029,7 +1031,7 @@ fn aaos_opts_w_other_overrides_rev_2() {
#[test]
fn aaos_opts_mult() {
// opts with multiple
let res = App::new("posix")
let res = Command::new("posix")
.args_override_self(true)
.arg(
arg!(--opt <val> ... "some option")
@ -1052,7 +1054,7 @@ fn aaos_opts_mult() {
#[test]
fn aaos_opts_mult_req_delims() {
// opts with multiple and require delims
let res = App::new("posix")
let res = Command::new("posix")
.args_override_self(true)
.arg(arg!(--opt <val> ... "some option").multiple_values(true))
.try_get_matches_from(vec![
@ -1078,7 +1080,7 @@ fn aaos_opts_mult_req_delims() {
#[test]
fn aaos_pos_mult() {
// opts with multiple
let res = App::new("posix")
let res = Command::new("posix")
.args_override_self(true)
.arg(arg!([val] ... "some pos"))
.try_get_matches_from(vec!["", "some", "other", "value"]);
@ -1094,7 +1096,7 @@ fn aaos_pos_mult() {
#[test]
fn aaos_option_use_delim_false() {
let m = App::new("posix")
let m = Command::new("posix")
.args_override_self(true)
.arg(arg!(--opt <val> "some option").use_value_delimiter(false))
.try_get_matches_from(vec!["", "--opt=some,other", "--opt=one,two"])
@ -1109,21 +1111,21 @@ fn aaos_option_use_delim_false() {
#[test]
fn no_auto_help() {
let app = App::new("myprog")
let cmd = Command::new("myprog")
.setting(AppSettings::NoAutoHelp)
.subcommand(App::new("foo"));
.subcommand(Command::new("foo"));
let result = app.clone().try_get_matches_from("myprog --help".split(' '));
let result = cmd.clone().try_get_matches_from("myprog --help".split(' '));
assert!(result.is_ok(), "{}", result.unwrap_err());
assert!(result.unwrap().is_present("help"));
let result = app.clone().try_get_matches_from("myprog -h".split(' '));
let result = cmd.clone().try_get_matches_from("myprog -h".split(' '));
assert!(result.is_ok(), "{}", result.unwrap_err());
assert!(result.unwrap().is_present("help"));
let result = app.clone().try_get_matches_from("myprog help".split(' '));
let result = cmd.clone().try_get_matches_from("myprog help".split(' '));
assert!(result.is_ok(), "{}", result.unwrap_err());
assert_eq!(result.unwrap().subcommand_name(), Some("help"));
@ -1131,18 +1133,18 @@ fn no_auto_help() {
#[test]
fn no_auto_version() {
let app = App::new("myprog")
let cmd = Command::new("myprog")
.version("3.0")
.setting(AppSettings::NoAutoVersion);
let result = app
let result = cmd
.clone()
.try_get_matches_from("myprog --version".split(' '));
assert!(result.is_ok(), "{}", result.unwrap_err());
assert!(result.unwrap().is_present("version"));
let result = app.clone().try_get_matches_from("myprog -V".split(' '));
let result = cmd.clone().try_get_matches_from("myprog -V".split(' '));
assert!(result.is_ok(), "{}", result.unwrap_err());
assert!(result.unwrap().is_present("version"));
@ -1150,19 +1152,19 @@ fn no_auto_version() {
#[test]
fn no_auto_version_mut_arg() {
let app = App::new("myprog")
let cmd = Command::new("myprog")
.version("3.0")
.mut_arg("version", |v| v.help("custom help"))
.setting(AppSettings::NoAutoVersion);
let result = app
let result = cmd
.clone()
.try_get_matches_from("myprog --version".split(' '));
assert!(result.is_ok(), "{}", result.unwrap_err());
assert!(result.unwrap().is_present("version"));
let result = app.clone().try_get_matches_from("myprog -V".split(' '));
let result = cmd.clone().try_get_matches_from("myprog -V".split(' '));
assert!(result.is_ok(), "{}", result.unwrap_err());
assert!(result.unwrap().is_present("version"));
@ -1171,12 +1173,12 @@ fn no_auto_version_mut_arg() {
#[test]
#[cfg(feature = "color")]
fn color_is_global() {
let mut app = App::new("myprog")
let mut cmd = Command::new("myprog")
.color(clap::ColorChoice::Never)
.subcommand(App::new("foo"));
app._build_all();
assert_eq!(app.get_color(), clap::ColorChoice::Never);
.subcommand(Command::new("foo"));
cmd._build_all();
assert_eq!(cmd.get_color(), clap::ColorChoice::Never);
let sub = app.get_subcommands().collect::<Vec<_>>()[0];
let sub = cmd.get_subcommands().collect::<Vec<_>>()[0];
assert_eq!(sub.get_color(), clap::ColorChoice::Never);
}

View file

@ -1,6 +1,6 @@
use crate::utils;
use clap::{arg, App, Arg};
use clap::{arg, Arg, Command};
static SC_VISIBLE_ALIAS_HELP: &str = "ct-test 1.2
Some help
@ -30,7 +30,7 @@ OPTIONS:
#[test]
fn single_alias_of_option() {
let a = App::new("single_alias")
let a = Command::new("single_alias")
.arg(
Arg::new("alias")
.long("alias")
@ -47,7 +47,7 @@ fn single_alias_of_option() {
#[test]
fn multiple_aliases_of_option() {
let a = App::new("multiple_aliases").arg(
let a = Command::new("multiple_aliases").arg(
Arg::new("aliases")
.long("aliases")
.takes_value(true)
@ -90,7 +90,7 @@ fn multiple_aliases_of_option() {
#[test]
fn single_alias_of_flag() {
let a = App::new("test")
let a = Command::new("test")
.arg(Arg::new("flag").long("flag").alias("alias"))
.try_get_matches_from(vec!["", "--alias"]);
assert!(a.is_ok(), "{}", a.unwrap_err());
@ -100,7 +100,7 @@ fn single_alias_of_flag() {
#[test]
fn multiple_aliases_of_flag() {
let a = App::new("test").arg(Arg::new("flag").long("flag").aliases(&[
let a = Command::new("test").arg(Arg::new("flag").long("flag").aliases(&[
"invisible",
"set",
"of",
@ -132,9 +132,9 @@ fn multiple_aliases_of_flag() {
#[test]
fn alias_on_a_subcommand_option() {
let m = App::new("test")
let m = Command::new("test")
.subcommand(
App::new("some").arg(
Command::new("some").arg(
Arg::new("test")
.short('t')
.long("test")
@ -155,8 +155,8 @@ fn alias_on_a_subcommand_option() {
#[test]
fn invisible_arg_aliases_help_output() {
let app = App::new("ct").author("Salim Afiune").subcommand(
App::new("test")
let cmd = Command::new("ct").author("Salim Afiune").subcommand(
Command::new("test")
.about("Some help")
.version("1.2")
.arg(
@ -169,7 +169,7 @@ fn invisible_arg_aliases_help_output() {
.arg(arg!(-f - -flag).aliases(&["unseeable", "flg1", "anyway"])),
);
assert!(utils::compare_output(
app,
cmd,
"ct test --help",
SC_INVISIBLE_ALIAS_HELP,
false
@ -178,8 +178,8 @@ fn invisible_arg_aliases_help_output() {
#[test]
fn visible_arg_aliases_help_output() {
let app = App::new("ct").author("Salim Afiune").subcommand(
App::new("test")
let cmd = Command::new("ct").author("Salim Afiune").subcommand(
Command::new("test")
.about("Some help")
.version("1.2")
.arg(
@ -198,7 +198,7 @@ fn visible_arg_aliases_help_output() {
),
);
assert!(utils::compare_output(
app,
cmd,
"ct test --help",
SC_VISIBLE_ALIAS_HELP,
false

View file

@ -1,6 +1,6 @@
use crate::utils;
use clap::{arg, App, Arg};
use clap::{arg, Arg, Command};
static SC_VISIBLE_ALIAS_HELP: &str = "ct-test 1.2
Some help
@ -30,7 +30,7 @@ OPTIONS:
#[test]
fn single_short_alias_of_option() {
let a = App::new("single_alias")
let a = Command::new("single_alias")
.arg(
Arg::new("alias")
.long("alias")
@ -47,7 +47,7 @@ fn single_short_alias_of_option() {
#[test]
fn multiple_short_aliases_of_option() {
let a = App::new("multiple_aliases").arg(
let a = Command::new("multiple_aliases").arg(
Arg::new("aliases")
.long("aliases")
.takes_value(true)
@ -84,7 +84,7 @@ fn multiple_short_aliases_of_option() {
#[test]
fn single_short_alias_of_flag() {
let a = App::new("test")
let a = Command::new("test")
.arg(Arg::new("flag").long("flag").short_alias('f'))
.try_get_matches_from(vec!["", "-f"]);
assert!(a.is_ok(), "{}", a.unwrap_err());
@ -94,7 +94,7 @@ fn single_short_alias_of_flag() {
#[test]
fn multiple_short_aliases_of_flag() {
let a = App::new("test").arg(
let a = Command::new("test").arg(
Arg::new("flag")
.long("flag")
.short_aliases(&['a', 'b', 'c', 'd', 'e']),
@ -124,9 +124,9 @@ fn multiple_short_aliases_of_flag() {
#[test]
fn short_alias_on_a_subcommand_option() {
let m = App::new("test")
let m = Command::new("test")
.subcommand(
App::new("some").arg(
Command::new("some").arg(
Arg::new("test")
.short('t')
.long("test")
@ -151,8 +151,8 @@ fn short_alias_on_a_subcommand_option() {
#[test]
fn invisible_short_arg_aliases_help_output() {
let app = App::new("ct").author("Salim Afiune").subcommand(
App::new("test")
let cmd = Command::new("ct").author("Salim Afiune").subcommand(
Command::new("test")
.about("Some help")
.version("1.2")
.arg(
@ -165,7 +165,7 @@ fn invisible_short_arg_aliases_help_output() {
.arg(arg!(-f - -flag).short_aliases(&['x', 'y', 'z'])),
);
assert!(utils::compare_output(
app,
cmd,
"ct test --help",
SC_INVISIBLE_ALIAS_HELP,
false
@ -174,8 +174,8 @@ fn invisible_short_arg_aliases_help_output() {
#[test]
fn visible_short_arg_aliases_help_output() {
let app = App::new("ct").author("Salim Afiune").subcommand(
App::new("test")
let cmd = Command::new("ct").author("Salim Afiune").subcommand(
Command::new("test")
.about("Some help")
.version("1.2")
.arg(
@ -195,7 +195,7 @@ fn visible_short_arg_aliases_help_output() {
),
);
assert!(utils::compare_output(
app,
cmd,
"ct test --help",
SC_VISIBLE_ALIAS_HELP,
false

View file

@ -1,11 +1,11 @@
#[cfg(debug_assertions)]
use clap::{App, Arg};
use clap::{Arg, Command};
#[test]
#[cfg(debug_assertions)]
#[should_panic = "`f` is not a name of an argument or a group."]
fn arg_matches_if_present_wrong_arg() {
let m = App::new("test")
let m = Command::new("test")
.arg(Arg::new("flag").short('f'))
.try_get_matches_from(&["test", "-f"])
.unwrap();
@ -18,7 +18,7 @@ fn arg_matches_if_present_wrong_arg() {
#[cfg(debug_assertions)]
#[should_panic = "`o` is not a name of an argument or a group."]
fn arg_matches_value_of_wrong_arg() {
let m = App::new("test")
let m = Command::new("test")
.arg(Arg::new("opt").short('o').takes_value(true))
.try_get_matches_from(&["test", "-o", "val"])
.unwrap();
@ -31,8 +31,8 @@ fn arg_matches_value_of_wrong_arg() {
#[cfg(debug_assertions)]
#[should_panic = "`seed` is not a name of a subcommand."]
fn arg_matches_subcommand_matches_wrong_sub() {
let m = App::new("test")
.subcommand(App::new("speed"))
let m = Command::new("test")
.subcommand(Command::new("speed"))
.try_get_matches_from(&["test", "speed"])
.unwrap();

View file

@ -1,4 +1,4 @@
use clap::{App, Arg};
use clap::{Arg, Command};
#[test]
fn borrowed_args() {
@ -7,11 +7,11 @@ fn borrowed_args() {
.short('S')
.long("some-thing")
.help("other help");
let result = App::new("sub_command_negate")
let result = Command::new("sub_command_negate")
.arg(Arg::new("test").index(1))
.arg(&arg)
.arg(&arg2)
.subcommand(App::new("sub1").arg(&arg))
.subcommand(Command::new("sub1").arg(&arg))
.try_get_matches_from(vec!["prog"]);
assert!(result.is_ok(), "{}", result.unwrap_err());
}

View file

@ -1,6 +1,8 @@
#![cfg(feature = "cargo")]
use clap::{crate_authors, crate_description, crate_name, crate_version, error::ErrorKind, App};
use clap::{
crate_authors, crate_description, crate_name, crate_version, error::ErrorKind, Command,
};
static DESCRIPTION_ONLY: &str = "prog 1
A simple to use, efficient, and full-featured Command Line Argument Parser
@ -26,7 +28,7 @@ OPTIONS:
#[test]
fn crate_version() {
let res = App::new("prog")
let res = Command::new("prog")
.version(crate_version!())
.try_get_matches_from(vec!["prog", "--version"]);
@ -41,7 +43,7 @@ fn crate_version() {
#[test]
fn crate_description() {
let res = App::new("prog")
let res = Command::new("prog")
.version("1")
.about(crate_description!())
.try_get_matches_from(vec!["prog", "--help"]);
@ -54,7 +56,7 @@ fn crate_description() {
#[test]
fn crate_authors() {
let res = App::new("prog")
let res = Command::new("prog")
.version("1")
.author(crate_authors!())
.try_get_matches_from(vec!["prog", "--help"]);
@ -67,7 +69,7 @@ fn crate_authors() {
#[test]
fn crate_name() {
let res = App::new(crate_name!())
let res = Command::new(crate_name!())
.version("3.0")
.try_get_matches_from(vec!["clap", "--version"]);

View file

@ -1,6 +1,6 @@
use crate::utils;
use clap::{arg, error::ErrorKind, App, Arg, ArgGroup};
use clap::{arg, error::ErrorKind, Arg, ArgGroup, Command};
static CONFLICT_ERR: &str = "error: The argument '--flag' cannot be used with '-F'
@ -30,7 +30,7 @@ For more information try --help
#[test]
fn flag_conflict() {
let result = App::new("flag_conflict")
let result = Command::new("flag_conflict")
.arg(arg!(-f --flag "some flag").conflicts_with("other"))
.arg(arg!(-o --other "some flag"))
.try_get_matches_from(vec!["myprog", "-f", "-o"]);
@ -41,7 +41,7 @@ fn flag_conflict() {
#[test]
fn flag_conflict_2() {
let result = App::new("flag_conflict")
let result = Command::new("flag_conflict")
.arg(arg!(-f --flag "some flag").conflicts_with("other"))
.arg(arg!(-o --other "some flag"))
.try_get_matches_from(vec!["myprog", "-o", "-f"]);
@ -52,7 +52,7 @@ fn flag_conflict_2() {
#[test]
fn flag_conflict_with_all() {
let result = App::new("flag_conflict")
let result = Command::new("flag_conflict")
.arg(arg!(-f --flag "some flag").conflicts_with_all(&["other"]))
.arg(arg!(-o --other "some flag"))
.try_get_matches_from(vec!["myprog", "-o", "-f"]);
@ -63,7 +63,7 @@ fn flag_conflict_with_all() {
#[test]
fn flag_conflict_with_everything() {
let result = App::new("flag_conflict")
let result = Command::new("flag_conflict")
.arg(arg!(-f --flag "some flag").exclusive(true))
.arg(arg!(-o --other "some flag"))
.try_get_matches_from(vec!["myprog", "-o", "-f"]);
@ -74,33 +74,33 @@ fn flag_conflict_with_everything() {
#[test]
fn arg_conflicts_with_group() {
let mut app = App::new("group_conflict")
let mut cmd = Command::new("group_conflict")
.arg(arg!(-f --flag "some flag").conflicts_with("gr"))
.group(ArgGroup::new("gr").arg("some").arg("other"))
.arg(arg!(--some "some arg"))
.arg(arg!(--other "other arg"));
let result = app.try_get_matches_from_mut(vec!["myprog", "--other", "-f"]);
let result = cmd.try_get_matches_from_mut(vec!["myprog", "--other", "-f"]);
assert!(result.is_err());
let err = result.err().unwrap();
assert_eq!(err.kind(), ErrorKind::ArgumentConflict);
let result = app.try_get_matches_from_mut(vec!["myprog", "-f", "--some"]);
let result = cmd.try_get_matches_from_mut(vec!["myprog", "-f", "--some"]);
assert!(result.is_err());
let err = result.err().unwrap();
assert_eq!(err.kind(), ErrorKind::ArgumentConflict);
let result = app.try_get_matches_from_mut(vec!["myprog", "--some"]);
let result = cmd.try_get_matches_from_mut(vec!["myprog", "--some"]);
if let Err(err) = result {
panic!("{}", err);
}
let result = app.try_get_matches_from_mut(vec!["myprog", "--other"]);
let result = cmd.try_get_matches_from_mut(vec!["myprog", "--other"]);
if let Err(err) = result {
panic!("{}", err);
}
let result = app.try_get_matches_from_mut(vec!["myprog", "--flag"]);
let result = cmd.try_get_matches_from_mut(vec!["myprog", "--flag"]);
if let Err(err) = result {
panic!("{}", err);
}
@ -108,7 +108,7 @@ fn arg_conflicts_with_group() {
#[test]
fn arg_conflicts_with_group_with_multiple_sources() {
let mut app = clap::App::new("group_conflict")
let mut cmd = clap::Command::new("group_conflict")
.arg(clap::arg!(-f --flag "some flag").conflicts_with("gr"))
.group(clap::ArgGroup::new("gr").multiple(true))
.arg(
@ -123,29 +123,29 @@ fn arg_conflicts_with_group_with_multiple_sources() {
.group("gr"),
);
let result = app.try_get_matches_from_mut(vec!["myprog", "-f"]);
let result = cmd.try_get_matches_from_mut(vec!["myprog", "-f"]);
if let Err(err) = result {
panic!("{}", err);
}
let result = app.try_get_matches_from_mut(vec!["myprog", "--some", "usb1"]);
let result = cmd.try_get_matches_from_mut(vec!["myprog", "--some", "usb1"]);
if let Err(err) = result {
panic!("{}", err);
}
let result = app.try_get_matches_from_mut(vec!["myprog", "--some", "usb1", "--other", "40"]);
let result = cmd.try_get_matches_from_mut(vec!["myprog", "--some", "usb1", "--other", "40"]);
if let Err(err) = result {
panic!("{}", err);
}
let result = app.try_get_matches_from_mut(vec!["myprog", "-f", "--some", "usb1"]);
let result = cmd.try_get_matches_from_mut(vec!["myprog", "-f", "--some", "usb1"]);
let err = result.err().unwrap();
assert_eq!(err.kind(), ErrorKind::ArgumentConflict);
}
#[test]
fn group_conflicts_with_arg() {
let mut app = App::new("group_conflict")
let mut cmd = Command::new("group_conflict")
.arg(arg!(-f --flag "some flag"))
.group(
ArgGroup::new("gr")
@ -156,27 +156,27 @@ fn group_conflicts_with_arg() {
.arg(arg!(--some "some arg"))
.arg(arg!(--other "other arg"));
let result = app.try_get_matches_from_mut(vec!["myprog", "--other", "-f"]);
let result = cmd.try_get_matches_from_mut(vec!["myprog", "--other", "-f"]);
assert!(result.is_err());
let err = result.err().unwrap();
assert_eq!(err.kind(), ErrorKind::ArgumentConflict);
let result = app.try_get_matches_from_mut(vec!["myprog", "-f", "--some"]);
let result = cmd.try_get_matches_from_mut(vec!["myprog", "-f", "--some"]);
assert!(result.is_err());
let err = result.err().unwrap();
assert_eq!(err.kind(), ErrorKind::ArgumentConflict);
let result = app.try_get_matches_from_mut(vec!["myprog", "--some"]);
let result = cmd.try_get_matches_from_mut(vec!["myprog", "--some"]);
if let Err(err) = result {
panic!("{}", err);
}
let result = app.try_get_matches_from_mut(vec!["myprog", "--other"]);
let result = cmd.try_get_matches_from_mut(vec!["myprog", "--other"]);
if let Err(err) = result {
panic!("{}", err);
}
let result = app.try_get_matches_from_mut(vec!["myprog", "--flag"]);
let result = cmd.try_get_matches_from_mut(vec!["myprog", "--flag"]);
if let Err(err) = result {
panic!("{}", err);
}
@ -184,28 +184,28 @@ fn group_conflicts_with_arg() {
#[test]
fn arg_conflicts_with_required_group() {
let mut app = App::new("group_conflict")
let mut cmd = Command::new("group_conflict")
.arg(arg!(-f --flag "some flag").conflicts_with("gr"))
.group(ArgGroup::new("gr").required(true).arg("some").arg("other"))
.arg(arg!(--some "some arg"))
.arg(arg!(--other "other arg"));
let result = app.try_get_matches_from_mut(vec!["myprog", "--other", "-f"]);
let result = cmd.try_get_matches_from_mut(vec!["myprog", "--other", "-f"]);
assert!(result.is_err());
let err = result.err().unwrap();
assert_eq!(err.kind(), ErrorKind::ArgumentConflict);
let result = app.try_get_matches_from_mut(vec!["myprog", "-f", "--some"]);
let result = cmd.try_get_matches_from_mut(vec!["myprog", "-f", "--some"]);
assert!(result.is_err());
let err = result.err().unwrap();
assert_eq!(err.kind(), ErrorKind::ArgumentConflict);
let result = app.try_get_matches_from_mut(vec!["myprog", "--some"]);
let result = cmd.try_get_matches_from_mut(vec!["myprog", "--some"]);
if let Err(err) = result {
panic!("{}", err);
}
let result = app.try_get_matches_from_mut(vec!["myprog", "--other"]);
let result = cmd.try_get_matches_from_mut(vec!["myprog", "--other"]);
if let Err(err) = result {
panic!("{}", err);
}
@ -213,7 +213,7 @@ fn arg_conflicts_with_required_group() {
#[test]
fn required_group_conflicts_with_arg() {
let mut app = App::new("group_conflict")
let mut cmd = Command::new("group_conflict")
.arg(arg!(-f --flag "some flag"))
.group(
ArgGroup::new("gr")
@ -225,22 +225,22 @@ fn required_group_conflicts_with_arg() {
.arg(arg!(--some "some arg"))
.arg(arg!(--other "other arg"));
let result = app.try_get_matches_from_mut(vec!["myprog", "--other", "-f"]);
let result = cmd.try_get_matches_from_mut(vec!["myprog", "--other", "-f"]);
assert!(result.is_err());
let err = result.err().unwrap();
assert_eq!(err.kind(), ErrorKind::ArgumentConflict);
let result = app.try_get_matches_from_mut(vec!["myprog", "-f", "--some"]);
let result = cmd.try_get_matches_from_mut(vec!["myprog", "-f", "--some"]);
assert!(result.is_err());
let err = result.err().unwrap();
assert_eq!(err.kind(), ErrorKind::ArgumentConflict);
let result = app.try_get_matches_from_mut(vec!["myprog", "--some"]);
let result = cmd.try_get_matches_from_mut(vec!["myprog", "--some"]);
if let Err(err) = result {
panic!("{}", err);
}
let result = app.try_get_matches_from_mut(vec!["myprog", "--other"]);
let result = cmd.try_get_matches_from_mut(vec!["myprog", "--other"]);
if let Err(err) = result {
panic!("{}", err);
}
@ -288,7 +288,7 @@ fn conflict_output_rev_with_required() {
#[test]
fn conflict_output_three_conflicting() {
let app = App::new("three_conflicting_arguments")
let cmd = Command::new("three_conflicting_arguments")
.arg(
Arg::new("one")
.long("one")
@ -305,7 +305,7 @@ fn conflict_output_three_conflicting() {
.conflicts_with_all(&["one", "two"]),
);
assert!(utils::compare_output(
app,
cmd,
"three_conflicting_arguments --one --two --three",
CONFLICT_ERR_THREE,
true,
@ -314,7 +314,7 @@ fn conflict_output_three_conflicting() {
#[test]
fn two_conflicting_arguments() {
let a = App::new("two_conflicting_arguments")
let a = Command::new("two_conflicting_arguments")
.arg(
Arg::new("develop")
.long("develop")
@ -339,7 +339,7 @@ fn two_conflicting_arguments() {
#[test]
fn three_conflicting_arguments() {
let a = App::new("three_conflicting_arguments")
let a = Command::new("three_conflicting_arguments")
.arg(
Arg::new("one")
.long("one")
@ -371,7 +371,7 @@ fn three_conflicting_arguments() {
#[test]
#[should_panic = "Argument 'config' cannot conflict with itself"]
fn self_conflicting_arg() {
let _ = App::new("prog")
let _ = Command::new("prog")
.arg(Arg::new("config").long("config").conflicts_with("config"))
.try_get_matches_from(vec!["", "--config"]);
}
@ -380,14 +380,14 @@ fn self_conflicting_arg() {
#[test]
#[should_panic = "Argument or group 'extra' specified in 'conflicts_with*' for 'config' does not exist"]
fn conflicts_with_invalid_arg() {
let _ = App::new("prog")
let _ = Command::new("prog")
.arg(Arg::new("config").long("config").conflicts_with("extra"))
.try_get_matches_from(vec!["", "--config"]);
}
#[test]
fn conflict_with_unused_default() {
let result = App::new("conflict")
let result = Command::new("conflict")
.arg(
arg!(-o --opt <opt> "some opt")
.required(false)
@ -405,7 +405,7 @@ fn conflict_with_unused_default() {
#[test]
fn conflicts_with_alongside_default() {
let result = App::new("conflict")
let result = Command::new("conflict")
.arg(
arg!(-o --opt <opt> "some opt")
.default_value("default")
@ -428,7 +428,7 @@ fn conflicts_with_alongside_default() {
#[test]
fn group_in_conflicts_with() {
let result = App::new("conflict")
let result = Command::new("conflict")
.arg(
Arg::new("opt")
.long("opt")
@ -451,7 +451,7 @@ fn group_in_conflicts_with() {
#[test]
fn group_conflicts_with_default_value() {
let result = App::new("conflict")
let result = Command::new("conflict")
.arg(
Arg::new("opt")
.long("opt")
@ -474,7 +474,7 @@ fn group_conflicts_with_default_value() {
#[test]
fn group_conflicts_with_default_arg() {
let result = App::new("conflict")
let result = Command::new("conflict")
.arg(Arg::new("opt").long("opt").default_value("default"))
.arg(Arg::new("flag").long("flag").group("one"))
.group(ArgGroup::new("one").conflicts_with("opt"))

View file

@ -1,8 +1,8 @@
use clap::{arg, App, Arg, ArgMatches};
use clap::{arg, Arg, ArgMatches, Command};
#[test]
fn opt_missing() {
let r = App::new("df")
let r = Command::new("df")
.arg(
Arg::new("color")
.long("color")
@ -21,7 +21,7 @@ fn opt_missing() {
#[test]
fn opt_present_with_missing_value() {
let r = App::new("df")
let r = Command::new("df")
.arg(
Arg::new("color")
.long("color")
@ -40,7 +40,7 @@ fn opt_present_with_missing_value() {
#[test]
fn opt_present_with_value() {
let r = App::new("df")
let r = Command::new("df")
.arg(
Arg::new("color")
.long("color")
@ -59,7 +59,7 @@ fn opt_present_with_value() {
#[test]
fn opt_present_with_empty_value() {
let r = App::new("df")
let r = Command::new("df")
.arg(
Arg::new("color")
.long("color")
@ -80,7 +80,7 @@ fn opt_present_with_empty_value() {
#[test]
fn opt_default() {
// assert no change to usual argument handling when adding default_missing_value()
let r = App::new("app")
let r = Command::new("cmd")
.arg(
arg!(o: -o [opt] "some opt")
.default_value("default")
@ -96,7 +96,7 @@ fn opt_default() {
#[test]
fn opt_default_user_override() {
// assert no change to usual argument handling when adding default_missing_value()
let r = App::new("app")
let r = Command::new("cmd")
.arg(
arg!(o: -o [opt] "some opt")
.default_value("default")
@ -112,7 +112,7 @@ fn opt_default_user_override() {
#[test]
#[allow(clippy::bool_assert_comparison)]
fn default_missing_value_flag_value() {
let app = App::new("test").arg(
let cmd = Command::new("test").arg(
Arg::new("flag")
.long("flag")
.takes_value(true)
@ -127,12 +127,12 @@ fn default_missing_value_flag_value() {
}
assert_eq!(
flag_value(app.clone().try_get_matches_from(&["test"]).unwrap()),
flag_value(cmd.clone().try_get_matches_from(&["test"]).unwrap()),
false
);
assert_eq!(
flag_value(
app.clone()
cmd.clone()
.try_get_matches_from(&["test", "--flag"])
.unwrap()
),
@ -140,7 +140,7 @@ fn default_missing_value_flag_value() {
);
assert_eq!(
flag_value(
app.clone()
cmd.clone()
.try_get_matches_from(&["test", "--flag=true"])
.unwrap()
),
@ -148,7 +148,7 @@ fn default_missing_value_flag_value() {
);
assert_eq!(
flag_value(
app.clone()
cmd.clone()
.try_get_matches_from(&["test", "--flag=false"])
.unwrap()
),
@ -160,9 +160,9 @@ fn default_missing_value_flag_value() {
#[test]
#[should_panic = "Argument `arg`'s default_missing_value=value doesn't match possible values"]
fn default_missing_values_are_possible_values() {
use clap::{App, Arg};
use clap::{Arg, Command};
let _ = App::new("test")
let _ = Command::new("test")
.arg(
Arg::new("arg")
.possible_values(["one", "two"])
@ -175,9 +175,9 @@ fn default_missing_values_are_possible_values() {
#[test]
#[should_panic = "Argument `arg`'s default_missing_value=value failed validation: invalid digit found in string"]
fn default_missing_values_are_valid() {
use clap::{App, Arg};
use clap::{Arg, Command};
let _ = App::new("test")
let _ = Command::new("test")
.arg(
Arg::new("arg")
.validator(|val| val.parse::<u32>().map_err(|e| e.to_string()))

View file

@ -1,9 +1,9 @@
use crate::utils;
use clap::{arg, error::ErrorKind, App, Arg};
use clap::{arg, error::ErrorKind, Arg, Command};
#[test]
fn opts() {
let r = App::new("df")
let r = Command::new("df")
.arg(
arg!(o: -o <opt> "some opt")
.required(false)
@ -18,7 +18,7 @@ fn opts() {
#[test]
fn opt_without_value_fail() {
let r = App::new("df")
let r = Command::new("df")
.arg(
arg!(o: -o <opt> "some opt")
.required(false)
@ -36,7 +36,7 @@ fn opt_without_value_fail() {
#[test]
fn opt_user_override() {
let r = App::new("df")
let r = Command::new("df")
.arg(
arg!(--opt <FILE> "some arg")
.required(false)
@ -51,7 +51,7 @@ fn opt_user_override() {
#[test]
fn positionals() {
let r = App::new("df")
let r = Command::new("df")
.arg(arg!([arg] "some opt").default_value("default"))
.try_get_matches_from(vec![""]);
assert!(r.is_ok(), "{}", r.unwrap_err());
@ -62,7 +62,7 @@ fn positionals() {
#[test]
fn positional_user_override() {
let r = App::new("df")
let r = Command::new("df")
.arg(arg!([arg] "some arg").default_value("default"))
.try_get_matches_from(vec!["", "value"]);
assert!(r.is_ok(), "{}", r.unwrap_err());
@ -78,7 +78,7 @@ fn osstr_opts() {
use std::ffi::OsStr;
let expected = OsStr::new("default");
let r = App::new("df")
let r = Command::new("df")
.arg(
arg!(o: -o <opt> "some opt")
.required(false)
@ -96,7 +96,7 @@ fn osstr_opt_user_override() {
use std::ffi::OsStr;
let default = OsStr::new("default");
let r = App::new("df")
let r = Command::new("df")
.arg(
arg!(--opt <FILE> "some arg")
.required(false)
@ -114,7 +114,7 @@ fn osstr_positionals() {
use std::ffi::OsStr;
let expected = OsStr::new("default");
let r = App::new("df")
let r = Command::new("df")
.arg(arg!([arg] "some opt").default_value_os(expected))
.try_get_matches_from(vec![""]);
assert!(r.is_ok(), "{}", r.unwrap_err());
@ -128,7 +128,7 @@ fn osstr_positional_user_override() {
use std::ffi::OsStr;
let default = OsStr::new("default");
let r = App::new("df")
let r = Command::new("df")
.arg(arg!([arg] "some arg").default_value_os(default))
.try_get_matches_from(vec!["", "value"]);
assert!(r.is_ok(), "{}", r.unwrap_err());
@ -141,7 +141,7 @@ fn osstr_positional_user_override() {
#[test]
fn default_if_arg_present_no_default() {
let r = App::new("df")
let r = Command::new("df")
.arg(arg!(--opt <FILE> "some arg").required(true))
.arg(arg!([arg] "some arg").default_value_if("opt", None, Some("default")))
.try_get_matches_from(vec!["", "--opt", "some"]);
@ -153,7 +153,7 @@ fn default_if_arg_present_no_default() {
#[test]
fn default_if_arg_present_no_default_user_override() {
let r = App::new("df")
let r = Command::new("df")
.arg(arg!(--opt <FILE> "some arg").required(false))
.arg(arg!([arg] "some arg").default_value_if("opt", None, Some("default")))
.try_get_matches_from(vec!["", "--opt", "some", "other"]);
@ -165,7 +165,7 @@ fn default_if_arg_present_no_default_user_override() {
#[test]
fn default_if_arg_present_no_arg_with_default() {
let r = App::new("df")
let r = Command::new("df")
.arg(arg!(--opt <FILE> "some arg").required(false))
.arg(
arg!([arg] "some arg")
@ -181,7 +181,7 @@ fn default_if_arg_present_no_arg_with_default() {
#[test]
fn default_if_arg_present_with_default() {
let r = App::new("df")
let r = Command::new("df")
.arg(arg!(--opt <FILE> "some arg").required(false))
.arg(
arg!([arg] "some arg")
@ -197,7 +197,7 @@ fn default_if_arg_present_with_default() {
#[test]
fn default_if_arg_present_with_default_user_override() {
let r = App::new("df")
let r = Command::new("df")
.arg(arg!(--opt <FILE> "some arg").required(false))
.arg(
arg!([arg] "some arg")
@ -213,7 +213,7 @@ fn default_if_arg_present_with_default_user_override() {
#[test]
fn default_if_arg_present_no_arg_with_default_user_override() {
let r = App::new("df")
let r = Command::new("df")
.arg(arg!(--opt <FILE> "some arg").required(false))
.arg(
arg!([arg] "some arg")
@ -231,7 +231,7 @@ fn default_if_arg_present_no_arg_with_default_user_override() {
#[test]
fn default_if_arg_present_with_value_no_default() {
let r = App::new("df")
let r = Command::new("df")
.arg(arg!(--opt <FILE> "some arg").required(false))
.arg(arg!([arg] "some arg").default_value_if("opt", Some("value"), Some("default")))
.try_get_matches_from(vec!["", "--opt", "value"]);
@ -243,7 +243,7 @@ fn default_if_arg_present_with_value_no_default() {
#[test]
fn default_if_arg_present_with_value_no_default_fail() {
let r = App::new("df")
let r = Command::new("df")
.arg(arg!(--opt <FILE> "some arg").required(false))
.arg(arg!([arg] "some arg").default_value_if("opt", Some("value"), Some("default")))
.try_get_matches_from(vec!["", "--opt", "other"]);
@ -255,7 +255,7 @@ fn default_if_arg_present_with_value_no_default_fail() {
#[test]
fn default_if_arg_present_with_value_no_default_user_override() {
let r = App::new("df")
let r = Command::new("df")
.arg(arg!(--opt <FILE> "some arg").required(false))
.arg(arg!([arg] "some arg").default_value_if("opt", Some("some"), Some("default")))
.try_get_matches_from(vec!["", "--opt", "some", "other"]);
@ -267,7 +267,7 @@ fn default_if_arg_present_with_value_no_default_user_override() {
#[test]
fn default_if_arg_present_with_value_no_arg_with_default() {
let r = App::new("df")
let r = Command::new("df")
.arg(arg!(--opt <FILE> "some arg").required(false))
.arg(
arg!([arg] "some arg")
@ -283,7 +283,7 @@ fn default_if_arg_present_with_value_no_arg_with_default() {
#[test]
fn default_if_arg_present_with_value_no_arg_with_default_fail() {
let r = App::new("df")
let r = Command::new("df")
.arg(arg!(--opt <FILE> "some arg").required(false))
.arg(
arg!([arg] "some arg")
@ -299,7 +299,7 @@ fn default_if_arg_present_with_value_no_arg_with_default_fail() {
#[test]
fn default_if_arg_present_with_value_with_default() {
let r = App::new("df")
let r = Command::new("df")
.arg(arg!(--opt <FILE> "some arg").required(false))
.arg(
arg!([arg] "some arg")
@ -315,7 +315,7 @@ fn default_if_arg_present_with_value_with_default() {
#[test]
fn default_if_arg_present_with_value_with_default_user_override() {
let r = App::new("df")
let r = Command::new("df")
.arg(arg!(--opt <FILE> "some arg").required(false))
.arg(
arg!([arg] "some arg")
@ -331,7 +331,7 @@ fn default_if_arg_present_with_value_with_default_user_override() {
#[test]
fn default_if_arg_present_no_arg_with_value_with_default_user_override() {
let r = App::new("df")
let r = Command::new("df")
.arg(arg!(--opt <FILE> "some arg").required(false))
.arg(
arg!([arg] "some arg")
@ -347,7 +347,7 @@ fn default_if_arg_present_no_arg_with_value_with_default_user_override() {
#[test]
fn default_if_arg_present_no_arg_with_value_with_default_user_override_fail() {
let r = App::new("df")
let r = Command::new("df")
.arg(arg!(--opt <FILE> "some arg").required(false))
.arg(
arg!([arg] "some arg")
@ -365,7 +365,7 @@ fn default_if_arg_present_no_arg_with_value_with_default_user_override_fail() {
#[test]
fn no_default_if_arg_present_with_value_no_default() {
let r = App::new("df")
let r = Command::new("df")
.arg(arg!(--opt <FILE> "some arg").required(false))
.arg(arg!([arg] "some arg").default_value_if("opt", Some("value"), None))
.try_get_matches_from(vec!["", "--opt", "value"]);
@ -376,7 +376,7 @@ fn no_default_if_arg_present_with_value_no_default() {
#[test]
fn no_default_if_arg_present_with_value_with_default() {
let r = App::new("df")
let r = Command::new("df")
.arg(arg!(--opt <FILE> "some arg").required(false))
.arg(
arg!([arg] "some arg")
@ -392,7 +392,7 @@ fn no_default_if_arg_present_with_value_with_default() {
#[test]
fn no_default_if_arg_present_with_value_with_default_user_override() {
let r = App::new("df")
let r = Command::new("df")
.arg(arg!(--opt <FILE> "some arg").required(false))
.arg(
arg!([arg] "some arg")
@ -408,7 +408,7 @@ fn no_default_if_arg_present_with_value_with_default_user_override() {
#[test]
fn no_default_if_arg_present_no_arg_with_value_with_default() {
let r = App::new("df")
let r = Command::new("df")
.arg(arg!(--opt <FILE> "some arg").required(false))
.arg(
arg!([arg] "some arg")
@ -426,7 +426,7 @@ fn no_default_if_arg_present_no_arg_with_value_with_default() {
#[test]
fn default_ifs_arg_present() {
let r = App::new("df")
let r = Command::new("df")
.arg(arg!(--opt <FILE> "some arg").required(false))
.arg(arg!(--flag "some arg"))
.arg(
@ -446,7 +446,7 @@ fn default_ifs_arg_present() {
#[test]
fn no_default_ifs_arg_present() {
let r = App::new("df")
let r = Command::new("df")
.arg(arg!(--opt <FILE> "some arg").required(false))
.arg(arg!(--flag "some arg"))
.arg(
@ -463,7 +463,7 @@ fn no_default_ifs_arg_present() {
#[test]
fn default_ifs_arg_present_user_override() {
let r = App::new("df")
let r = Command::new("df")
.arg(arg!(--opt <FILE> "some arg").required(false))
.arg(arg!(--flag "some arg"))
.arg(
@ -483,7 +483,7 @@ fn default_ifs_arg_present_user_override() {
#[test]
fn default_ifs_arg_present_order() {
let r = App::new("df")
let r = Command::new("df")
.arg(arg!(--opt <FILE> "some arg").required(false))
.arg(arg!(--flag "some arg"))
.arg(
@ -505,7 +505,7 @@ fn default_ifs_arg_present_order() {
#[test]
fn conditional_reqs_pass() {
let m = App::new("Test app")
let m = Command::new("Test cmd")
.arg(
Arg::new("target")
.takes_value(true)
@ -534,7 +534,7 @@ fn conditional_reqs_pass() {
#[test]
fn multiple_defaults() {
let r = App::new("diff")
let r = Command::new("diff")
.arg(
Arg::new("files")
.long("files")
@ -551,7 +551,7 @@ fn multiple_defaults() {
#[test]
fn multiple_defaults_override() {
let r = App::new("diff")
let r = Command::new("diff")
.arg(
Arg::new("files")
.long("files")
@ -568,7 +568,7 @@ fn multiple_defaults_override() {
#[test]
fn default_vals_donnot_show_in_smart_usage() {
let app = App::new("bug")
let cmd = Command::new("bug")
.arg(
Arg::new("foo")
.long("config")
@ -578,7 +578,7 @@ fn default_vals_donnot_show_in_smart_usage() {
.arg(Arg::new("input").required(true));
assert!(utils::compare_output(
app,
cmd,
"bug",
"error: The following required arguments were not provided:
<input>
@ -594,7 +594,7 @@ For more information try --help
#[test]
fn issue_1050_num_vals_and_defaults() {
let res = App::new("hello")
let res = Command::new("hello")
.arg(
Arg::new("exit-code")
.long("exit-code")
@ -612,9 +612,9 @@ fn issue_1050_num_vals_and_defaults() {
#[test]
#[should_panic = "Argument group 'group' is required but all of it's arguments have a default value."]
fn required_groups_with_default_values() {
use clap::{App, Arg, ArgGroup};
use clap::{Arg, ArgGroup, Command};
let _ = App::new("test")
let _ = Command::new("test")
.arg(Arg::new("arg").default_value("value"))
.group(ArgGroup::new("group").args(&["arg"]).required(true))
.try_get_matches();
@ -624,9 +624,9 @@ fn required_groups_with_default_values() {
#[test]
#[should_panic = "Argument 'arg' is required and can't have a default value"]
fn required_args_with_default_values() {
use clap::{App, Arg};
use clap::{Arg, Command};
let _ = App::new("test")
let _ = Command::new("test")
.arg(Arg::new("arg").required(true).default_value("value"))
.try_get_matches();
}
@ -635,9 +635,9 @@ fn required_args_with_default_values() {
#[test]
#[should_panic = "Argument `arg`'s default_value=value doesn't match possible values"]
fn default_values_are_possible_values() {
use clap::{App, Arg};
use clap::{Arg, Command};
let _ = App::new("test")
let _ = Command::new("test")
.arg(
Arg::new("arg")
.possible_values(["one", "two"])
@ -650,9 +650,9 @@ fn default_values_are_possible_values() {
#[test]
#[should_panic = "Argument `arg`'s default_value=value failed validation: invalid digit found in string"]
fn default_values_are_valid() {
use clap::{App, Arg};
use clap::{Arg, Command};
let _ = App::new("test")
let _ = Command::new("test")
.arg(
Arg::new("arg")
.validator(|val| val.parse::<u32>().map_err(|e| e.to_string()))
@ -663,7 +663,7 @@ fn default_values_are_valid() {
#[test]
fn with_value_delimiter() {
let app = App::new("multiple_values").arg(
let cmd = Command::new("multiple_values").arg(
Arg::new("option")
.long("option")
.help("multiple options")
@ -671,7 +671,7 @@ fn with_value_delimiter() {
.default_value("first;second"),
);
let matches = app.try_get_matches_from(vec![""]).unwrap();
let matches = cmd.try_get_matches_from(vec![""]).unwrap();
assert_eq!(
matches.values_of("option").unwrap().collect::<Vec<_>>(),
@ -681,14 +681,14 @@ fn with_value_delimiter() {
#[test]
fn missing_with_value_delimiter() {
let app = App::new("program").arg(
let cmd = Command::new("program").arg(
Arg::new("option")
.long("option")
.value_delimiter(';')
.default_missing_values(&["value1;value2;value3", "value4;value5"]),
);
let matches = app
let matches = cmd
.try_get_matches_from(vec!["program", "--option"])
.unwrap();

View file

@ -1,8 +1,8 @@
use clap::{App, Arg};
use clap::{Arg, Command};
#[test]
fn opt_default_no_delim() {
let m = App::new("no_delim")
let m = Command::new("no_delim")
.arg(Arg::new("option").long("option").takes_value(true))
.try_get_matches_from(vec!["", "--option", "val1,val2,val3"]);
@ -16,7 +16,7 @@ fn opt_default_no_delim() {
#[test]
fn opt_eq_no_delim() {
let m = App::new("no_delim")
let m = Command::new("no_delim")
.arg(Arg::new("option").long("option").takes_value(true))
.try_get_matches_from(vec!["", "--option=val1,val2,val3"]);
@ -30,7 +30,7 @@ fn opt_eq_no_delim() {
#[test]
fn opt_s_eq_no_delim() {
let m = App::new("no_delim")
let m = Command::new("no_delim")
.arg(Arg::new("option").short('o').takes_value(true))
.try_get_matches_from(vec!["", "-o=val1,val2,val3"]);
@ -44,7 +44,7 @@ fn opt_s_eq_no_delim() {
#[test]
fn opt_s_default_no_delim() {
let m = App::new("no_delim")
let m = Command::new("no_delim")
.arg(Arg::new("option").short('o').takes_value(true))
.try_get_matches_from(vec!["", "-o", "val1,val2,val3"]);
@ -58,7 +58,7 @@ fn opt_s_default_no_delim() {
#[test]
fn opt_s_no_space_no_delim() {
let m = App::new("no_delim")
let m = Command::new("no_delim")
.arg(Arg::new("option").short('o').takes_value(true))
.try_get_matches_from(vec!["", "-o", "val1,val2,val3"]);
@ -72,7 +72,7 @@ fn opt_s_no_space_no_delim() {
#[test]
fn opt_s_no_space_mult_no_delim() {
let m = App::new("no_delim")
let m = Command::new("no_delim")
.arg(
Arg::new("option")
.short('o')
@ -91,7 +91,7 @@ fn opt_s_no_space_mult_no_delim() {
#[test]
fn opt_eq_mult_def_delim() {
let m = App::new("no_delim")
let m = Command::new("no_delim")
.arg(
Arg::new("option")
.long("opt")

Some files were not shown because too many files have changed in this diff Show more