refactor: Update app variables to cmd

This commit is contained in:
Ed Page 2022-02-14 15:47:20 -06:00
parent 9a7e6a523d
commit e8010e79a9
99 changed files with 1472 additions and 1472 deletions

View file

@ -3,9 +3,9 @@ use clap::{arg, Arg};
use criterion::{criterion_group, criterion_main, Criterion};
use std::io::Cursor;
fn build_help(app: &mut Command) -> 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()
}
@ -157,53 +157,53 @@ fn app_example10<'c>() -> Command<'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

@ -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) {
@ -271,18 +271,18 @@ OPTIONS:
/// Build a clap application with short help strings.
fn app_short() -> Command<'static> {
app(false, |k| USAGES[k].short)
cmd(false, |k| USAGES[k].short)
}
/// Build a clap application with long help strings.
fn app_long() -> Command<'static> {
app(true, |k| USAGES[k].long)
cmd(true, |k| USAGES[k].long)
}
/// Build the help text of an application.
fn build_help(app: &mut Command) -> 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,11 +290,11 @@ fn build_help(app: &mut Command) -> 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) -> Command<'static>
fn cmd<F>(_next_line_help: bool, doc: F) -> Command<'static>
where
F: Fn(&'static str) -> &'static str,
{

View file

@ -3,9 +3,9 @@ use clap_complete::{generate, shells::Bash};
use std::io;
fn main() {
let mut app = Command::new("myapp")
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

@ -92,16 +92,16 @@ fn build_cli() -> Command<'static> {
)
}
fn print_completions<G: Generator>(gen: G, app: &mut Command) {
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

@ -57,17 +57,17 @@ struct Opt {
email: Option<String>,
}
fn print_completions<G: Generator>(gen: G, app: &mut Command) {
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

@ -28,7 +28,7 @@ pub trait Generator {
/// pub struct Fish;
///
/// impl Generator for Fish {
/// # fn generate(&self, app: &Command, buf: &mut dyn Write) {}
/// # fn generate(&self, cmd: &Command, buf: &mut dyn Write) {}
/// fn file_name(&self, name: &str) -> String {
/// format!("{}.fish", name)
/// }
@ -55,15 +55,15 @@ pub trait Generator {
/// pub struct ClapDebug;
///
/// impl Generator for ClapDebug {
/// fn generate(&self, app: &Command, 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: &Command, buf: &mut dyn Write);
fn generate(&self, cmd: &Command, buf: &mut dyn Write);
}
/// Generate a completions file for a specified shell at compile-time.
@ -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::Command,
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::Command, 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::Command, 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

@ -6,10 +6,10 @@ use clap::{Arg, Command};
///
/// Subcommand `rustup toolchain install` would be converted to
/// `("install", "rustup toolchain install")`.
pub fn all_subcommands(app: &Command) -> 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);
}
@ -19,17 +19,17 @@ pub fn all_subcommands(app: &Command) -> Vec<(String, String)> {
/// 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 Command<'help>,
pub fn find_subcommand_with_path<'help, 'cmd>(
p: &'cmd Command<'help>,
path: Vec<&str>,
) -> &'app Command<'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::Command`] in the form of `("name", "bin_name")`.
@ -145,71 +145,71 @@ mod tests {
),
)
.subcommand(Command::new("hello"))
.bin_name("my-app")
.bin_name("my-cmd")
}
fn built() -> Command<'static> {
let mut app = common_app();
let mut cmd = common_app();
app._build_all();
app
cmd._build_all();
cmd
}
fn built_with_version() -> Command<'static> {
let mut app = common_app().version("3.0");
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

@ -39,17 +39,17 @@
//! )
//! }
//!
//! fn print_completions<G: Generator>(gen: G, app: &mut Command) {
//! 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: &Command, 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: &Command) -> 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: &Command) -> String {
subcmds.join("\n ")
}
fn subcommand_details(app: &Command) -> 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: &Command) -> 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: &Command, 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: &Command, 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: &Command, 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#"

View file

@ -15,13 +15,13 @@ impl Generator for Fish {
format!("{}.fish", name)
}
fn generate(&self, app: &Command, 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());
}
}
@ -34,7 +34,7 @@ fn escape_string(string: &str) -> String {
fn gen_fish_inner(
root_command: &str,
parent_commands: &[&str],
app: &Command,
cmd: &Command,
buffer: &mut String,
) {
debug!("gen_fish_inner");
@ -54,7 +54,7 @@ fn gen_fish_inner(
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 {
@ -65,7 +65,7 @@ fn gen_fish_inner(
.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<_>>()
@ -77,7 +77,7 @@ fn gen_fish_inner(
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() {
@ -102,7 +102,7 @@ fn gen_fish_inner(
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() {
@ -125,7 +125,7 @@ fn gen_fish_inner(
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");
@ -140,7 +140,7 @@ fn gen_fish_inner(
}
// 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: &Command, 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#"

View file

@ -87,13 +87,13 @@ impl Generator for Shell {
}
}
fn generate(&self, app: &clap::Command, 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: &Command, 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()
);
@ -280,10 +280,10 @@ esac",
//
// 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, 'app>(
parent: &'app Command<'help>,
fn parser_of<'help, 'cmd>(
parent: &'cmd Command<'help>,
bin_name: &str,
) -> Option<&'app Command<'help>> {
) -> 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()) {
@ -504,7 +504,7 @@ fn write_opts_of(p: &Command, p_global: Option<&Command>) -> String {
ret.join("\n")
}
fn arg_conflicts(app: &Command, arg: &Arg, app_global: Option<&Command>) -> 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() {
@ -529,7 +529,7 @@ fn arg_conflicts(app: &Command, arg: &Arg, app_global: Option<&Command>) -> Stri
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();

View file

@ -27,8 +27,8 @@ fn build_app_with_name(s: &'static str) -> Command<'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,8 +111,8 @@ 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() -> Command<'static> {
@ -246,8 +246,8 @@ 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() -> Command<'static> {

View file

@ -26,8 +26,8 @@ fn build_app_with_name(s: &'static str) -> Command<'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,8 +73,8 @@ 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() -> Command<'static> {
@ -148,8 +148,8 @@ 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() -> Command<'static> {

View file

@ -28,8 +28,8 @@ fn build_app_with_name(s: &'static str) -> Command<'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,8 +43,8 @@ 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() -> Command<'static> {
@ -78,8 +78,8 @@ 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() -> Command<'static> {
@ -125,8 +125,8 @@ 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() -> Command<'static> {
@ -161,8 +161,8 @@ 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() -> Command<'static> {

View file

@ -23,9 +23,9 @@ macro_rules! assert_eq {
};
}
pub fn common<G: Generator>(gen: G, app: &mut Command, 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

@ -34,8 +34,8 @@ fn build_app_with_name(s: &'static str) -> Command<'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,8 +93,8 @@ 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() -> Command<'static> {
@ -182,8 +182,8 @@ 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() -> Command<'static> {

View file

@ -26,8 +26,8 @@ fn build_app_with_name(s: &'static str) -> Command<'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,8 +104,8 @@ _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() -> Command<'static> {
@ -242,8 +242,8 @@ _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() -> Command<'static> {
@ -318,8 +318,8 @@ _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() -> Command<'static> {
@ -438,8 +438,8 @@ _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() -> Command<'static> {
@ -510,8 +510,8 @@ _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() -> Command<'static> {

View file

@ -6,7 +6,7 @@ use clap_complete::{generate, shells::*};
#[test]
fn generate_completions() {
let mut app = Command::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(
@ -15,9 +15,9 @@ fn generate_completions() {
.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

@ -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

@ -4,9 +4,9 @@ use clap_complete_fig::Fig;
use std::io;
fn main() {
let mut app = Command::new("myapp")
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: &Command, 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: &Command,
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: &Command, 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: &Command, 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

@ -27,8 +27,8 @@ fn build_app_with_name(s: &'static str) -> Command<'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,8 +90,8 @@ 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() -> Command<'static> {
@ -201,8 +201,8 @@ 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() -> Command<'static> {
@ -280,8 +280,8 @@ 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() -> Command<'static> {
@ -344,8 +344,8 @@ 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() -> Command<'static> {

View file

@ -19,9 +19,9 @@ macro_rules! assert_eq {
};
}
pub fn common<G: Generator>(gen: G, app: &mut Command, 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

@ -5,7 +5,7 @@ use std::io;
#[test]
fn generate_completions() {
let mut app = Command::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(
@ -14,5 +14,5 @@ fn generate_completions() {
.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

@ -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

@ -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

@ -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 => {

View file

@ -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::Command<'_>) -> clap::Command<'_> {
fn augment_subcommands(_cmd: clap::Command<'_>) -> clap::Command<'_> {
unimplemented!()
}
fn augment_subcommands_for_update(_app: clap::Command<'_>) -> clap::Command<'_> {
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::Command<'_>) -> clap::Command<'_> {
fn augment_args(_cmd: clap::Command<'_>) -> clap::Command<'_> {
unimplemented!()
}
fn augment_args_for_update(_app: clap::Command<'_>) -> clap::Command<'_> {
fn augment_args_for_update(_cmd: clap::Command<'_>) -> clap::Command<'_> {
unimplemented!()
}
}

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::Command,
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::Command, 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

@ -6,7 +6,7 @@ use std::io;
#[test]
fn generate_completions() {
let mut app = Command::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(
@ -15,9 +15,9 @@ fn generate_completions() {
.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

@ -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::Command::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

@ -5,7 +5,7 @@ use std::io;
// Run this example as `cargo run --example man | man -l -`.
fn main() -> Result<(), std::io::Error> {
let app = Command::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")
@ -36,5 +36,5 @@ And a few newlines.",
.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::Command<'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::Command<'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::Command) -> 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::Command) -> 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::Command) -> 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::Command) -> 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::Command) {
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::Command) {
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::Command) {
}
}
pub(crate) fn synopsis(roff: &mut Roff, app: &clap::Command) {
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::Command) {
};
}
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::Command) {
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::Command) {
roff.text(line);
}
pub(crate) fn options(roff: &mut Roff, app: &clap::Command) {
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::Command) {
}
}
pub(crate) fn subcommands(roff: &mut Roff, app: &clap::Command, 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,17 +158,17 @@ pub(crate) fn subcommands(roff: &mut Roff, app: &clap::Command, section: &str) {
}
}
pub(crate) fn version(app: &clap::Command) -> 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::Command) {
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)]);
}

View file

@ -4,7 +4,7 @@ use std::io;
#[test]
fn render_manpage() {
let app = Command::new("myapp")
let cmd = Command::new("myapp")
.version("1.0")
.author("Kevin K. <kbknapp@gmail.com>")
.about("Does awesome things")
@ -25,5 +25,5 @@ fn render_manpage() {
.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

@ -1,7 +1,7 @@
// Note: this requires the `cargo` feature
fn main() {
let app = clap::Command::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. [Command 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)
@ -173,7 +173,7 @@ In addition to the raw attributes, the following magic attributes are supported:
[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 Command Attributes, this
makes reuse harder. Generally prefer putting the app attributes on the `Parser`
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

View file

@ -12,7 +12,7 @@ fn applet_commands() -> [Command<'static>; 2] {
}
fn main() {
let app = Command::new(env!("CARGO_CRATE_NAME"))
let cmd = Command::new(env!("CARGO_CRATE_NAME"))
.multicall(true)
.subcommand(
Command::new("busybox")
@ -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

@ -3,16 +3,16 @@
use clap::Command;
fn main() {
let app = Command::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(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

@ -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

@ -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::Command<'static> {
fn cmd() -> clap::Command<'static> {
app_from_crate!().arg(
arg!(<PORT>)
.help("Network port to use")
@ -20,5 +20,5 @@ fn app() -> clap::Command<'static> {
#[test]
fn verify_app() {
app().debug_assert();
cmd().debug_assert();
}

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

@ -38,16 +38,16 @@ pub enum AppSettings {
/// Deprecated, replace
/// ```rust,no_run
/// let app = clap::Command::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::Command::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() {
@ -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

@ -2474,7 +2474,7 @@ impl<'help> Arg<'help> {
/// ```rust
/// # use clap::{Command, Arg};
///
/// macro_rules! app {
/// macro_rules! cmd {
/// () => {{
/// Command::new("prog")
/// .arg(Arg::new("color").long("color")
@ -2494,7 +2494,7 @@ impl<'help> Arg<'help> {
///
/// // first, we'll provide no arguments
///
/// m = app!().get_matches_from(vec![
/// m = cmd!().get_matches_from(vec![
/// "prog"
/// ]);
///
@ -2504,7 +2504,7 @@ impl<'help> Arg<'help> {
///
/// // next, we'll provide a runtime value to override the default (as usually done).
///
/// m = app!().get_matches_from(vec![
/// m = cmd!().get_matches_from(vec![
/// "prog", "--color=never"
/// ]);
///
@ -2514,7 +2514,7 @@ impl<'help> Arg<'help> {
///
/// // finally, we will use the shortcut and only provide the argument without a value.
///
/// m = app!().get_matches_from(vec![
/// m = cmd!().get_matches_from(vec![
/// "prog", "--color"
/// ]);
///

View file

@ -38,7 +38,7 @@ use yaml_rust::Yaml;
///
/// ```rust
/// # use clap::{Command, arg, ArgGroup, ErrorKind};
/// let result = Command::new("app")
/// 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();
@ -56,7 +56,7 @@ use yaml_rust::Yaml;
///
/// ```rust
/// # use clap::{Command, arg, ArgGroup};
/// let result = Command::new("app")
/// 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...

View file

@ -226,19 +226,19 @@ impl<'help> App<'help> {
/// ```rust
/// # use clap::{Command, Arg};
///
/// let mut app = Command::new("foo")
/// let mut cmd = Command::new("foo")
/// .arg(Arg::new("bar")
/// .short('b'))
/// .mut_arg("bar", |a| a.short('B'));
///
/// let res = app.try_get_matches_from_mut(vec!["foo", "-b"]);
/// let res = cmd.try_get_matches_from_mut(vec!["foo", "-b"]);
///
/// // Since we changed `bar`'s short to "B" this should err as there
/// // is no `-b` anymore, only `-B`
///
/// assert!(res.is_err());
///
/// let res = app.try_get_matches_from_mut(vec!["foo", "-B"]);
/// let res = cmd.try_get_matches_from_mut(vec!["foo", "-B"]);
/// assert!(res.is_ok());
/// ```
#[must_use]
@ -285,7 +285,7 @@ impl<'help> App<'help> {
///
/// ```no_run
/// # use clap::{Command, arg, ArgGroup};
/// Command::new("app")
/// Command::new("cmd")
/// .arg(arg!("--set-ver [ver] 'set the version manually'"))
/// .arg(arg!("--major 'auto increase major'"))
/// .arg(arg!("--minor 'auto increase minor'"))
@ -308,7 +308,7 @@ impl<'help> App<'help> {
///
/// ```no_run
/// # use clap::{Command, arg, ArgGroup};
/// Command::new("app")
/// Command::new("cmd")
/// .arg(arg!("--set-ver [ver] 'set the version manually'"))
/// .arg(arg!("--major 'auto increase major'"))
/// .arg(arg!("--minor 'auto increase minor'"))
@ -403,7 +403,7 @@ impl<'help> App<'help> {
///
/// ```rust
/// # use clap::{Command, Arg};
/// fn app() -> Command<'static> {
/// fn cmd() -> Command<'static> {
/// Command::new("foo")
/// .arg(Arg::new("bar").short('b')
/// )
@ -411,11 +411,11 @@ impl<'help> App<'help> {
///
/// #[test]
/// fn verify_app() {
/// app().debug_assert();
/// cmd().debug_assert();
/// }
///
/// fn main() {
/// let m = app().get_matches_from(vec!["foo", "-b"]);
/// let m = cmd().get_matches_from(vec!["foo", "-b"]);
/// println!("{}", m.is_present("bar"));
/// }
/// ```
@ -429,8 +429,8 @@ impl<'help> App<'help> {
///
/// ```rust
/// # use clap::{Command, ErrorKind};
/// let mut app = Command::new("myprog");
/// let err = app.error(ErrorKind::InvalidValue, "Some failure case");
/// let mut cmd = Command::new("myprog");
/// let err = cmd.error(ErrorKind::InvalidValue, "Some failure case");
/// ```
pub fn error(&mut self, kind: ErrorKind, message: impl std::fmt::Display) -> Error {
Error::raw(kind, message).format(self)
@ -469,10 +469,10 @@ impl<'help> App<'help> {
///
/// ```no_run
/// # use clap::{Command, Arg};
/// let mut app = Command::new("myprog")
/// let mut cmd = Command::new("myprog")
/// // Args and options go here...
/// ;
/// let matches = app.get_matches_mut();
/// let matches = cmd.get_matches_mut();
/// ```
/// [`env::args_os`]: std::env::args_os()
/// [`App::get_matches`]: Command::get_matches()
@ -613,9 +613,9 @@ impl<'help> App<'help> {
/// # use clap::{Command, Arg};
/// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"];
///
/// let mut app = Command::new("myprog");
/// let mut cmd = Command::new("myprog");
/// // Args and options go here...
/// let matches = app.try_get_matches_from_mut(arg_vec)
/// let matches = cmd.try_get_matches_from_mut(arg_vec)
/// .unwrap_or_else(|e| e.exit());
/// ```
/// [`App::try_get_matches_from`]: Command::try_get_matches_from()
@ -683,8 +683,8 @@ impl<'help> App<'help> {
///
/// ```rust
/// # use clap::Command;
/// let mut app = Command::new("myprog");
/// app.print_help();
/// let mut cmd = Command::new("myprog");
/// cmd.print_help();
/// ```
/// [`io::stdout()`]: std::io::stdout()
pub fn print_help(&mut self) -> io::Result<()> {
@ -705,8 +705,8 @@ impl<'help> App<'help> {
///
/// ```rust
/// # use clap::Command;
/// let mut app = Command::new("myprog");
/// app.print_long_help();
/// let mut cmd = Command::new("myprog");
/// cmd.print_long_help();
/// ```
/// [`io::stdout()`]: std::io::stdout()
/// [`BufWriter`]: std::io::BufWriter
@ -731,9 +731,9 @@ impl<'help> App<'help> {
/// ```rust
/// # use clap::Command;
/// use std::io;
/// let mut app = Command::new("myprog");
/// let mut cmd = Command::new("myprog");
/// let mut out = io::stdout();
/// app.write_help(&mut out).expect("failed to write to stdout");
/// cmd.write_help(&mut out).expect("failed to write to stdout");
/// ```
/// [`io::Write`]: std::io::Write
/// [`-h` (short)]: Arg::help()
@ -755,9 +755,9 @@ impl<'help> App<'help> {
/// ```rust
/// # use clap::Command;
/// use std::io;
/// let mut app = Command::new("myprog");
/// let mut cmd = Command::new("myprog");
/// let mut out = io::stdout();
/// app.write_long_help(&mut out).expect("failed to write to stdout");
/// cmd.write_long_help(&mut out).expect("failed to write to stdout");
/// ```
/// [`io::Write`]: std::io::Write
/// [`-h` (short)]: Arg::help()
@ -783,8 +783,8 @@ impl<'help> App<'help> {
/// ```rust
/// # use clap::Command;
/// use std::io;
/// let app = Command::new("myprog");
/// println!("{}", app.render_version());
/// let cmd = Command::new("myprog");
/// println!("{}", cmd.render_version());
/// ```
/// [`io::Write`]: std::io::Write
/// [`-V` (short)]: Command::version()
@ -807,8 +807,8 @@ impl<'help> App<'help> {
/// ```rust
/// # use clap::Command;
/// use std::io;
/// let app = Command::new("myprog");
/// println!("{}", app.render_long_version());
/// let cmd = Command::new("myprog");
/// println!("{}", cmd.render_long_version());
/// ```
/// [`io::Write`]: std::io::Write
/// [`-V` (short)]: Command::version()
@ -825,8 +825,8 @@ impl<'help> App<'help> {
/// ```rust
/// # use clap::Command;
/// use std::io;
/// let mut app = Command::new("myprog");
/// println!("{}", app.render_usage());
/// let mut cmd = Command::new("myprog");
/// println!("{}", cmd.render_usage());
/// ```
pub fn render_usage(&mut self) -> String {
// If there are global arguments, or settings we need to propagate them down to subcommands
@ -880,13 +880,13 @@ impl<'help> App<'help> {
///
/// ```rust
/// # use clap::{Command, arg};
/// let app = Command::new("app")
/// let cmd = Command::new("cmd")
/// .ignore_errors(true)
/// .arg(arg!(-c --config <FILE> "Sets a custom config file").required(false))
/// .arg(arg!(-x --stuff <FILE> "Sets a custom stuff file").required(false))
/// .arg(arg!(f: -f "Flag"));
///
/// let r = app.try_get_matches_from(vec!["app", "-c", "file", "-f", "-x"]);
/// let r = cmd.try_get_matches_from(vec!["cmd", "-c", "file", "-f", "-x"]);
///
/// assert!(r.is_ok(), "unexpected error: {:?}", r);
/// let m = r.unwrap();
@ -970,14 +970,14 @@ impl<'help> App<'help> {
#[must_use]
pub fn color(self, color: ColorChoice) -> Self {
#![allow(deprecated)]
let app = self
let cmd = self
.unset_global_setting(AppSettings::ColorAuto)
.unset_global_setting(AppSettings::ColorAlways)
.unset_global_setting(AppSettings::ColorNever);
match color {
ColorChoice::Auto => app.global_setting(AppSettings::ColorAuto),
ColorChoice::Always => app.global_setting(AppSettings::ColorAlways),
ColorChoice::Never => app.global_setting(AppSettings::ColorNever),
ColorChoice::Auto => cmd.global_setting(AppSettings::ColorAuto),
ColorChoice::Always => cmd.global_setting(AppSettings::ColorAlways),
ColorChoice::Never => cmd.global_setting(AppSettings::ColorNever),
}
}
@ -1335,11 +1335,11 @@ impl<'help> App<'help> {
///
/// ```ignore
/// # use clap::{Command, load_yaml};
/// let yaml = load_yaml!("app.yaml");
/// let app = Command::from(yaml)
/// let yaml = load_yaml!("cmd.yaml");
/// let cmd = Command::from(yaml)
/// .name(crate_name!());
///
/// // continued logic goes here, such as `app.get_matches()` etc.
/// // continued logic goes here, such as `cmd.get_matches()` etc.
/// ```
#[must_use]
pub fn name<S: Into<String>>(mut self, name: S) -> Self {
@ -1847,27 +1847,27 @@ impl<'help> App<'help> {
///
/// We'll start with the "subcommand short" example. In this example, let's
/// assume we have a program with a subcommand `module` which can be invoked
/// via `app module`. Now let's also assume `module` also has a subcommand
/// called `install` which can be invoked `app module install`. If for some
/// reason users needed to be able to reach `app module install` via the
/// short-hand `app install`, we'd have several options.
/// via `cmd module`. Now let's also assume `module` also has a subcommand
/// called `install` which can be invoked `cmd module install`. If for some
/// reason users needed to be able to reach `cmd module install` via the
/// short-hand `cmd install`, we'd have several options.
///
/// We *could* create another sibling subcommand to `module` called
/// `install`, but then we would need to manage another subcommand and manually
/// dispatch to `app module install` handling code. This is error prone and
/// dispatch to `cmd module install` handling code. This is error prone and
/// tedious.
///
/// We could instead use [`Command::replace`] so that, when the user types `app
/// We could instead use [`Command::replace`] so that, when the user types `cmd
/// install`, `clap` will replace `install` with `module install` which will
/// end up getting parsed as if the user typed the entire incantation.
///
/// ```rust
/// # use clap::Command;
/// let m = Command::new("app")
/// let m = Command::new("cmd")
/// .subcommand(Command::new("module")
/// .subcommand(Command::new("install")))
/// .replace("install", &["module", "install"])
/// .get_matches_from(vec!["app", "install"]);
/// .get_matches_from(vec!["cmd", "install"]);
///
/// assert!(m.subcommand_matches("module").is_some());
/// assert!(m.subcommand_matches("module").unwrap().subcommand_matches("install").is_some());
@ -1878,7 +1878,7 @@ impl<'help> App<'help> {
/// Let's assume we have an application with two flags `--save-context` and
/// `--save-runtime`. But often users end up needing to do *both* at the
/// same time. We can add a third flag `--save-all` which semantically means
/// the same thing as `app --save-context --save-runtime`. To implement that,
/// the same thing as `cmd --save-context --save-runtime`. To implement that,
/// we have several options.
///
/// We could create this third argument and manually check if that argument
@ -1896,13 +1896,13 @@ impl<'help> App<'help> {
///
/// ```rust
/// # use clap::{Command, Arg};
/// let m = Command::new("app")
/// let m = Command::new("cmd")
/// .arg(Arg::new("save-context")
/// .long("save-context"))
/// .arg(Arg::new("save-runtime")
/// .long("save-runtime"))
/// .replace("--save-all", &["--save-context", "--save-runtime"])
/// .get_matches_from(vec!["app", "--save-all"]);
/// .get_matches_from(vec!["cmd", "--save-all"]);
///
/// assert!(m.is_present("save-context"));
/// assert!(m.is_present("save-runtime"));
@ -1916,7 +1916,7 @@ impl<'help> App<'help> {
///
/// ```rust
/// # use clap::{Command, Arg};
/// let m = Command::new("app")
/// let m = Command::new("cmd")
/// .arg(Arg::new("save-context")
/// .long("save-context"))
/// .arg(Arg::new("save-runtime")
@ -1926,7 +1926,7 @@ impl<'help> App<'help> {
/// .takes_value(true)
/// .possible_values(["txt", "json"]))
/// .replace("--save-all", &["--save-context", "--save-runtime", "--format=json"])
/// .get_matches_from(vec!["app", "--save-all"]);
/// .get_matches_from(vec!["cmd", "--save-all"]);
///
/// assert!(m.is_present("save-context"));
/// assert!(m.is_present("save-runtime"));
@ -2803,7 +2803,7 @@ impl<'help> App<'help> {
/// subcommand will be parsed as another value.
///
/// ```text
/// app --foo val1 val2 subcommand
/// cmd --foo val1 val2 subcommand
/// --------- ----------
/// values another value
/// ```
@ -2812,7 +2812,7 @@ impl<'help> App<'help> {
/// greedily consuming arguments.
///
/// ```text
/// app --foo val1 val2 subcommand
/// cmd --foo val1 val2 subcommand
/// --------- ----------
/// values subcommand
/// ```
@ -2824,16 +2824,16 @@ impl<'help> App<'help> {
///
/// ```rust
/// # use clap::{Command, Arg};
/// let app = Command::new("app").subcommand(Command::new("sub")).arg(
/// let cmd = Command::new("cmd").subcommand(Command::new("sub")).arg(
/// Arg::new("arg")
/// .long("arg")
/// .multiple_values(true)
/// .takes_value(true),
/// );
///
/// let matches = app
/// let matches = cmd
/// .clone()
/// .try_get_matches_from(&["app", "--arg", "1", "2", "3", "sub"])
/// .try_get_matches_from(&["cmd", "--arg", "1", "2", "3", "sub"])
/// .unwrap();
/// assert_eq!(
/// matches.values_of("arg").unwrap().collect::<Vec<_>>(),
@ -2841,9 +2841,9 @@ impl<'help> App<'help> {
/// );
/// assert!(matches.subcommand_matches("sub").is_none());
///
/// let matches = app
/// let matches = cmd
/// .subcommand_precedence_over_arg(true)
/// .try_get_matches_from(&["app", "--arg", "1", "2", "3", "sub"])
/// .try_get_matches_from(&["cmd", "--arg", "1", "2", "3", "sub"])
/// .unwrap();
/// assert_eq!(
/// matches.values_of("arg").unwrap().collect::<Vec<_>>(),
@ -2938,7 +2938,7 @@ impl<'help> App<'help> {
/// but there is other related functionality that would be convenient to provide
/// and it is convenient for the code to implement it to be in the same executable.
///
/// The name of the app is essentially unused
/// The name of the cmd is essentially unused
/// and may be the same as the name of a subcommand.
///
/// The names of the immediate subcommands of the Command
@ -2949,14 +2949,14 @@ impl<'help> App<'help> {
///
/// ```rust
/// # use clap::{Command, ErrorKind};
/// let mut app = Command::new("hostname")
/// let mut cmd = Command::new("hostname")
/// .multicall(true)
/// .subcommand(Command::new("hostname"))
/// .subcommand(Command::new("dnsdomainname"));
/// let m = app.try_get_matches_from_mut(&["/usr/bin/hostname", "dnsdomainname"]);
/// let m = cmd.try_get_matches_from_mut(&["/usr/bin/hostname", "dnsdomainname"]);
/// assert!(m.is_err());
/// assert_eq!(m.unwrap_err().kind(), ErrorKind::UnknownArgument);
/// let m = app.get_matches_from(&["/usr/bin/dnsdomainname"]);
/// let m = cmd.get_matches_from(&["/usr/bin/dnsdomainname"]);
/// assert_eq!(m.subcommand_name(), Some("dnsdomainname"));
/// ```
///
@ -2979,7 +2979,7 @@ impl<'help> App<'help> {
/// fn applet_commands() -> [Command<'static>; 2] {
/// [Command::new("true"), Command::new("false")]
/// }
/// let mut app = Command::new("busybox")
/// let mut cmd = Command::new("busybox")
/// .multicall(true)
/// .subcommand(
/// Command::new("busybox")
@ -2990,11 +2990,11 @@ impl<'help> App<'help> {
/// .subcommands(applet_commands());
/// // When called from the executable's canonical name
/// // its applets can be matched as subcommands.
/// let m = app.try_get_matches_from_mut(&["/usr/bin/busybox", "true"]).unwrap();
/// let m = cmd.try_get_matches_from_mut(&["/usr/bin/busybox", "true"]).unwrap();
/// assert_eq!(m.subcommand_name(), Some("busybox"));
/// assert_eq!(m.subcommand().unwrap().1.subcommand_name(), Some("true"));
/// // When called from a link named after an applet that applet is matched.
/// let m = app.get_matches_from(&["/usr/bin/true"]);
/// let m = cmd.get_matches_from(&["/usr/bin/true"]);
/// assert_eq!(m.subcommand_name(), Some("true"));
/// ```
///
@ -3172,25 +3172,25 @@ impl<'help> App<'help> {
self.bin_name = Some(name.into());
}
/// Get the name of the app.
/// Get the name of the cmd.
#[inline]
pub fn get_name(&self) -> &str {
&self.name
}
/// Get the version of the app.
/// Get the version of the cmd.
#[inline]
pub fn get_version(&self) -> Option<&'help str> {
self.version
}
/// Get the long version of the app.
/// Get the long version of the cmd.
#[inline]
pub fn get_long_version(&self) -> Option<&'help str> {
self.long_version
}
/// Get the authors of the app.
/// Get the authors of the cmd.
#[inline]
pub fn get_author(&self) -> Option<&'help str> {
self.author
@ -3444,7 +3444,7 @@ impl<'help> App<'help> {
.map(|id| {
self.args.args().find(|arg| arg.id == *id).expect(
"App::get_arg_conflicts_with: \
The passed arg conflicts with an arg unknown to the app",
The passed arg conflicts with an arg unknown to the cmd",
)
})
.collect()
@ -3475,7 +3475,7 @@ impl<'help> App<'help> {
.find(|arg| arg.id == *id)
.expect(
"App::get_arg_conflicts_with: \
The passed arg conflicts with an arg unknown to the app",
The passed arg conflicts with an arg unknown to the cmd",
)
})
.collect()
@ -3653,7 +3653,7 @@ impl<'help> App<'help> {
let yaml_file_hash = y.as_hash().expect("YAML file must be a hash");
// We WANT this to panic on error...so expect() is good.
let (mut a, yaml, err) = if let Some(name) = y["name"].as_str() {
(App::new(name), yaml_file_hash, "app".into())
(App::new(name), yaml_file_hash, "cmd".into())
} else {
let (name_yaml, value_yaml) = yaml_file_hash
.iter()
@ -4243,7 +4243,7 @@ impl<'help> App<'help> {
panic!(
"`help`s `-h` conflicts with `{}`.
To change `help`s short, call `app.arg(Arg::new(\"help\")...)`.",
To change `help`s short, call `cmd.arg(Arg::new(\"help\")...)`.",
other_arg.name
);
}

View file

@ -5,35 +5,35 @@ use crate::mkeymap::KeyType;
use crate::util::Id;
use crate::{AppSettings, Arg, Command, ValueHint};
pub(crate) fn assert_app(app: &Command) {
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(),
!cmd.is_propagate_version_set(),
"Command {}: No version information via Command::version or Command::long_version to propagate",
app.get_name(),
cmd.get_name(),
);
// Used `Command::mut_arg("version", ..) but did not provide any version information to display
let has_mutated_version = app
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),
assert!(cmd.is_set(AppSettings::NoAutoVersion),
"Command {}: Used Command::mut_arg(\"version\", ..) without providing Command::version, Command::long_version or using AppSettings::NoAutoVersion"
,app.get_name()
,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::Command(format!("-{}", s), sc.get_name()));
}
@ -51,7 +51,7 @@ pub(crate) fn assert_app(app: &Command) {
}
}
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: &Command) {
// Name conflicts
assert!(
app.two_args_of(|x| x.id == arg.id).is_none(),
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",
app.get_name(),
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!(
"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: &Command) {
// 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!(
"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: &Command) {
// 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!(
"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: &Command) {
// requires, r_if, r_unless
for req in &arg.requires {
assert!(
app.id_exists(&req.1),
cmd.id_exists(&req.1),
"Command {}: Argument or group '{:?}' specified in 'requires*' for '{}' does not exist",
app.get_name(),
cmd.get_name(),
req.1,
arg.name,
);
@ -136,9 +136,9 @@ pub(crate) fn assert_app(app: &Command) {
for req in &arg.r_ifs {
assert!(
app.id_exists(&req.0),
cmd.id_exists(&req.0),
"Command {}: Argument or group '{:?}' specified in 'required_if_eq*' for '{}' does not exist",
app.get_name(),
cmd.get_name(),
req.0,
arg.name
);
@ -146,9 +146,9 @@ pub(crate) fn assert_app(app: &Command) {
for req in &arg.r_ifs_all {
assert!(
app.id_exists(&req.0),
cmd.id_exists(&req.0),
"Command {}: Argument or group '{:?}' specified in 'required_if_eq_all' for '{}' does not exist",
app.get_name(),
cmd.get_name(),
req.0,
arg.name
);
@ -156,9 +156,9 @@ pub(crate) fn assert_app(app: &Command) {
for req in &arg.r_unless {
assert!(
app.id_exists(req),
cmd.id_exists(req),
"Command {}: Argument or group '{:?}' specified in 'required_unless*' for '{}' does not exist",
app.get_name(),
cmd.get_name(),
req,
arg.name,
);
@ -167,9 +167,9 @@ pub(crate) fn assert_app(app: &Command) {
// blacklist
for req in &arg.blacklist {
assert!(
app.id_exists(req),
cmd.id_exists(req),
"Command {}: Argument or group '{:?}' specified in 'conflicts_with*' for '{}' does not exist",
app.get_name(),
cmd.get_name(),
req,
arg.name,
);
@ -179,13 +179,13 @@ pub(crate) fn assert_app(app: &Command) {
assert!(
arg.long.is_none(),
"Command {}: Flags or Options cannot have last(true) set. '{}' has both a long and last(true) set.",
app.get_name(),
cmd.get_name(),
arg.name
);
assert!(
arg.short.is_none(),
"Command {}: Flags or Options cannot have last(true) set. '{}' has both a short and last(true) set.",
app.get_name(),
cmd.get_name(),
arg.name
);
}
@ -193,7 +193,7 @@ pub(crate) fn assert_app(app: &Command) {
assert!(
!(arg.is_required_set() && arg.is_global_set()),
"Command {}: Global arguments cannot be required.\n\n\t'{}' is marked as both global and required",
app.get_name(),
cmd.get_name(),
arg.name
);
@ -201,7 +201,7 @@ pub(crate) fn assert_app(app: &Command) {
assert!(
arg.validator.is_none() || arg.validator_os.is_none(),
"Command {}: Argument '{}' has both `validator` and `validator_os` set which is not allowed",
app.get_name(),
cmd.get_name(),
arg.name
);
@ -209,33 +209,33 @@ pub(crate) fn assert_app(app: &Command) {
assert!(
arg.is_positional(),
"Command {}: Argument '{}' has hint CommandWithArguments and must be positional.",
app.get_name(),
cmd.get_name(),
arg.name
);
assert!(
app.is_trailing_var_arg_set(),
cmd.is_trailing_var_arg_set(),
"Command {}: Positional argument '{}' has hint CommandWithArguments, so Command must have TrailingVarArg set.",
app.get_name(),
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,
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",
app.get_name(),
cmd.get_name(),
group.name,
);
// Groups should not have naming conflicts with Args
assert!(
!app.get_arguments().any(|x| x.id == group.id),
!cmd.get_arguments().any(|x| x.id == group.id),
"Command {}: Argument group name '{}' must not conflict with argument name",
app.get_name(),
cmd.get_name(),
group.name,
);
@ -243,11 +243,11 @@ pub(crate) fn assert_app(app: &Command) {
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())
}),
"Command {}: Argument group '{}' is required but all of it's arguments have a default value.",
app.get_name(),
cmd.get_name(),
group.name
)
}
@ -255,9 +255,9 @@ pub(crate) fn assert_app(app: &Command) {
for arg in &group.args {
// Args listed inside groups should exist
assert!(
app.get_arguments().any(|x| x.id == *arg),
cmd.get_arguments().any(|x| x.id == *arg),
"Command {}: Argument group '{}' contains non-existent argument '{:?}'",
app.get_name(),
cmd.get_name(),
group.name,
arg
);
@ -272,25 +272,25 @@ pub(crate) fn assert_app(app: &Command) {
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}"),
"Command {}: {}",
app.get_name(),
cmd.get_name(),
"`{flags}` template variable was removed in clap3, they are now included in `{options}`",
);
assert!(
!help_template.contains("{unified}"),
"Command {}: {}",
app.get_name(),
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)]
@ -370,14 +370,14 @@ fn find_duplicates<T: PartialEq>(slice: &[T]) -> impl Iterator<Item = (&T, &T)>
})
}
fn assert_app_flags(app: &Command) {
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: &Command) {
}
};
($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,7 +410,7 @@ fn assert_app_flags(app: &Command) {
}
#[cfg(debug_assertions)]
fn _verify_positionals(app: &Command) -> bool {
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: &Command) -> 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: &Command) -> 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: &Command) -> 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: &Command) -> 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: &Command) -> 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: &Command) -> 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: &Command) -> 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: &Command) -> 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

@ -3,24 +3,24 @@ use crate::Command;
#[test]
fn propagate_version() {
let mut app = Command::new("test")
let mut cmd = Command::new("test")
.propagate_version(true)
.version("1.1")
.subcommand(Command::new("sub1"));
app._propagate();
cmd._propagate();
assert_eq!(
app.get_subcommands().next().unwrap().get_version(),
cmd.get_subcommands().next().unwrap().get_version(),
Some("1.1")
);
}
#[test]
fn global_setting() {
let mut app = Command::new("test")
let mut cmd = Command::new("test")
.disable_version_flag(true)
.subcommand(Command::new("subcmd"));
app._propagate();
assert!(app
cmd._propagate();
assert!(cmd
.get_subcommands()
.find(|s| s.get_name() == "subcmd")
.unwrap()
@ -36,12 +36,12 @@ fn app_send_sync() {
#[test]
fn issue_2090() {
let mut app = Command::new("app")
let mut cmd = Command::new("cmd")
.disable_version_flag(true)
.subcommand(Command::new("sub"));
app._build();
cmd._build();
assert!(app
assert!(cmd
.get_subcommands()
.next()
.unwrap()

View file

@ -316,13 +316,13 @@ pub trait Args: FromArgMatches + Sized {
/// Append to [`Command`] so it can instantiate `Self`.
///
/// See also [`IntoApp`].
fn augment_args(app: Command<'_>) -> Command<'_>;
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: Command<'_>) -> Command<'_>;
fn augment_args_for_update(cmd: Command<'_>) -> Command<'_>;
}
/// Parse a sub-command into a user-defined enum.
@ -360,13 +360,13 @@ pub trait Subcommand: FromArgMatches + Sized {
/// Append to [`Command`] so it can instantiate `Self`.
///
/// See also [`IntoApp`].
fn augment_subcommands(app: Command<'_>) -> Command<'_>;
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: Command<'_>) -> Command<'_>;
fn augment_subcommands_for_update(cmd: Command<'_>) -> Command<'_>;
/// Test whether `Self` can parse a specific subcommand
fn has_subcommand(name: &str) -> bool;
}
@ -470,20 +470,20 @@ impl<T: FromArgMatches> FromArgMatches for Box<T> {
}
impl<T: Args> Args for Box<T> {
fn augment_args(app: Command<'_>) -> Command<'_> {
<T as Args>::augment_args(app)
fn augment_args(cmd: Command<'_>) -> Command<'_> {
<T as Args>::augment_args(cmd)
}
fn augment_args_for_update(app: Command<'_>) -> Command<'_> {
<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: Command<'_>) -> Command<'_> {
<T as Subcommand>::augment_subcommands(app)
fn augment_subcommands(cmd: Command<'_>) -> Command<'_> {
<T as Subcommand>::augment_subcommands(cmd)
}
fn augment_subcommands_for_update(app: Command<'_>) -> Command<'_> {
<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

@ -75,13 +75,13 @@ impl Error {
/// Format the existing message with the Command's context
#[must_use]
pub fn format(mut self, app: &mut Command) -> 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
@ -174,17 +174,17 @@ impl Error {
}
#[inline(never)]
fn for_app(kind: ErrorKind, app: &Command, 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: &Command) -> 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: &Command, 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: &Command, 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: &Command, 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: &Command,
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: &Command, 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: &Command, 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: &Command,
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: &Command,
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: &Command, 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: &Command,
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: &Command, 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: &Command, 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: &Command,
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: &Command, 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: &Command,
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: &Command,
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: &Command, 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: &Command,
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: &Command, 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: &Command) -> 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: &Command, 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

@ -188,7 +188,7 @@ macro_rules! arg_enum {
/// # extern crate clap;
/// # use clap::Command;
/// # fn main() {
/// let m = Command::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>"`
///
@ -217,7 +217,7 @@ macro_rules! crate_version {
/// # extern crate clap;
/// # use clap::Command;
/// # fn main() {
/// let m = Command::new("app")
/// let m = Command::new("cmd")
/// .author(crate_authors!("\n"))
/// .get_matches();
/// # }
@ -247,7 +247,7 @@ macro_rules! crate_authors {
/// # extern crate clap;
/// # use clap::Command;
/// # fn main() {
/// let m = Command::new("app")
/// let m = Command::new("cmd")
/// .about(crate_description!())
/// .get_matches();
/// # }
@ -308,34 +308,34 @@ macro_rules! crate_name {
#[macro_export]
macro_rules! app_from_crate {
() => {{
let mut app = $crate::Command::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::Command::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
}};
}

View file

@ -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 Command<'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 Command<'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,21 +652,21 @@ 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: &Command<'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)?;
@ -706,7 +706,7 @@ impl<'help, 'app, 'writer> Help<'help, 'app, 'writer> {
fn subcommand_next_line_help(
&self,
app: &Command<'help>,
cmd: &Command<'help>,
spec_vals: &str,
longest: usize,
) -> bool {
@ -715,7 +715,7 @@ impl<'help, 'app, 'writer> Help<'help, 'app, 'writer> {
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
@ -737,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<_>>();
@ -780,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() {
@ -808,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(())
@ -839,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: &Command<'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))
{
@ -863,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 {
@ -881,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(())
@ -897,7 +897,7 @@ 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 [`Command::help_template`].
@ -980,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()?;

View file

@ -8,20 +8,20 @@ use crate::util::ChildGraph;
use crate::util::Id;
use crate::INTERNAL_ERROR_MSG;
pub(crate) struct Usage<'help, 'app> {
app: &'app Command<'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 Command<'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

@ -15,22 +15,22 @@ use indexmap::map::Entry;
pub(crate) struct ArgMatcher(ArgMatches);
impl ArgMatcher {
pub(crate) fn new(_app: &Command) -> 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

@ -85,16 +85,16 @@ impl ArgMatches {
///
/// ```rust
/// # use clap::{Command, Arg};
/// let mut app = Command::new("myapp")
/// 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());

View file

@ -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 Command<'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 Command<'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

@ -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: &Command, 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: &Command, 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

@ -241,7 +241,7 @@ fn arg_required_else_help_with_default() {
#[test]
fn arg_required_else_help_error_message() {
let app = Command::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
@ -277,12 +277,12 @@ fn subcommand_required_else_help() {
#[test]
fn subcommand_required_else_help_error_message() {
#![allow(deprecated)]
let app = Command::new("test")
let cmd = Command::new("test")
.setting(AppSettings::SubcommandRequiredElseHelp)
.version("1.0")
.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
@ -407,7 +407,7 @@ fn no_bin_name() {
#[test]
fn skip_possible_values() {
let app = Command::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
@ -616,7 +616,7 @@ fn disable_help_subcommand() {
#[test]
fn dont_collapse_args() {
let app = Command::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 = Command::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
@ -860,11 +860,11 @@ fn issue_1437_allow_hyphen_values_for_positional_arg() {
#[test]
fn issue_1093_allow_ext_sc() {
let app = Command::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
@ -1111,21 +1111,21 @@ fn aaos_option_use_delim_false() {
#[test]
fn no_auto_help() {
let app = Command::new("myprog")
let cmd = Command::new("myprog")
.setting(AppSettings::NoAutoHelp)
.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"));
@ -1133,18 +1133,18 @@ fn no_auto_help() {
#[test]
fn no_auto_version() {
let app = Command::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"));
@ -1152,19 +1152,19 @@ fn no_auto_version() {
#[test]
fn no_auto_version_mut_arg() {
let app = Command::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"));
@ -1173,12 +1173,12 @@ fn no_auto_version_mut_arg() {
#[test]
#[cfg(feature = "color")]
fn color_is_global() {
let mut app = Command::new("myprog")
let mut cmd = Command::new("myprog")
.color(clap::ColorChoice::Never)
.subcommand(Command::new("foo"));
app._build_all();
assert_eq!(app.get_color(), clap::ColorChoice::Never);
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

@ -155,7 +155,7 @@ fn alias_on_a_subcommand_option() {
#[test]
fn invisible_arg_aliases_help_output() {
let app = Command::new("ct").author("Salim Afiune").subcommand(
let cmd = Command::new("ct").author("Salim Afiune").subcommand(
Command::new("test")
.about("Some help")
.version("1.2")
@ -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,7 +178,7 @@ fn invisible_arg_aliases_help_output() {
#[test]
fn visible_arg_aliases_help_output() {
let app = Command::new("ct").author("Salim Afiune").subcommand(
let cmd = Command::new("ct").author("Salim Afiune").subcommand(
Command::new("test")
.about("Some help")
.version("1.2")
@ -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

@ -151,7 +151,7 @@ fn short_alias_on_a_subcommand_option() {
#[test]
fn invisible_short_arg_aliases_help_output() {
let app = Command::new("ct").author("Salim Afiune").subcommand(
let cmd = Command::new("ct").author("Salim Afiune").subcommand(
Command::new("test")
.about("Some help")
.version("1.2")
@ -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,7 +174,7 @@ fn invisible_short_arg_aliases_help_output() {
#[test]
fn visible_short_arg_aliases_help_output() {
let app = Command::new("ct").author("Salim Afiune").subcommand(
let cmd = Command::new("ct").author("Salim Afiune").subcommand(
Command::new("test")
.about("Some help")
.version("1.2")
@ -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

@ -74,33 +74,33 @@ fn flag_conflict_with_everything() {
#[test]
fn arg_conflicts_with_group() {
let mut app = Command::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::Command::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 = Command::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 = Command::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 = Command::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 = Command::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,

View file

@ -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 = Command::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 = Command::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 = Command::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()
),

View file

@ -505,7 +505,7 @@ fn default_ifs_arg_present_order() {
#[test]
fn conditional_reqs_pass() {
let m = Command::new("Test app")
let m = Command::new("Test cmd")
.arg(
Arg::new("target")
.takes_value(true)
@ -568,7 +568,7 @@ fn multiple_defaults_override() {
#[test]
fn default_vals_donnot_show_in_smart_usage() {
let app = Command::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>
@ -663,7 +663,7 @@ fn default_values_are_valid() {
#[test]
fn with_value_delimiter() {
let app = Command::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 = Command::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

@ -86,7 +86,7 @@ OPTIONS:
#[test]
fn no_derive_order() {
let app = Command::new("test").version("1.2").args(&[
let cmd = Command::new("test").version("1.2").args(&[
Arg::new("flag_b").long("flag_b").help("first flag"),
Arg::new("option_b")
.long("option_b")
@ -100,7 +100,7 @@ fn no_derive_order() {
]);
assert!(utils::compare_output(
app,
cmd,
"test --help",
NO_DERIVE_ORDER,
false
@ -109,7 +109,7 @@ fn no_derive_order() {
#[test]
fn derive_order() {
let app = Command::new("test")
let cmd = Command::new("test")
.setting(AppSettings::DeriveDisplayOrder)
.version("1.2")
.args(&[
@ -126,7 +126,7 @@ fn derive_order() {
]);
assert!(utils::compare_output(
app,
cmd,
"test --help",
UNIFIED_HELP_AND_DERIVE,
false
@ -149,7 +149,7 @@ OPTIONS:
--option_a <option_a> second option
";
let app = Command::new("test")
let cmd = Command::new("test")
.setting(AppSettings::DeriveDisplayOrder)
.version("1.2")
.next_display_order(10000)
@ -169,7 +169,7 @@ OPTIONS:
.help("first option"),
);
assert!(utils::compare_output(app, "test --help", HELP, false));
assert!(utils::compare_output(cmd, "test --help", HELP, false));
}
#[test]
@ -188,7 +188,7 @@ OPTIONS:
-V, --version Print version information
";
let app = Command::new("test")
let cmd = Command::new("test")
.setting(AppSettings::DeriveDisplayOrder)
.version("1.2")
.next_display_order(None)
@ -207,12 +207,12 @@ OPTIONS:
.help("second option"),
);
assert!(utils::compare_output(app, "test --help", HELP, false));
assert!(utils::compare_output(cmd, "test --help", HELP, false));
}
#[test]
fn derive_order_subcommand_propagate() {
let app = Command::new("test")
let cmd = Command::new("test")
.global_setting(AppSettings::DeriveDisplayOrder)
.subcommand(
Command::new("sub").version("1.2").args(&[
@ -230,7 +230,7 @@ fn derive_order_subcommand_propagate() {
);
assert!(utils::compare_output(
app,
cmd,
"test sub --help",
UNIFIED_DERIVE_SC_PROP,
false
@ -239,7 +239,7 @@ fn derive_order_subcommand_propagate() {
#[test]
fn derive_order_subcommand_propagate_with_explicit_display_order() {
let app = Command::new("test")
let cmd = Command::new("test")
.global_setting(AppSettings::DeriveDisplayOrder)
.subcommand(
Command::new("sub").version("1.2").args(&[
@ -260,7 +260,7 @@ fn derive_order_subcommand_propagate_with_explicit_display_order() {
);
assert!(utils::compare_output(
app,
cmd,
"test sub --help",
UNIFIED_DERIVE_SC_PROP_EXPLICIT_ORDER,
false
@ -269,7 +269,7 @@ fn derive_order_subcommand_propagate_with_explicit_display_order() {
#[test]
fn prefer_user_help_with_derive_order() {
let app = Command::new("test")
let cmd = Command::new("test")
.setting(AppSettings::DeriveDisplayOrder)
.version("1.2")
.args(&[
@ -282,7 +282,7 @@ fn prefer_user_help_with_derive_order() {
]);
assert!(utils::compare_output(
app,
cmd,
"test --help",
PREFER_USER_HELP_DERIVE_ORDER,
false
@ -291,7 +291,7 @@ fn prefer_user_help_with_derive_order() {
#[test]
fn prefer_user_help_in_subcommand_with_derive_order() {
let app = Command::new("test")
let cmd = Command::new("test")
.global_setting(AppSettings::DeriveDisplayOrder)
.subcommand(
Command::new("sub").version("1.2").args(&[
@ -305,7 +305,7 @@ fn prefer_user_help_in_subcommand_with_derive_order() {
);
assert!(utils::compare_output(
app,
cmd,
"test sub --help",
PREFER_USER_HELP_SUBCMD_DERIVE_ORDER,
false

View file

@ -4,10 +4,10 @@ use clap::Command;
#[test]
fn very_large_display_order() {
let app = Command::new("test").subcommand(Command::new("sub").display_order(usize::MAX));
let cmd = Command::new("test").subcommand(Command::new("sub").display_order(usize::MAX));
assert!(utils::compare_output(
app,
cmd,
"test --help",
"test

View file

@ -30,7 +30,7 @@ USAGE:
For more information try --help
";
fn app() -> Command<'static> {
fn cmd() -> Command<'static> {
Command::new("prog")
.arg(
Arg::new("a")
@ -54,17 +54,17 @@ fn app() -> Command<'static> {
#[test]
fn valid_cases() {
let res = app().try_get_matches_from(vec!["", "-a"]);
let res = cmd().try_get_matches_from(vec!["", "-a"]);
assert!(res.is_ok(), "{}", res.unwrap_err());
let res = app().clone().try_get_matches_from(vec!["", "-b", "-c"]);
let res = cmd().clone().try_get_matches_from(vec!["", "-b", "-c"]);
assert!(res.is_ok(), "{}", res.unwrap_err());
let res = app().try_get_matches_from(vec!["", "-c", "-b"]);
let res = cmd().try_get_matches_from(vec!["", "-c", "-b"]);
assert!(res.is_ok(), "{}", res.unwrap_err());
}
#[test]
fn help_text() {
let res = app().try_get_matches_from(vec!["prog", "--help"]);
let res = cmd().try_get_matches_from(vec!["prog", "--help"]);
assert!(res.is_err());
let err = res.unwrap_err();
assert_eq!(err.kind(), ErrorKind::DisplayHelp);
@ -74,13 +74,13 @@ fn help_text() {
#[test]
fn no_duplicate_error() {
let res = app().try_get_matches_from(vec!["", "-b"]);
let res = cmd().try_get_matches_from(vec!["", "-b"]);
assert!(res.is_err());
let err = res.unwrap_err();
assert_eq!(err.kind(), ErrorKind::MissingRequiredArgument);
assert_eq!(err.to_string(), ONLY_B_ERROR);
let res = app().try_get_matches_from(vec!["", "-c"]);
let res = cmd().try_get_matches_from(vec!["", "-c"]);
assert!(res.is_err());
let err = res.unwrap_err();
assert_eq!(err.kind(), ErrorKind::MissingRequiredArgument);

View file

@ -103,14 +103,14 @@ fn no_empty_values_without_equals() {
#[test]
fn no_empty_values_without_equals_but_requires_equals() {
let app = Command::new("config").arg(
let cmd = Command::new("config").arg(
Arg::new("config")
.long("config")
.takes_value(true)
.forbid_empty_values(true)
.require_equals(true),
);
let m = app.clone().try_get_matches_from(&["config", "--config"]);
let m = cmd.clone().try_get_matches_from(&["config", "--config"]);
// Should error on no equals rather than empty value.
assert!(m.is_err());
assert_eq!(m.unwrap_err().kind(), ErrorKind::NoEquals);
@ -125,7 +125,7 @@ For more information try --help
";
assert!(utils::compare_output(
app,
cmd,
"config --config",
NO_EUQALS_ERROR,
true

View file

@ -29,7 +29,7 @@ USAGE:
For more information try --help
";
let app = Command::new("test")
let cmd = Command::new("test")
.arg(
Arg::new("all")
.short('a')
@ -52,9 +52,9 @@ For more information try --help
.long("no-git-push")
.help("Do not push generated commit and tags to git remote"),
);
let mut app = app;
let mut cmd = cmd;
let expected_kind = ErrorKind::InvalidValue;
let err = app.error(expected_kind, "Failed for mysterious reasons");
let err = cmd.error(expected_kind, "Failed for mysterious reasons");
assert!(compare_error(err, expected_kind, MESSAGE, true));
}

View file

@ -124,7 +124,7 @@ fn flag_subcommand_long_with_alias_same_as_long_flag() {
#[test]
fn flag_subcommand_short_with_aliases_vis_and_hidden() {
let app = Command::new("test").subcommand(
let cmd = Command::new("test").subcommand(
Command::new("some")
.short_flag('S')
.arg(
@ -136,15 +136,15 @@ fn flag_subcommand_short_with_aliases_vis_and_hidden() {
.visible_short_flag_aliases(&['M', 'B'])
.short_flag_alias('C'),
);
let app1 = app.clone();
let app1 = cmd.clone();
let matches1 = app1.try_get_matches_from(vec!["test", "-M"]).unwrap();
assert_eq!(matches1.subcommand_name().unwrap(), "some");
let app2 = app.clone();
let app2 = cmd.clone();
let matches2 = app2.try_get_matches_from(vec!["test", "-C"]).unwrap();
assert_eq!(matches2.subcommand_name().unwrap(), "some");
let app3 = app.clone();
let app3 = cmd.clone();
let matches3 = app3.try_get_matches_from(vec!["test", "-B"]).unwrap();
assert_eq!(matches3.subcommand_name().unwrap(), "some");
}
@ -471,7 +471,7 @@ OPTIONS:
#[test]
fn flag_subcommand_long_short_normal_usage_string() {
let app = Command::new("pacman")
let cmd = Command::new("pacman")
.about("package manager utility")
.version("5.2.1")
.subcommand_required(true)
@ -504,7 +504,7 @@ fn flag_subcommand_long_short_normal_usage_string() {
),
);
assert!(utils::compare_output(
app,
cmd,
"pacman -Qh",
FLAG_SUBCOMMAND_HELP,
false
@ -525,7 +525,7 @@ OPTIONS:
#[test]
fn flag_subcommand_long_normal_usage_string() {
let app = Command::new("pacman")
let cmd = Command::new("pacman")
.about("package manager utility")
.version("5.2.1")
.subcommand_required(true)
@ -557,7 +557,7 @@ fn flag_subcommand_long_normal_usage_string() {
),
);
assert!(utils::compare_output(
app,
cmd,
"pacman query --help",
FLAG_SUBCOMMAND_NO_SHORT_HELP,
false
@ -578,7 +578,7 @@ OPTIONS:
#[test]
fn flag_subcommand_short_normal_usage_string() {
let app = Command::new("pacman")
let cmd = Command::new("pacman")
.about("package manager utility")
.version("5.2.1")
.subcommand_required(true)
@ -610,7 +610,7 @@ fn flag_subcommand_short_normal_usage_string() {
),
);
assert!(utils::compare_output(
app,
cmd,
"pacman query --help",
FLAG_SUBCOMMAND_NO_LONG_HELP,
false

View file

@ -138,30 +138,30 @@ fn multiple_flags_in_single() {
#[test]
fn issue_1284_argument_in_flag_style() {
let app = Command::new("mycat")
let cmd = Command::new("mycat")
.arg(Arg::new("filename"))
.arg(Arg::new("a-flag").long("a-flag"));
let m = app
let m = cmd
.clone()
.try_get_matches_from(vec!["", "--", "--another-flag"])
.unwrap();
assert_eq!(m.value_of("filename"), Some("--another-flag"));
let m = app
let m = cmd
.clone()
.try_get_matches_from(vec!["", "--a-flag"])
.unwrap();
assert!(m.is_present("a-flag"));
let m = app
let m = cmd
.clone()
.try_get_matches_from(vec!["", "--", "--a-flag"])
.unwrap();
assert_eq!(m.value_of("filename"), Some("--a-flag"));
assert!(utils::compare_output(
app,
cmd,
"mycat --another-flag",
USE_FLAG_AS_ARGUMENT,
true
@ -180,10 +180,10 @@ USAGE:
For more information try --help
";
let app = Command::new("test").arg(Arg::new("arg").takes_value(true).required(true));
let cmd = Command::new("test").arg(Arg::new("arg").takes_value(true).required(true));
assert!(utils::compare_output(
app,
cmd,
"test -----",
MULTIPLE_DASHES,
true

View file

@ -2,7 +2,7 @@ use clap::{arg, Arg, Command};
#[test]
fn issue_1076() {
let mut app = Command::new("myprog")
let mut cmd = Command::new("myprog")
.arg(
Arg::new("GLOBAL_ARG")
.long("global-arg")
@ -19,9 +19,9 @@ fn issue_1076() {
.takes_value(true),
)
.subcommand(Command::new("outer").subcommand(Command::new("inner")));
let _ = app.try_get_matches_from_mut(vec!["myprog"]);
let _ = app.try_get_matches_from_mut(vec!["myprog"]);
let _ = app.try_get_matches_from_mut(vec!["myprog"]);
let _ = cmd.try_get_matches_from_mut(vec!["myprog"]);
let _ = cmd.try_get_matches_from_mut(vec!["myprog"]);
let _ = cmd.try_get_matches_from_mut(vec!["myprog"]);
}
#[test]
@ -57,7 +57,7 @@ fn propagate_global_arg_to_subcommand_in_subsubcommand_2053() {
.subcommand(Command::new("test")),
)
.try_get_matches_from(&[
"app",
"cmd",
"test",
"test",
"--global-flag",
@ -91,7 +91,7 @@ fn global_arg_available_in_subcommand() {
#[test]
fn deeply_nested_discovery() {
let app = Command::new("a")
let cmd = Command::new("a")
.arg(arg!(--"long-a").global(true))
.subcommand(
Command::new("b")
@ -103,7 +103,7 @@ fn deeply_nested_discovery() {
),
);
let m = app
let m = cmd
.try_get_matches_from(["a", "b", "c", "d", "--long-a", "--long-b", "--long-c"])
.unwrap();
assert!(m.is_present("long-a"));

View file

@ -176,7 +176,7 @@ fn grouped_value_multiple_positional_arg_last_multiple() {
#[test]
fn issue_1374() {
let app = Command::new("MyApp").arg(
let cmd = Command::new("MyApp").arg(
Arg::new("input")
.takes_value(true)
.long("input")
@ -184,13 +184,13 @@ fn issue_1374() {
.min_values(0)
.multiple_occurrences(true),
);
let matches = app
let matches = cmd
.clone()
.try_get_matches_from(&["MyApp", "--input", "a", "b", "c", "--input", "d"])
.unwrap();
let vs = matches.values_of("input").unwrap();
assert_eq!(vs.collect::<Vec<_>>(), vec!["a", "b", "c", "d"]);
let matches = app
let matches = cmd
.clone()
.try_get_matches_from(&["MyApp", "--input", "a", "b", "--input", "c", "d"])
.unwrap();

View file

@ -167,7 +167,7 @@ fn empty_group() {
#[test]
fn req_group_usage_string() {
let app = Command::new("req_group")
let cmd = Command::new("req_group")
.arg(arg!([base] "Base commit"))
.arg(arg!(
-d --delete "Remove the base commit information"
@ -179,7 +179,7 @@ fn req_group_usage_string() {
);
assert!(utils::compare_output(
app,
cmd,
"clap-test",
REQ_GROUP_USAGE,
true
@ -188,7 +188,7 @@ fn req_group_usage_string() {
#[test]
fn req_group_with_conflict_usage_string() {
let app = Command::new("req_group")
let cmd = Command::new("req_group")
.arg(arg!([base] "Base commit").conflicts_with("delete"))
.arg(arg!(
-d --delete "Remove the base commit information"
@ -200,7 +200,7 @@ fn req_group_with_conflict_usage_string() {
);
assert!(utils::compare_output(
app,
cmd,
"clap-test --delete base",
REQ_GROUP_CONFLICT_USAGE,
true
@ -209,7 +209,7 @@ fn req_group_with_conflict_usage_string() {
#[test]
fn req_group_with_conflict_usage_string_only_options() {
let app = Command::new("req_group")
let cmd = Command::new("req_group")
.arg(arg!(-a --all "All").conflicts_with("delete"))
.arg(arg!(
-d --delete "Remove the base commit information"
@ -220,7 +220,7 @@ fn req_group_with_conflict_usage_string_only_options() {
.required(true),
);
assert!(utils::compare_output(
app,
cmd,
"clap-test --delete --all",
REQ_GROUP_CONFLICT_ONLY_OPTIONS,
true
@ -270,11 +270,11 @@ ARGS:
OPTIONS:
-h, --help Print help information
";
let app = Command::new("prog")
let cmd = Command::new("prog")
.arg(Arg::new("a").value_name("A"))
.group(ArgGroup::new("group").arg("a").required(true));
assert!(utils::compare_output(
app,
cmd,
"prog --help",
GROUP_USAGE_USE_VAL_NAME,
false,
@ -296,7 +296,7 @@ fn group_acts_like_arg() {
/* This is used to be fixed in a hack, we need to find a better way to fix it.
#[test]
fn issue_1794() {
let app = clap::Command::new("hello")
let cmd = clap::Command::new("hello")
.bin_name("deno")
.arg(Arg::new("option1").long("option1").takes_value(false))
.arg(Arg::new("pos1").takes_value(true))
@ -307,14 +307,14 @@ fn issue_1794() {
.required(true),
);
let m = app.clone().try_get_matches_from(&["app", "pos1", "pos2"]).unwrap();
let m = cmd.clone().try_get_matches_from(&["cmd", "pos1", "pos2"]).unwrap();
assert_eq!(m.value_of("pos1"), Some("pos1"));
assert_eq!(m.value_of("pos2"), Some("pos2"));
assert!(!m.is_present("option1"));
let m = app
let m = cmd
.clone()
.try_get_matches_from(&["app", "--option1", "positional"]).unwrap();
.try_get_matches_from(&["cmd", "--option1", "positional"]).unwrap();
assert_eq!(m.value_of("pos1"), None);
assert_eq!(m.value_of("pos2"), Some("positional"));
assert!(m.is_present("option1"));

File diff suppressed because it is too large Load diff

View file

@ -98,7 +98,7 @@ OPTIONS:
fn hide_env() {
env::set_var("ENVVAR", "MYVAL");
let app = Command::new("ctest").version("0.1").arg(
let cmd = Command::new("ctest").version("0.1").arg(
Arg::new("cafe")
.short('c')
.long("cafe")
@ -109,14 +109,14 @@ fn hide_env() {
.takes_value(true),
);
assert!(utils::compare_output(app, "ctest --help", HIDE_ENV, false));
assert!(utils::compare_output(cmd, "ctest --help", HIDE_ENV, false));
}
#[test]
fn show_env() {
env::set_var("ENVVAR", "MYVAL");
let app = Command::new("ctest").version("0.1").arg(
let cmd = Command::new("ctest").version("0.1").arg(
Arg::new("cafe")
.short('c')
.long("cafe")
@ -126,14 +126,14 @@ fn show_env() {
.takes_value(true),
);
assert!(utils::compare_output(app, "ctest --help", SHOW_ENV, false));
assert!(utils::compare_output(cmd, "ctest --help", SHOW_ENV, false));
}
#[test]
fn hide_env_vals() {
env::set_var("ENVVAR", "MYVAL");
let app = Command::new("ctest").version("0.1").arg(
let cmd = Command::new("ctest").version("0.1").arg(
Arg::new("cafe")
.short('c')
.long("cafe")
@ -145,7 +145,7 @@ fn hide_env_vals() {
);
assert!(utils::compare_output(
app,
cmd,
"ctest --help",
HIDE_ENV_VALS,
false
@ -156,7 +156,7 @@ fn hide_env_vals() {
fn show_env_vals() {
env::set_var("ENVVAR", "MYVAL");
let app = Command::new("ctest").version("0.1").arg(
let cmd = Command::new("ctest").version("0.1").arg(
Arg::new("cafe")
.short('c')
.long("cafe")
@ -167,7 +167,7 @@ fn show_env_vals() {
);
assert!(utils::compare_output(
app,
cmd,
"ctest --help",
SHOW_ENV_VALS,
false
@ -178,7 +178,7 @@ fn show_env_vals() {
fn hide_env_flag() {
env::set_var("ENVVAR", "MYVAL");
let app = Command::new("ctest").version("0.1").arg(
let cmd = Command::new("ctest").version("0.1").arg(
Arg::new("cafe")
.short('c')
.long("cafe")
@ -188,7 +188,7 @@ fn hide_env_flag() {
);
assert!(utils::compare_output(
app,
cmd,
"ctest --help",
HIDE_ENV_FLAG,
false
@ -199,7 +199,7 @@ fn hide_env_flag() {
fn show_env_flag() {
env::set_var("ENVVAR", "MYVAL");
let app = Command::new("ctest").version("0.1").arg(
let cmd = Command::new("ctest").version("0.1").arg(
Arg::new("cafe")
.short('c')
.long("cafe")
@ -208,7 +208,7 @@ fn show_env_flag() {
);
assert!(utils::compare_output(
app,
cmd,
"ctest --help",
SHOW_ENV_FLAG,
false
@ -219,7 +219,7 @@ fn show_env_flag() {
fn hide_env_vals_flag() {
env::set_var("ENVVAR", "MYVAL");
let app = Command::new("ctest").version("0.1").arg(
let cmd = Command::new("ctest").version("0.1").arg(
Arg::new("cafe")
.short('c')
.long("cafe")
@ -229,7 +229,7 @@ fn hide_env_vals_flag() {
);
assert!(utils::compare_output(
app,
cmd,
"ctest --help",
HIDE_ENV_VALS_FLAG,
false
@ -240,7 +240,7 @@ fn hide_env_vals_flag() {
fn show_env_vals_flag() {
env::set_var("ENVVAR", "MYVAL");
let app = Command::new("ctest").version("0.1").arg(
let cmd = Command::new("ctest").version("0.1").arg(
Arg::new("cafe")
.short('c')
.long("cafe")
@ -249,7 +249,7 @@ fn show_env_vals_flag() {
);
assert!(utils::compare_output(
app,
cmd,
"ctest --help",
SHOW_ENV_VALS_FLAG,
false

View file

@ -18,7 +18,7 @@ OPTIONS:
#[test]
fn hide_args() {
let app = Command::new("test")
let cmd = Command::new("test")
.author("Kevin K.")
.about("tests stuff")
.version("1.4")
@ -29,7 +29,7 @@ fn hide_args() {
Arg::new("DUMMY").hide(true),
]);
assert!(utils::compare_output(
app,
cmd,
"test --help",
HIDDEN_ARGS,
false
@ -73,7 +73,7 @@ OPTIONS:
/// Ensure hide with short option
#[test]
fn hide_short_args() {
let app = Command::new("test")
let cmd = Command::new("test")
.about("hides short args")
.author("Steve P.")
.version("2.31.2")
@ -90,7 +90,7 @@ fn hide_short_args() {
]);
assert!(utils::compare_output(
app,
cmd,
"test -h",
HIDDEN_SHORT_ARGS,
false
@ -100,7 +100,7 @@ fn hide_short_args() {
/// Ensure visible with opposite option
#[test]
fn hide_short_args_long_help() {
let app = Command::new("test")
let cmd = Command::new("test")
.about("hides short args")
.author("Steve P.")
.version("2.31.2")
@ -117,7 +117,7 @@ fn hide_short_args_long_help() {
]);
assert!(utils::compare_output(
app,
cmd,
"test --help",
HIDDEN_SHORT_ARGS_LONG_HELP,
false
@ -144,7 +144,7 @@ OPTIONS:
#[test]
fn hide_long_args() {
let app = Command::new("test")
let cmd = Command::new("test")
.about("hides long args")
.author("Steve P.")
.version("2.31.2")
@ -161,7 +161,7 @@ fn hide_long_args() {
]);
assert!(utils::compare_output(
app,
cmd,
"test --help",
HIDDEN_LONG_ARGS,
false
@ -184,7 +184,7 @@ OPTIONS:
#[test]
fn hide_long_args_short_help() {
let app = Command::new("test")
let cmd = Command::new("test")
.about("hides long args")
.author("Steve P.")
.version("2.31.2")
@ -201,7 +201,7 @@ fn hide_long_args_short_help() {
]);
assert!(utils::compare_output(
app,
cmd,
"test -h",
HIDDEN_LONG_ARGS_SHORT_HELP,
false
@ -223,13 +223,13 @@ OPTIONS:
#[test]
fn hide_pos_args() {
let app = Command::new("test").version("1.4").args(&[
let cmd = Command::new("test").version("1.4").args(&[
Arg::new("pos").help("some pos").hide(true),
Arg::new("another").help("another pos"),
]);
assert!(utils::compare_output(
app,
cmd,
"test --help",
HIDDEN_POS_ARGS,
false
@ -248,12 +248,12 @@ OPTIONS:
#[test]
fn hide_subcmds() {
let app = Command::new("test")
let cmd = Command::new("test")
.version("1.4")
.subcommand(Command::new("sub").hide(true));
assert!(utils::compare_output(
app,
cmd,
"test --help",
HIDDEN_SUBCMDS,
false
@ -270,7 +270,7 @@ After help
#[test]
fn hide_opt_args_only() {
let app = Command::new("test")
let cmd = Command::new("test")
.version("1.4")
.after_help("After help")
.mut_arg("help", |a| a.hide(true))
@ -282,7 +282,7 @@ fn hide_opt_args_only() {
);
assert!(utils::compare_output(
app,
cmd,
"test --help",
HIDDEN_OPT_ARGS_ONLY,
false
@ -299,7 +299,7 @@ After help
#[test]
fn hide_pos_args_only() {
let app = Command::new("test")
let cmd = Command::new("test")
.version("1.4")
.after_help("After help")
.mut_arg("help", |a| a.hide(true))
@ -307,7 +307,7 @@ fn hide_pos_args_only() {
.args(&[Arg::new("pos").help("some pos").hide(true)]);
assert!(utils::compare_output(
app,
cmd,
"test --help",
HIDDEN_POS_ARGS_ONLY,
false
@ -324,7 +324,7 @@ After help
#[test]
fn hide_subcmds_only() {
let app = Command::new("test")
let cmd = Command::new("test")
.version("1.4")
.after_help("After help")
.mut_arg("help", |a| a.hide(true))
@ -332,7 +332,7 @@ fn hide_subcmds_only() {
.subcommand(Command::new("sub").hide(true));
assert!(utils::compare_output(
app,
cmd,
"test --help",
HIDDEN_SUBCMDS_ONLY,
false

View file

@ -2,11 +2,11 @@ use clap::{arg, Arg, Command};
#[test]
fn single_short_arg_without_value() {
let app = Command::new("app").ignore_errors(true).arg(arg!(
let cmd = Command::new("cmd").ignore_errors(true).arg(arg!(
-c --config [FILE] "Sets a custom config file"
));
let r = app.try_get_matches_from(vec!["app", "-c" /* missing: , "config file" */]);
let r = cmd.try_get_matches_from(vec!["cmd", "-c" /* missing: , "config file" */]);
assert!(r.is_ok(), "unexpected error: {:?}", r);
let m = r.unwrap();
@ -15,11 +15,11 @@ fn single_short_arg_without_value() {
#[test]
fn single_long_arg_without_value() {
let app = Command::new("app").ignore_errors(true).arg(arg!(
let cmd = Command::new("cmd").ignore_errors(true).arg(arg!(
-c --config [FILE] "Sets a custom config file"
));
let r = app.try_get_matches_from(vec!["app", "--config" /* missing: , "config file" */]);
let r = cmd.try_get_matches_from(vec!["cmd", "--config" /* missing: , "config file" */]);
assert!(r.is_ok(), "unexpected error: {:?}", r);
let m = r.unwrap();
@ -28,7 +28,7 @@ fn single_long_arg_without_value() {
#[test]
fn multiple_args_and_final_arg_without_value() {
let app = Command::new("app")
let cmd = Command::new("cmd")
.ignore_errors(true)
.arg(arg!(
-c --config [FILE] "Sets a custom config file"
@ -38,8 +38,8 @@ fn multiple_args_and_final_arg_without_value() {
))
.arg(arg!(f: -f "Flag"));
let r = app.try_get_matches_from(vec![
"app", "-c", "file", "-f", "-x", /* missing: , "some stuff" */
let r = cmd.try_get_matches_from(vec![
"cmd", "-c", "file", "-f", "-x", /* missing: , "some stuff" */
]);
assert!(r.is_ok(), "unexpected error: {:?}", r);
@ -51,7 +51,7 @@ fn multiple_args_and_final_arg_without_value() {
#[test]
fn multiple_args_and_intermittent_arg_without_value() {
let app = Command::new("app")
let cmd = Command::new("cmd")
.ignore_errors(true)
.arg(arg!(
-c --config[FILE] "Sets a custom config file"
@ -61,8 +61,8 @@ fn multiple_args_and_intermittent_arg_without_value() {
))
.arg(arg!(f: -f "Flag"));
let r = app.try_get_matches_from(vec![
"app", "-x", /* missing: ,"some stuff" */
let r = cmd.try_get_matches_from(vec![
"cmd", "-x", /* missing: ,"some stuff" */
"-c", "file", "-f",
]);
@ -75,7 +75,7 @@ fn multiple_args_and_intermittent_arg_without_value() {
#[test]
fn subcommand() {
let app = Command::new("test")
let cmd = Command::new("test")
.ignore_errors(true)
.subcommand(
Command::new("some")
@ -96,7 +96,7 @@ fn subcommand() {
)
.arg(Arg::new("other").long("other"));
let m = app
let m = cmd
.try_get_matches_from(vec![
"myprog",
"some",

View file

@ -52,9 +52,9 @@ fn multiple_occurrences_of_flags_mixed() {
#[test]
fn multiple_occurrences_of_positional() {
let app = Command::new("test").arg(Arg::new("multi").multiple_occurrences(true));
let cmd = Command::new("test").arg(Arg::new("multi").multiple_occurrences(true));
let m = app
let m = cmd
.clone()
.try_get_matches_from(&["test"])
.expect("zero occurrences work");
@ -62,7 +62,7 @@ fn multiple_occurrences_of_positional() {
assert_eq!(m.occurrences_of("multi"), 0);
assert!(m.values_of("multi").is_none());
let m = app
let m = cmd
.clone()
.try_get_matches_from(&["test", "one"])
.expect("single occurrence work");
@ -70,7 +70,7 @@ fn multiple_occurrences_of_positional() {
assert_eq!(m.occurrences_of("multi"), 1);
assert_eq!(m.values_of("multi").unwrap().collect::<Vec<_>>(), ["one"]);
let m = app
let m = cmd
.clone()
.try_get_matches_from(&["test", "one", "two", "three", "four"])
.expect("many occurrences work");
@ -99,7 +99,7 @@ fn multiple_occurrences_of_flags_large_quantity() {
#[cfg(feature = "env")]
#[test]
fn multiple_occurrences_of_before_env() {
let app = Command::new("mo_before_env").arg(
let cmd = Command::new("mo_before_env").arg(
Arg::new("verbose")
.env("VERBOSE")
.short('v')
@ -108,18 +108,18 @@ fn multiple_occurrences_of_before_env() {
.multiple_occurrences(true),
);
let m = app.clone().try_get_matches_from(vec![""]);
let m = cmd.clone().try_get_matches_from(vec![""]);
assert!(m.is_ok(), "{}", m.unwrap_err());
assert_eq!(m.unwrap().occurrences_of("verbose"), 0);
let m = app.clone().try_get_matches_from(vec!["", "-v"]);
let m = cmd.clone().try_get_matches_from(vec!["", "-v"]);
assert!(m.is_ok(), "{}", m.unwrap_err());
assert_eq!(m.unwrap().occurrences_of("verbose"), 1);
let m = app.clone().try_get_matches_from(vec!["", "-vv"]);
let m = cmd.clone().try_get_matches_from(vec!["", "-vv"]);
assert!(m.is_ok(), "{}", m.unwrap_err());
assert_eq!(m.unwrap().occurrences_of("verbose"), 2);
let m = app.clone().try_get_matches_from(vec!["", "-vvv"]);
let m = cmd.clone().try_get_matches_from(vec!["", "-vvv"]);
assert!(m.is_ok(), "{}", m.unwrap_err());
assert_eq!(m.unwrap().occurrences_of("verbose"), 3);
}
@ -127,7 +127,7 @@ fn multiple_occurrences_of_before_env() {
#[cfg(feature = "env")]
#[test]
fn multiple_occurrences_of_after_env() {
let app = Command::new("mo_after_env").arg(
let cmd = Command::new("mo_after_env").arg(
Arg::new("verbose")
.short('v')
.long("verbose")
@ -136,44 +136,44 @@ fn multiple_occurrences_of_after_env() {
.env("VERBOSE"),
);
let m = app.clone().try_get_matches_from(vec![""]);
let m = cmd.clone().try_get_matches_from(vec![""]);
assert!(m.is_ok(), "{}", m.unwrap_err());
assert_eq!(m.unwrap().occurrences_of("verbose"), 0);
let m = app.clone().try_get_matches_from(vec!["", "-v"]);
let m = cmd.clone().try_get_matches_from(vec!["", "-v"]);
assert!(m.is_ok(), "{}", m.unwrap_err());
assert_eq!(m.unwrap().occurrences_of("verbose"), 1);
let m = app.clone().try_get_matches_from(vec!["", "-vv"]);
let m = cmd.clone().try_get_matches_from(vec!["", "-vv"]);
assert!(m.is_ok(), "{}", m.unwrap_err());
assert_eq!(m.unwrap().occurrences_of("verbose"), 2);
let m = app.clone().try_get_matches_from(vec!["", "-vvv"]);
let m = cmd.clone().try_get_matches_from(vec!["", "-vvv"]);
assert!(m.is_ok(), "{}", m.unwrap_err());
assert_eq!(m.unwrap().occurrences_of("verbose"), 3);
}
#[test]
fn max_occurrences_implies_multiple_occurrences() {
let app = Command::new("prog").arg(
let cmd = Command::new("prog").arg(
Arg::new("verbose")
.short('v')
.long("verbose")
.max_occurrences(3),
);
let m = app.try_get_matches_from(vec!["prog", "-vvv"]);
let m = cmd.try_get_matches_from(vec!["prog", "-vvv"]);
assert!(m.is_ok(), "{}", m.unwrap_err());
assert_eq!(m.unwrap().occurrences_of("verbose"), 3);
// One max should not imply multiple occurrences
let app = Command::new("prog").arg(
let cmd = Command::new("prog").arg(
Arg::new("verbose")
.short('v')
.long("verbose")
.max_occurrences(1),
);
let m = app.try_get_matches_from(vec!["prog", "-vvv"]);
let m = cmd.try_get_matches_from(vec!["prog", "-vvv"]);
assert!(m.is_err());
assert_eq!(m.unwrap_err().kind(), ErrorKind::UnexpectedMultipleUsage);
@ -181,35 +181,35 @@ fn max_occurrences_implies_multiple_occurrences() {
#[test]
fn max_occurrences_try_inputs() {
let app = Command::new("prog").arg(
let cmd = Command::new("prog").arg(
Arg::new("verbose")
.short('v')
.long("verbose")
.max_occurrences(3),
);
let m = app.clone().try_get_matches_from(vec!["prog", "-v"]);
let m = cmd.clone().try_get_matches_from(vec!["prog", "-v"]);
assert!(m.is_ok(), "{}", m.unwrap_err());
assert_eq!(m.unwrap().occurrences_of("verbose"), 1);
let m = app.clone().try_get_matches_from(vec!["prog", "-vv"]);
let m = cmd.clone().try_get_matches_from(vec!["prog", "-vv"]);
assert!(m.is_ok(), "{}", m.unwrap_err());
assert_eq!(m.unwrap().occurrences_of("verbose"), 2);
let m = app.clone().try_get_matches_from(vec!["prog", "-vvv"]);
let m = cmd.clone().try_get_matches_from(vec!["prog", "-vvv"]);
assert!(m.is_ok(), "{}", m.unwrap_err());
assert_eq!(m.unwrap().occurrences_of("verbose"), 3);
let m = app.clone().try_get_matches_from(vec!["prog", "-vvvv"]);
let m = cmd.clone().try_get_matches_from(vec!["prog", "-vvvv"]);
assert!(m.is_err());
assert_eq!(m.unwrap_err().kind(), ErrorKind::TooManyOccurrences);
let m = app
let m = cmd
.clone()
.try_get_matches_from(vec!["prog", "-v", "-v", "-v"]);
assert!(m.is_ok(), "{}", m.unwrap_err());
assert_eq!(m.unwrap().occurrences_of("verbose"), 3);
let m = app
let m = cmd
.clone()
.try_get_matches_from(vec!["prog", "-v", "-vv", "-v"]);
assert!(m.is_err());
@ -218,22 +218,22 @@ fn max_occurrences_try_inputs() {
#[test]
fn max_occurrences_positional() {
let app = Command::new("prog").arg(Arg::new("verbose").max_occurrences(3));
let m = app.clone().try_get_matches_from(vec!["prog", "v"]);
let cmd = Command::new("prog").arg(Arg::new("verbose").max_occurrences(3));
let m = cmd.clone().try_get_matches_from(vec!["prog", "v"]);
assert!(m.is_ok(), "{}", m.unwrap_err());
assert_eq!(m.unwrap().occurrences_of("verbose"), 1);
let m = app.clone().try_get_matches_from(vec!["prog", "v", "v"]);
let m = cmd.clone().try_get_matches_from(vec!["prog", "v", "v"]);
assert!(m.is_ok(), "{}", m.unwrap_err());
assert_eq!(m.unwrap().occurrences_of("verbose"), 2);
let m = app
let m = cmd
.clone()
.try_get_matches_from(vec!["prog", "v", "v", "v"]);
assert!(m.is_ok(), "{}", m.unwrap_err());
assert_eq!(m.unwrap().occurrences_of("verbose"), 3);
let m = app
let m = cmd
.clone()
.try_get_matches_from(vec!["prog", "v", "v", "v", "v"]);
assert!(m.is_err());

View file

@ -55,14 +55,14 @@ USAGE:
For more information try --help
";
let app = Command::new("prog").arg(
let cmd = Command::new("prog").arg(
Arg::new("cfg")
.require_equals(true)
.takes_value(true)
.long("config"),
);
assert!(utils::compare_output(
app,
cmd,
"prog --config file.conf",
NO_EQUALS,
true
@ -462,14 +462,14 @@ fn issue_1105_setup(argv: Vec<&'static str>) -> Result<ArgMatches, clap::Error>
#[test]
fn issue_1105_empty_value_long_fail() {
let r = issue_1105_setup(vec!["app", "--option", "--flag"]);
let r = issue_1105_setup(vec!["cmd", "--option", "--flag"]);
assert!(r.is_err());
assert_eq!(r.unwrap_err().kind(), ErrorKind::EmptyValue);
}
#[test]
fn issue_1105_empty_value_long_explicit() {
let r = issue_1105_setup(vec!["app", "--option", ""]);
let r = issue_1105_setup(vec!["cmd", "--option", ""]);
assert!(r.is_ok(), "{}", r.unwrap_err());
let m = r.unwrap();
assert_eq!(m.value_of("option"), Some(""));
@ -477,7 +477,7 @@ fn issue_1105_empty_value_long_explicit() {
#[test]
fn issue_1105_empty_value_long_equals() {
let r = issue_1105_setup(vec!["app", "--option="]);
let r = issue_1105_setup(vec!["cmd", "--option="]);
assert!(r.is_ok(), "{}", r.unwrap_err());
let m = r.unwrap();
assert_eq!(m.value_of("option"), Some(""));
@ -485,14 +485,14 @@ fn issue_1105_empty_value_long_equals() {
#[test]
fn issue_1105_empty_value_short_fail() {
let r = issue_1105_setup(vec!["app", "-o", "--flag"]);
let r = issue_1105_setup(vec!["cmd", "-o", "--flag"]);
assert!(r.is_err());
assert_eq!(r.unwrap_err().kind(), ErrorKind::EmptyValue);
}
#[test]
fn issue_1105_empty_value_short_explicit() {
let r = issue_1105_setup(vec!["app", "-o", ""]);
let r = issue_1105_setup(vec!["cmd", "-o", ""]);
assert!(r.is_ok(), "{}", r.unwrap_err());
let m = r.unwrap();
assert_eq!(m.value_of("option"), Some(""));
@ -500,7 +500,7 @@ fn issue_1105_empty_value_short_explicit() {
#[test]
fn issue_1105_empty_value_short_equals() {
let r = issue_1105_setup(vec!["app", "-o="]);
let r = issue_1105_setup(vec!["cmd", "-o="]);
assert!(r.is_ok(), "{}", r.unwrap_err());
let m = r.unwrap();
assert_eq!(m.value_of("option"), Some(""));
@ -508,7 +508,7 @@ fn issue_1105_empty_value_short_equals() {
#[test]
fn issue_1105_empty_value_short_explicit_no_space() {
let r = issue_1105_setup(vec!["app", "-o", ""]);
let r = issue_1105_setup(vec!["cmd", "-o", ""]);
assert!(r.is_ok(), "{}", r.unwrap_err());
let m = r.unwrap();
assert_eq!(m.value_of("option"), Some(""));
@ -517,11 +517,11 @@ fn issue_1105_empty_value_short_explicit_no_space() {
#[test]
#[cfg(feature = "suggestions")]
fn issue_1073_suboptimal_flag_suggestion() {
let app = Command::new("ripgrep-616")
let cmd = Command::new("ripgrep-616")
.arg(Arg::new("files-with-matches").long("files-with-matches"))
.arg(Arg::new("files-without-match").long("files-without-match"));
assert!(utils::compare_output(
app,
cmd,
"ripgrep-616 --files-without-matches",
DYM_ISSUE_1073,
true
@ -530,7 +530,7 @@ fn issue_1073_suboptimal_flag_suggestion() {
#[test]
fn short_non_ascii_no_space() {
let matches = Command::new("app")
let matches = Command::new("cmd")
.arg(arg!(opt: -'磨' <opt>))
.try_get_matches_from(&["test", "-磨VALUE"])
.unwrap();
@ -540,7 +540,7 @@ fn short_non_ascii_no_space() {
#[test]
fn short_eq_val_starts_with_eq() {
let matches = Command::new("app")
let matches = Command::new("cmd")
.arg(arg!(opt: -f <opt>))
.try_get_matches_from(&["test", "-f==value"])
.unwrap();
@ -550,7 +550,7 @@ fn short_eq_val_starts_with_eq() {
#[test]
fn long_eq_val_starts_with_eq() {
let matches = Command::new("app")
let matches = Command::new("cmd")
.arg(arg!(opt: --foo <opt>))
.try_get_matches_from(&["test", "--foo==value"])
.unwrap();
@ -560,16 +560,16 @@ fn long_eq_val_starts_with_eq() {
#[test]
fn issue_2022_get_flags_misuse() {
let app = Command::new("test")
let cmd = Command::new("test")
.next_help_heading(Some("test"))
.arg(Arg::new("a").long("a").default_value("32"));
let matches = app.try_get_matches_from(&[""]).unwrap();
let matches = cmd.try_get_matches_from(&[""]).unwrap();
assert!(matches.value_of("a").is_some())
}
#[test]
fn issue_2279() {
let before_help_heading = Command::new("app")
let before_help_heading = Command::new("cmd")
.arg(Arg::new("foo").short('f').default_value("bar"))
.next_help_heading(Some("This causes default_value to be ignored"))
.try_get_matches_from(&[""])
@ -577,7 +577,7 @@ fn issue_2279() {
assert_eq!(before_help_heading.value_of("foo"), Some("bar"));
let after_help_heading = Command::new("app")
let after_help_heading = Command::new("cmd")
.next_help_heading(Some("This causes default_value to be ignored"))
.arg(Arg::new("foo").short('f').default_value("bar"))
.try_get_matches_from(&[""])
@ -588,39 +588,39 @@ fn issue_2279() {
#[test]
fn infer_long_arg() {
let app = Command::new("test")
let cmd = Command::new("test")
.infer_long_args(true)
.arg(Arg::new("racetrack").long("racetrack").alias("autobahn"))
.arg(Arg::new("racecar").long("racecar").takes_value(true));
let matches = app
let matches = cmd
.clone()
.try_get_matches_from(&["test", "--racec=hello"])
.unwrap();
assert!(!matches.is_present("racetrack"));
assert_eq!(matches.value_of("racecar"), Some("hello"));
let matches = app
let matches = cmd
.clone()
.try_get_matches_from(&["test", "--racet"])
.unwrap();
assert!(matches.is_present("racetrack"));
assert_eq!(matches.value_of("racecar"), None);
let matches = app
let matches = cmd
.clone()
.try_get_matches_from(&["test", "--auto"])
.unwrap();
assert!(matches.is_present("racetrack"));
assert_eq!(matches.value_of("racecar"), None);
let app = Command::new("test")
let cmd = Command::new("test")
.infer_long_args(true)
.arg(Arg::new("arg").long("arg"));
let matches = app.clone().try_get_matches_from(&["test", "--"]).unwrap();
let matches = cmd.clone().try_get_matches_from(&["test", "--"]).unwrap();
assert!(!matches.is_present("arg"));
let matches = app.clone().try_get_matches_from(&["test", "--a"]).unwrap();
let matches = cmd.clone().try_get_matches_from(&["test", "--a"]).unwrap();
assert!(matches.is_present("arg"));
}

View file

@ -179,36 +179,36 @@ fn positional_hyphen_does_not_panic() {
#[test]
fn single_positional_usage_string() {
let mut app = Command::new("test").arg(arg!([FILE] "some file"));
assert_eq!(app.render_usage(), "USAGE:\n test [FILE]");
let mut cmd = Command::new("test").arg(arg!([FILE] "some file"));
assert_eq!(cmd.render_usage(), "USAGE:\n test [FILE]");
}
#[test]
fn single_positional_multiple_usage_string() {
let mut app = Command::new("test").arg(arg!([FILE]... "some file"));
assert_eq!(app.render_usage(), "USAGE:\n test [FILE]...");
let mut cmd = Command::new("test").arg(arg!([FILE]... "some file"));
assert_eq!(cmd.render_usage(), "USAGE:\n test [FILE]...");
}
#[test]
fn multiple_positional_usage_string() {
let mut app = Command::new("test")
let mut cmd = Command::new("test")
.arg(arg!([FILE] "some file"))
.arg(arg!([FILES]... "some file"));
assert_eq!(app.render_usage(), "USAGE:\n test [ARGS]");
assert_eq!(cmd.render_usage(), "USAGE:\n test [ARGS]");
}
#[test]
fn multiple_positional_one_required_usage_string() {
let mut app = Command::new("test")
let mut cmd = Command::new("test")
.arg(arg!(<FILE> "some file"))
.arg(arg!([FILES]... "some file"));
assert_eq!(app.render_usage(), "USAGE:\n test <FILE> [FILES]...");
assert_eq!(cmd.render_usage(), "USAGE:\n test <FILE> [FILES]...");
}
#[test]
fn single_positional_required_usage_string() {
let mut app = Command::new("test").arg(arg!(<FILE> "some file"));
assert_eq!(app.render_usage(), "USAGE:\n test <FILE>");
let mut cmd = Command::new("test").arg(arg!(<FILE> "some file"));
assert_eq!(cmd.render_usage(), "USAGE:\n test <FILE>");
}
// This tests a programmer error and will only succeed with debug_assertions
@ -290,7 +290,7 @@ fn positional_arg_with_short() {
#[test]
fn ignore_hyphen_values_on_last() {
let app = clap::Command::new("foo")
let cmd = clap::Command::new("foo")
.arg(
clap::Arg::new("cmd")
.multiple_values(true)
@ -305,6 +305,6 @@ fn ignore_hyphen_values_on_last() {
.required(false),
);
let matches = app.try_get_matches_from(["test", "-n", "foo"]).unwrap();
let matches = cmd.try_get_matches_from(["test", "-n", "foo"]).unwrap();
assert_eq!(matches.value_of("name"), Some("foo"));
}

View file

@ -366,19 +366,19 @@ fn require_overridden_4() {
#[test]
fn issue_1374_overrides_self_with_multiple_values() {
let app = Command::new("test").arg(
let cmd = Command::new("test").arg(
Arg::new("input")
.long("input")
.takes_value(true)
.overrides_with("input")
.min_values(0),
);
let m = app
let m = cmd
.clone()
.try_get_matches_from(&["test", "--input", "a", "b", "c", "--input", "d"])
.unwrap();
assert_eq!(m.values_of("input").unwrap().collect::<Vec<_>>(), &["d"]);
let m = app
let m = cmd
.clone()
.try_get_matches_from(&["test", "--input", "a", "b", "--input", "c", "d"])
.unwrap();
@ -390,10 +390,10 @@ fn issue_1374_overrides_self_with_multiple_values() {
#[test]
fn incremental_override() {
let mut app = Command::new("test")
let mut cmd = Command::new("test")
.arg(arg!(--name <NAME>).multiple_occurrences(true))
.arg(arg!(--"no-name").overrides_with("name"));
let m = app
let m = cmd
.try_get_matches_from_mut(&["test", "--name=ahmed", "--no-name", "--name=ali"])
.unwrap();
assert_eq!(m.values_of("name").unwrap().collect::<Vec<_>>(), &["ali"]);

View file

@ -20,8 +20,8 @@ fn get_app() -> Command<'static> {
.subcommand(Command::new("outer").subcommand(Command::new("inner")))
}
fn get_matches(app: Command<'static>, argv: &'static str) -> ArgMatches {
app.try_get_matches_from(argv.split(' ').collect::<Vec<_>>())
fn get_matches(cmd: Command<'static>, argv: &'static str) -> ArgMatches {
cmd.try_get_matches_from(argv.split(' ').collect::<Vec<_>>())
.unwrap()
}

View file

@ -117,13 +117,13 @@ fn positional_required_2() {
#[test]
fn positional_required_with_requires() {
let app = Command::new("positional_required")
let cmd = Command::new("positional_required")
.arg(Arg::new("flag").required(true).requires("opt"))
.arg(Arg::new("opt"))
.arg(Arg::new("bar"));
assert!(utils::compare_output(
app,
cmd,
"clap-test",
POSITIONAL_REQ,
true
@ -142,13 +142,13 @@ For more information try --help
#[test]
fn positional_required_with_requires_if_no_value() {
let app = Command::new("positional_required")
let cmd = Command::new("positional_required")
.arg(Arg::new("flag").required(true).requires_if("val", "opt"))
.arg(Arg::new("opt"))
.arg(Arg::new("bar"));
assert!(utils::compare_output(
app,
cmd,
"clap-test",
POSITIONAL_REQ_IF_NO_VAL,
true
@ -166,14 +166,14 @@ For more information try --help
#[test]
fn positional_required_with_requires_if_value() {
let app = Command::new("positional_required")
let cmd = Command::new("positional_required")
.arg(Arg::new("flag").required(true).requires_if("val", "opt"))
.arg(Arg::new("foo").required(true))
.arg(Arg::new("opt"))
.arg(Arg::new("bar"));
assert!(utils::compare_output(
app,
cmd,
"clap-test val",
POSITIONAL_REQ_IF_VAL,
true
@ -770,7 +770,7 @@ fn required_if_any_all_values_present_fail() {
#[test]
fn list_correct_required_args() {
let app = Command::new("Test app")
let cmd = Command::new("Test cmd")
.version("1.0")
.author("F0x06")
.about("Arg test")
@ -795,7 +795,7 @@ fn list_correct_required_args() {
);
assert!(utils::compare_output(
app,
cmd,
"test --input somepath --target file",
COND_REQ_IN_USAGE,
true
@ -804,7 +804,7 @@ fn list_correct_required_args() {
#[test]
fn required_if_val_present_fail_error_output() {
let app = Command::new("Test app")
let cmd = Command::new("Test cmd")
.version("1.0")
.author("F0x06")
.about("Arg test")
@ -829,7 +829,7 @@ fn required_if_val_present_fail_error_output() {
);
assert!(utils::compare_output(
app,
cmd,
"test --input somepath --target file",
COND_REQ_IN_USAGE,
true
@ -919,7 +919,7 @@ fn required_ifs_wrong_val_mult_fail() {
#[test]
fn require_eq() {
let app = Command::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')
@ -929,7 +929,7 @@ fn require_eq() {
.help("some"),
);
assert!(utils::compare_output(
app,
cmd,
"clap-test",
REQUIRE_EQUALS,
true
@ -938,7 +938,7 @@ fn require_eq() {
#[test]
fn require_eq_filtered() {
let app = Command::new("clap-test")
let cmd = Command::new("clap-test")
.version("v1.4.8")
.arg(
Arg::new("opt")
@ -959,7 +959,7 @@ fn require_eq_filtered() {
.help("some other arg"),
);
assert!(utils::compare_output(
app,
cmd,
"clap-test -f=blah",
REQUIRE_EQUALS_FILTERED,
true
@ -968,7 +968,7 @@ fn require_eq_filtered() {
#[test]
fn require_eq_filtered_group() {
let app = Command::new("clap-test")
let cmd = Command::new("clap-test")
.version("v1.4.8")
.arg(
Arg::new("opt")
@ -1006,7 +1006,7 @@ fn require_eq_filtered_group() {
.required(true),
);
assert!(utils::compare_output(
app,
cmd,
"clap-test -f=blah --g1=blah",
REQUIRE_EQUALS_FILTERED_GROUP,
true
@ -1055,7 +1055,7 @@ USAGE:
For more information try --help
";
let app = Command::new("test")
let cmd = Command::new("test")
.arg(
Arg::new("a")
.long("a")
@ -1085,7 +1085,7 @@ For more information try --help
.conflicts_with("c"),
);
assert!(utils::compare_output(
app,
cmd,
"test --c asd",
MULTIPLE_REQUIRED_UNLESS_USAGE,
true
@ -1094,9 +1094,9 @@ For more information try --help
#[test]
fn issue_1158_conflicting_requirements() {
let app = issue_1158_app();
let cmd = issue_1158_app();
assert!(utils::compare_output(app, "example id", ISSUE_1158, true));
assert!(utils::compare_output(cmd, "example id", ISSUE_1158, true));
}
#[test]
@ -1110,7 +1110,7 @@ fn issue_1158_conflicting_requirements_rev() {
fn issue_1643_args_mutually_require_each_other() {
use clap::*;
let app = Command::new("test")
let cmd = Command::new("test")
.arg(
Arg::new("relation_id")
.help("The relation id to get the data from")
@ -1128,7 +1128,7 @@ fn issue_1643_args_mutually_require_each_other() {
.requires("relation_id"),
);
app.try_get_matches_from(&["test", "-u", "hello", "-r", "farewell"])
cmd.try_get_matches_from(&["test", "-u", "hello", "-r", "farewell"])
.unwrap();
}
@ -1168,7 +1168,7 @@ fn issue_2624() {
#[test]
fn required_unless_all_with_any() {
let app = Command::new("prog")
let cmd = Command::new("prog")
.arg(Arg::new("foo").long("foo"))
.arg(Arg::new("bar").long("bar"))
.arg(Arg::new("baz").long("baz"))
@ -1179,23 +1179,23 @@ fn required_unless_all_with_any() {
.required_unless_present_all(&["bar", "baz"]),
);
let result = app.clone().try_get_matches_from(vec!["myprog"]);
let result = cmd.clone().try_get_matches_from(vec!["myprog"]);
assert!(result.is_err(), "{:?}", result.unwrap());
let result = app.clone().try_get_matches_from(vec!["myprog", "--foo"]);
let result = cmd.clone().try_get_matches_from(vec!["myprog", "--foo"]);
assert!(result.is_ok(), "{:?}", result.unwrap_err());
assert!(!result.unwrap().is_present("flag"));
let result = app
let result = cmd
.clone()
.try_get_matches_from(vec!["myprog", "--bar", "--baz"]);
assert!(result.is_ok(), "{:?}", result.unwrap_err());
assert!(!result.unwrap().is_present("flag"));
let result = app.try_get_matches_from(vec!["myprog", "--bar"]);
let result = cmd.try_get_matches_from(vec!["myprog", "--bar"]);
assert!(result.is_err(), "{:?}", result.unwrap());
}

View file

@ -92,7 +92,7 @@ static SUBCMD_AFTER_DOUBLE_DASH: &str =
\tIf you tried to supply `subcmd` as a subcommand, remove the '--' before it.
USAGE:
app [SUBCOMMAND]
cmd [SUBCOMMAND]
For more information try --help
";
@ -222,18 +222,18 @@ fn multiple_aliases() {
#[test]
#[cfg(feature = "suggestions")]
fn subcmd_did_you_mean_output() {
let app = Command::new("dym").subcommand(Command::new("subcmd"));
assert!(utils::compare_output(app, "dym subcm", DYM_SUBCMD, true));
let cmd = Command::new("dym").subcommand(Command::new("subcmd"));
assert!(utils::compare_output(cmd, "dym subcm", DYM_SUBCMD, true));
}
#[test]
#[cfg(feature = "suggestions")]
fn subcmd_did_you_mean_output_ambiguous() {
let app = Command::new("dym")
let cmd = Command::new("dym")
.subcommand(Command::new("test"))
.subcommand(Command::new("temp"));
assert!(utils::compare_output(
app,
cmd,
"dym te",
DYM_SUBCMD_AMBIGUOUS,
true
@ -256,12 +256,12 @@ USAGE:
For more information try --help
";
let app = Command::new("dym").subcommand(
let cmd = Command::new("dym").subcommand(
Command::new("subcmd").arg(arg!(-s --subcmdarg <subcmdarg> "tests").required(false)),
);
assert!(utils::compare_output(
app,
cmd,
"dym --subcmarg subcmd",
EXPECTED,
true
@ -282,12 +282,12 @@ USAGE:
For more information try --help
";
let app = Command::new("dym").subcommand(
let cmd = Command::new("dym").subcommand(
Command::new("subcmd").arg(arg!(-s --subcmdarg <subcmdarg> "tests").required(false)),
);
assert!(utils::compare_output(
app,
cmd,
"dym --subcmarg foo",
EXPECTED,
true
@ -305,7 +305,7 @@ fn alias_help() {
#[test]
fn visible_aliases_help_output() {
let app = Command::new("clap-test").version("2.6").subcommand(
let cmd = Command::new("clap-test").version("2.6").subcommand(
Command::new("test")
.about("Some help")
.alias("invisible")
@ -313,7 +313,7 @@ fn visible_aliases_help_output() {
.visible_alias("done"),
);
assert!(utils::compare_output(
app,
cmd,
"clap-test --help",
VISIBLE_ALIAS_HELP,
false
@ -322,11 +322,11 @@ fn visible_aliases_help_output() {
#[test]
fn invisible_aliases_help_output() {
let app = Command::new("clap-test")
let cmd = Command::new("clap-test")
.version("2.6")
.subcommand(Command::new("test").about("Some help").alias("invisible"));
assert!(utils::compare_output(
app,
cmd,
"clap-test --help",
INVISIBLE_ALIAS_HELP,
false
@ -429,15 +429,15 @@ fn issue_1722_not_emit_error_when_arg_follows_similar_to_a_subcommand() {
#[test]
fn subcommand_placeholder_test() {
let mut app = Command::new("myprog")
let mut cmd = Command::new("myprog")
.subcommand(Command::new("subcommand"))
.subcommand_value_name("TEST_PLACEHOLDER")
.subcommand_help_heading("TEST_HEADER");
assert_eq!(&app.render_usage(), "USAGE:\n myprog [TEST_PLACEHOLDER]");
assert_eq!(&cmd.render_usage(), "USAGE:\n myprog [TEST_PLACEHOLDER]");
let mut help_text = Vec::new();
app.write_help(&mut help_text)
cmd.write_help(&mut help_text)
.expect("Failed to write to internal buffer");
assert!(String::from_utf8(help_text)
@ -447,11 +447,11 @@ fn subcommand_placeholder_test() {
#[test]
fn subcommand_used_after_double_dash() {
let app = Command::new("app").subcommand(Command::new("subcmd"));
let cmd = Command::new("cmd").subcommand(Command::new("subcmd"));
assert!(utils::compare_output(
app,
"app -- subcmd",
cmd,
"cmd -- subcmd",
SUBCMD_AFTER_DOUBLE_DASH,
true
));
@ -481,37 +481,37 @@ fn subcommand_after_argument_looks_like_help() {
#[test]
fn issue_2494_subcommand_is_present() {
let app = Command::new("opt")
let cmd = Command::new("opt")
.arg(Arg::new("global").long("global"))
.subcommand(Command::new("global"));
let m = app
let m = cmd
.clone()
.try_get_matches_from(&["opt", "--global", "global"])
.unwrap();
assert_eq!(m.subcommand_name().unwrap(), "global");
assert!(m.is_present("global"));
let m = app
let m = cmd
.clone()
.try_get_matches_from(&["opt", "--global"])
.unwrap();
assert!(m.subcommand_name().is_none());
assert!(m.is_present("global"));
let m = app.try_get_matches_from(&["opt", "global"]).unwrap();
let m = cmd.try_get_matches_from(&["opt", "global"]).unwrap();
assert_eq!(m.subcommand_name().unwrap(), "global");
assert!(!m.is_present("global"));
}
#[test]
fn subcommand_not_recognized() {
let app = Command::new("fake")
let cmd = Command::new("fake")
.subcommand(Command::new("sub"))
.disable_help_subcommand(true)
.infer_subcommands(true);
assert!(utils::compare_output(
app,
cmd,
"fake help",
"error: The subcommand 'help' wasn't recognized
@ -530,22 +530,22 @@ fn busybox_like_multicall() {
fn applet_commands() -> [Command<'static>; 2] {
[Command::new("true"), Command::new("false")]
}
let app = Command::new("busybox")
let cmd = Command::new("busybox")
.multicall(true)
.subcommand(Command::new("busybox").subcommands(applet_commands()))
.subcommands(applet_commands());
let m = app
let m = cmd
.clone()
.try_get_matches_from(&["busybox", "true"])
.unwrap();
assert_eq!(m.subcommand_name(), Some("busybox"));
assert_eq!(m.subcommand().unwrap().1.subcommand_name(), Some("true"));
let m = app.clone().try_get_matches_from(&["true"]).unwrap();
let m = cmd.clone().try_get_matches_from(&["true"]).unwrap();
assert_eq!(m.subcommand_name(), Some("true"));
let m = app.clone().try_get_matches_from(&["a.out"]);
let m = cmd.clone().try_get_matches_from(&["a.out"]);
assert!(m.is_err());
assert_eq!(m.unwrap_err().kind(), ErrorKind::UnknownArgument);
}
@ -553,29 +553,29 @@ fn busybox_like_multicall() {
#[cfg(feature = "unstable-multicall")]
#[test]
fn hostname_like_multicall() {
let mut app = Command::new("hostname")
let mut cmd = Command::new("hostname")
.multicall(true)
.subcommand(Command::new("hostname"))
.subcommand(Command::new("dnsdomainname"));
let m = app.clone().try_get_matches_from(&["hostname"]).unwrap();
let m = cmd.clone().try_get_matches_from(&["hostname"]).unwrap();
assert_eq!(m.subcommand_name(), Some("hostname"));
let m = app
let m = cmd
.clone()
.try_get_matches_from(&["dnsdomainname"])
.unwrap();
assert_eq!(m.subcommand_name(), Some("dnsdomainname"));
let m = app.clone().try_get_matches_from(&["a.out"]);
let m = cmd.clone().try_get_matches_from(&["a.out"]);
assert!(m.is_err());
assert_eq!(m.unwrap_err().kind(), ErrorKind::UnknownArgument);
let m = app.try_get_matches_from_mut(&["hostname", "hostname"]);
let m = cmd.try_get_matches_from_mut(&["hostname", "hostname"]);
assert!(m.is_err());
assert_eq!(m.unwrap_err().kind(), ErrorKind::UnknownArgument);
let m = app.try_get_matches_from(&["hostname", "dnsdomainname"]);
let m = cmd.try_get_matches_from(&["hostname", "dnsdomainname"]);
assert!(m.is_err());
assert_eq!(m.unwrap_err().kind(), ErrorKind::UnknownArgument);
}

View file

@ -67,9 +67,9 @@ SUBCOMMANDS:
#[test]
fn with_template() {
let app = get_app().help_template(EXAMPLE1_TMPL_S);
let cmd = get_app().help_template(EXAMPLE1_TMPL_S);
assert!(utils::compare_output(
app,
cmd,
"MyApp --help",
SIMPLE_TEMPLATE,
false
@ -78,9 +78,9 @@ fn with_template() {
#[test]
fn custom_template() {
let app = get_app().help_template(EXAMPLE1_TMPS_F);
let cmd = get_app().help_template(EXAMPLE1_TMPS_F);
assert!(utils::compare_output(
app,
cmd,
"MyApp --help",
CUSTOM_TEMPL_HELP,
false
@ -89,23 +89,23 @@ fn custom_template() {
#[test]
fn template_empty() {
let app = Command::new("MyApp")
let cmd = Command::new("MyApp")
.version("1.0")
.author("Kevin K. <kbknapp@gmail.com>")
.about("Does awesome things")
.help_template("");
assert!(utils::compare_output(app, "MyApp --help", "\n", false));
assert!(utils::compare_output(cmd, "MyApp --help", "\n", false));
}
#[test]
fn template_notag() {
let app = Command::new("MyApp")
let cmd = Command::new("MyApp")
.version("1.0")
.author("Kevin K. <kbknapp@gmail.com>")
.about("Does awesome things")
.help_template("test no tag test");
assert!(utils::compare_output(
app,
cmd,
"MyApp --help",
"test no tag test\n",
false
@ -114,13 +114,13 @@ fn template_notag() {
#[test]
fn template_unknowntag() {
let app = Command::new("MyApp")
let cmd = Command::new("MyApp")
.version("1.0")
.author("Kevin K. <kbknapp@gmail.com>")
.about("Does awesome things")
.help_template("test {unknown_tag} test");
assert!(utils::compare_output(
app,
cmd,
"MyApp --help",
"test {unknown_tag} test\n",
false
@ -129,13 +129,13 @@ fn template_unknowntag() {
#[test]
fn template_author_version() {
let app = Command::new("MyApp")
let cmd = Command::new("MyApp")
.version("1.0")
.author("Kevin K. <kbknapp@gmail.com>")
.about("Does awesome things")
.help_template("{author}\n{version}\n{about}\n{bin}");
assert!(utils::compare_output(
app,
cmd,
"MyApp --help",
"Kevin K. <kbknapp@gmail.com>\n1.0\nDoes awesome things\nMyApp\n",
false

View file

@ -397,14 +397,14 @@ fn sc_short_flag_x2_long_opt_eq_pos() {
#[test]
fn mut_arg_all() {
let mut app = utils::complex_app();
let arg_names = app
let mut cmd = utils::complex_app();
let arg_names = cmd
.get_arguments()
.map(|a| a.get_id())
.filter(|a| *a != "version" && *a != "help")
.collect::<Vec<_>>();
for arg_name in arg_names {
app = app.mut_arg(arg_name, |arg| arg.hide_possible_values(true));
cmd = cmd.mut_arg(arg_name, |arg| arg.hide_possible_values(true));
}
}

View file

@ -15,7 +15,7 @@ fn both_validator_and_validator_os() {
.map_err(|e| e.to_string())
}),
)
.try_get_matches_from(&["app", "1"]);
.try_get_matches_from(&["cmd", "1"]);
}
#[test]
@ -24,7 +24,7 @@ fn test_validator_fromstr_trait() {
let matches = Command::new("test")
.arg(Arg::new("from_str").validator(u32::from_str))
.try_get_matches_from(&["app", "1234"])
.try_get_matches_from(&["cmd", "1234"])
.expect("match failed");
assert_eq!(matches.value_of_t::<u32>("from_str").ok(), Some(1234));
@ -34,7 +34,7 @@ fn test_validator_fromstr_trait() {
fn test_validator_msg_newline() {
let res = Command::new("test")
.arg(Arg::new("test").validator(|val| val.parse::<u32>().map_err(|e| e.to_string())))
.try_get_matches_from(&["app", "f"]);
.try_get_matches_from(&["cmd", "f"]);
assert!(res.is_err());
let err = res.unwrap_err();
@ -59,7 +59,7 @@ fn stateful_validator() {
state = true;
val.parse::<u32>().map_err(|e| e.to_string())
}))
.try_get_matches_from(&["app", "10"])
.try_get_matches_from(&["cmd", "10"])
.unwrap();
assert!(state);

View file

@ -156,12 +156,12 @@ OPTIONS:
#[test]
fn version_about_multi_subcmd() {
let app = with_subcommand()
let cmd = with_subcommand()
.mut_arg("version", |a| a.help("Print custom version about text"))
.propagate_version(true);
assert!(utils::compare_output(
app,
cmd,
"foo bar baz -h",
VERSION_ABOUT_MULTI_SC,
false

View file

@ -3,95 +3,95 @@ use clap::Parser;
#[test]
fn app_name_in_short_help_from_struct() {
#[derive(Parser)]
#[clap(name = "my-app")]
#[clap(name = "my-cmd")]
struct MyApp {}
let mut help = Vec::new();
MyApp::into_app().write_help(&mut help).unwrap();
let help = String::from_utf8(help).unwrap();
assert!(help.contains("my-app"));
assert!(help.contains("my-cmd"));
}
#[test]
fn app_name_in_long_help_from_struct() {
#[derive(Parser)]
#[clap(name = "my-app")]
#[clap(name = "my-cmd")]
struct MyApp {}
let mut help = Vec::new();
MyApp::into_app().write_long_help(&mut help).unwrap();
let help = String::from_utf8(help).unwrap();
assert!(help.contains("my-app"));
assert!(help.contains("my-cmd"));
}
#[test]
fn app_name_in_short_help_from_enum() {
#[derive(Parser)]
#[clap(name = "my-app")]
#[clap(name = "my-cmd")]
enum MyApp {}
let mut help = Vec::new();
MyApp::into_app().write_help(&mut help).unwrap();
let help = String::from_utf8(help).unwrap();
assert!(help.contains("my-app"));
assert!(help.contains("my-cmd"));
}
#[test]
fn app_name_in_long_help_from_enum() {
#[derive(Parser)]
#[clap(name = "my-app")]
#[clap(name = "my-cmd")]
enum MyApp {}
let mut help = Vec::new();
MyApp::into_app().write_long_help(&mut help).unwrap();
let help = String::from_utf8(help).unwrap();
assert!(help.contains("my-app"));
assert!(help.contains("my-cmd"));
}
#[test]
fn app_name_in_short_version_from_struct() {
#[derive(Parser)]
#[clap(name = "my-app")]
#[clap(name = "my-cmd")]
struct MyApp {}
let version = MyApp::into_app().render_version();
assert!(version.contains("my-app"));
assert!(version.contains("my-cmd"));
}
#[test]
fn app_name_in_long_version_from_struct() {
#[derive(Parser)]
#[clap(name = "my-app")]
#[clap(name = "my-cmd")]
struct MyApp {}
let version = MyApp::into_app().render_long_version();
assert!(version.contains("my-app"));
assert!(version.contains("my-cmd"));
}
#[test]
fn app_name_in_short_version_from_enum() {
#[derive(Parser)]
#[clap(name = "my-app")]
#[clap(name = "my-cmd")]
enum MyApp {}
let version = MyApp::into_app().render_version();
assert!(version.contains("my-app"));
assert!(version.contains("my-cmd"));
}
#[test]
fn app_name_in_long_version_from_enum() {
#[derive(Parser)]
#[clap(name = "my-app")]
#[clap(name = "my-cmd")]
enum MyApp {}
let version = MyApp::into_app().render_long_version();
assert!(version.contains("my-app"));
assert!(version.contains("my-cmd"));
}

View file

@ -232,9 +232,9 @@ fn doc_comment_about_handles_both_abouts() {
Compress { output: String },
}
let app = Opts::into_app();
assert_eq!(app.get_about(), Some("Opts doc comment summary"));
let cmd = Opts::into_app();
assert_eq!(cmd.get_about(), Some("Opts doc comment summary"));
// clap will fallback to `about` on `None`. The main care about is not providing a `Sub` doc
// comment.
assert_eq!(app.get_long_about(), None);
assert_eq!(cmd.get_long_about(), None);
}

View file

@ -12,15 +12,15 @@ fn arg_help_heading_applied() {
no_section: u32,
}
let app = CliOptions::into_app();
let cmd = CliOptions::into_app();
let should_be_in_section_a = app
let should_be_in_section_a = cmd
.get_arguments()
.find(|a| a.get_id() == "should-be-in-section-a")
.unwrap();
assert_eq!(should_be_in_section_a.get_help_heading(), Some("HEADING A"));
let should_be_in_section_b = app
let should_be_in_section_b = cmd
.get_arguments()
.find(|a| a.get_id() == "no-section")
.unwrap();
@ -40,15 +40,15 @@ fn app_help_heading_applied() {
should_be_in_default_section: u32,
}
let app = CliOptions::into_app();
let cmd = CliOptions::into_app();
let should_be_in_section_a = app
let should_be_in_section_a = cmd
.get_arguments()
.find(|a| a.get_id() == "should-be-in-section-a")
.unwrap();
assert_eq!(should_be_in_section_a.get_help_heading(), Some("HEADING A"));
let should_be_in_default_section = app
let should_be_in_default_section = cmd
.get_arguments()
.find(|a| a.get_id() == "should-be-in-default-section")
.unwrap();
@ -117,27 +117,27 @@ fn app_help_heading_flattened() {
SubCOne { should_be_in_sub_c: u32 },
}
let app = CliOptions::into_app();
let cmd = CliOptions::into_app();
let should_be_in_section_a = app
let should_be_in_section_a = cmd
.get_arguments()
.find(|a| a.get_id() == "should-be-in-section-a")
.unwrap();
assert_eq!(should_be_in_section_a.get_help_heading(), Some("HEADING A"));
let should_be_in_section_b = app
let should_be_in_section_b = cmd
.get_arguments()
.find(|a| a.get_id() == "should-be-in-section-b")
.unwrap();
assert_eq!(should_be_in_section_b.get_help_heading(), Some("HEADING B"));
let should_be_in_default_section = app
let should_be_in_default_section = cmd
.get_arguments()
.find(|a| a.get_id() == "should-be-in-default-section")
.unwrap();
assert_eq!(should_be_in_default_section.get_help_heading(), None);
let sub_a_two = app.find_subcommand("sub-a-two").unwrap();
let sub_a_two = cmd.find_subcommand("sub-a-two").unwrap();
let should_be_in_sub_a = sub_a_two
.get_arguments()
@ -145,7 +145,7 @@ fn app_help_heading_flattened() {
.unwrap();
assert_eq!(should_be_in_sub_a.get_help_heading(), Some("SUB A"));
let sub_b_one = app.find_subcommand("sub-b-one").unwrap();
let sub_b_one = cmd.find_subcommand("sub-b-one").unwrap();
let should_be_in_sub_b = sub_b_one
.get_arguments()
@ -153,7 +153,7 @@ fn app_help_heading_flattened() {
.unwrap();
assert_eq!(should_be_in_sub_b.get_help_heading(), Some("SUB B"));
let sub_c = app.find_subcommand("sub-c").unwrap();
let sub_c = cmd.find_subcommand("sub-c").unwrap();
let sub_c_one = sub_c.find_subcommand("sub-c-one").unwrap();
let should_be_in_sub_c = sub_c_one
@ -178,9 +178,9 @@ fn flatten_field_with_help_heading() {
should_be_in_section_a: u32,
}
let app = CliOptions::into_app();
let cmd = CliOptions::into_app();
let should_be_in_section_a = app
let should_be_in_section_a = cmd
.get_arguments()
.find(|a| a.get_id() == "should-be-in-section-a")
.unwrap();
@ -278,10 +278,10 @@ OPTIONS:
}
use clap::IntoApp;
let mut app = Args::into_app();
let mut cmd = Args::into_app();
let mut buffer: Vec<u8> = Default::default();
app.write_help(&mut buffer).unwrap();
cmd.write_help(&mut buffer).unwrap();
let help = String::from_utf8(buffer).unwrap();
assert_eq!(help, HELP);
}
@ -335,10 +335,10 @@ OPTIONS:
}
use clap::IntoApp;
let mut app = Args::into_app();
let mut cmd = Args::into_app();
let mut buffer: Vec<u8> = Default::default();
app.write_help(&mut buffer).unwrap();
cmd.write_help(&mut buffer).unwrap();
let help = String::from_utf8(buffer).unwrap();
assert_eq!(help, HELP);
}
@ -391,10 +391,10 @@ OPTIONS:
}
use clap::IntoApp;
let mut app = Args::into_app();
let mut cmd = Args::into_app();
let mut buffer: Vec<u8> = Default::default();
app.write_help(&mut buffer).unwrap();
cmd.write_help(&mut buffer).unwrap();
let help = String::from_utf8(buffer).unwrap();
assert_eq!(help, HELP);
}

View file

@ -39,7 +39,7 @@ fn basic() {
#[test]
fn quoted_app_name() {
#![allow(deprecated)]
let mut app = clap::clap_app!(("app name with spaces-and-hyphens") =>
let mut cmd = clap::clap_app!(("cmd name with spaces-and-hyphens") =>
(version: "0.1")
(about: "tests clap library")
(author: "Kevin K. <kbknapp@gmail.com>")
@ -69,19 +69,19 @@ fn quoted_app_name() {
(@arg scpositional: index(1) "tests positionals"))
);
assert_eq!(app.get_name(), "app name with spaces-and-hyphens");
assert_eq!(cmd.get_name(), "cmd name with spaces-and-hyphens");
let mut help_text = vec![];
app.write_help(&mut help_text)
cmd.write_help(&mut help_text)
.expect("Could not write help text.");
let help_text = String::from_utf8(help_text).expect("Help text is not valid utf-8");
assert!(help_text.starts_with("app name with spaces-and-hyphens 0.1\n"));
assert!(help_text.starts_with("cmd name with spaces-and-hyphens 0.1\n"));
}
#[test]
fn quoted_arg_long_name() {
#![allow(deprecated)]
let app = clap::clap_app!(claptests =>
let cmd = clap::clap_app!(claptests =>
(version: "0.1")
(about: "tests clap library")
(author: "Kevin K. <kbknapp@gmail.com>")
@ -111,7 +111,7 @@ fn quoted_arg_long_name() {
(@arg scpositional: index(1) "tests positionals"))
);
let matches = app
let matches = cmd
.try_get_matches_from(vec!["bin_name", "value1", "value2", "--long-option-2"])
.expect("Expected to successfully match the given args.");
assert!(matches.is_present("option2"));
@ -120,7 +120,7 @@ fn quoted_arg_long_name() {
#[test]
fn quoted_arg_name() {
#![allow(deprecated)]
let app = clap::clap_app!(claptests =>
let cmd = clap::clap_app!(claptests =>
(version: "0.1")
(about: "tests clap library")
(author: "Kevin K. <kbknapp@gmail.com>")
@ -150,7 +150,7 @@ fn quoted_arg_name() {
(@arg scpositional: index(1) "tests positionals"))
);
let matches = app
let matches = cmd
.try_get_matches_from(vec!["bin_name", "value1", "value2", "--long-option-2"])
.expect("Expected to successfully match the given args.");
assert!(matches.is_present("option2"));
@ -159,7 +159,7 @@ fn quoted_arg_name() {
#[test]
fn group_macro() {
#![allow(deprecated)]
let app = clap::clap_app!(claptests =>
let cmd = clap::clap_app!(claptests =>
(version: "0.1")
(about: "tests clap library")
(author: "Kevin K. <kbknapp@gmail.com>")
@ -170,7 +170,7 @@ fn group_macro() {
)
);
let result = app.try_get_matches_from(vec!["bin_name", "--hard"]);
let result = cmd.try_get_matches_from(vec!["bin_name", "--hard"]);
assert!(result.is_ok());
let matches = result.expect("Expected to successfully match the given args.");
assert!(matches.is_present("difficulty"));
@ -180,7 +180,7 @@ fn group_macro() {
#[test]
fn group_macro_set_multiple() {
#![allow(deprecated)]
let app = clap::clap_app!(claptests =>
let cmd = clap::clap_app!(claptests =>
(version: "0.1")
(about: "tests clap library")
(author: "Kevin K. <kbknapp@gmail.com>")
@ -191,7 +191,7 @@ fn group_macro_set_multiple() {
)
);
let result = app.try_get_matches_from(vec!["bin_name", "--hard", "--easy"]);
let result = cmd.try_get_matches_from(vec!["bin_name", "--hard", "--easy"]);
assert!(result.is_ok());
let matches = result.expect("Expected to successfully match the given args.");
assert!(matches.is_present("difficulty"));
@ -203,7 +203,7 @@ fn group_macro_set_multiple() {
#[test]
fn group_macro_set_not_multiple() {
#![allow(deprecated)]
let app = clap::clap_app!(claptests =>
let cmd = clap::clap_app!(claptests =>
(version: "0.1")
(about: "tests clap library")
(author: "Kevin K. <kbknapp@gmail.com>")
@ -214,7 +214,7 @@ fn group_macro_set_not_multiple() {
)
);
let result = app.try_get_matches_from(vec!["bin_name", "--hard", "--easy"]);
let result = cmd.try_get_matches_from(vec!["bin_name", "--hard", "--easy"]);
assert!(result.is_err());
let err = result.unwrap_err();
assert_eq!(err.kind(), ErrorKind::ArgumentConflict);
@ -223,7 +223,7 @@ fn group_macro_set_not_multiple() {
#[test]
fn group_macro_set_required() {
#![allow(deprecated)]
let app = clap::clap_app!(claptests =>
let cmd = clap::clap_app!(claptests =>
(version: "0.1")
(about: "tests clap library")
(author: "Kevin K. <kbknapp@gmail.com>")
@ -234,7 +234,7 @@ fn group_macro_set_required() {
)
);
let result = app.try_get_matches_from(vec!["bin_name"]);
let result = cmd.try_get_matches_from(vec!["bin_name"]);
assert!(result.is_err());
let err = result.unwrap_err();
assert_eq!(err.kind(), ErrorKind::MissingRequiredArgument);
@ -243,7 +243,7 @@ fn group_macro_set_required() {
#[test]
fn group_macro_set_not_required() {
#![allow(deprecated)]
let app = clap::clap_app!(claptests =>
let cmd = clap::clap_app!(claptests =>
(version: "0.1")
(about: "tests clap library")
(author: "Kevin K. <kbknapp@gmail.com>")
@ -254,7 +254,7 @@ fn group_macro_set_not_required() {
)
);
let result = app.try_get_matches_from(vec!["bin_name"]);
let result = cmd.try_get_matches_from(vec!["bin_name"]);
assert!(result.is_ok());
let matches = result.expect("Expected to successfully match the given args.");
assert!(!matches.is_present("difficulty"));
@ -263,7 +263,7 @@ fn group_macro_set_not_required() {
#[test]
fn multiarg() {
#![allow(deprecated)]
let app = clap::clap_app!(claptests =>
let cmd = clap::clap_app!(claptests =>
(@arg flag: --flag "value")
(@arg multiarg: --multiarg
default_value("flag-unset") default_value_if("flag", None, Some("flag-set"))
@ -273,7 +273,7 @@ fn multiarg() {
"multiarg2")
);
let matches = app
let matches = cmd
.clone()
.try_get_matches_from(vec!["bin_name"])
.expect("match failed");
@ -281,7 +281,7 @@ fn multiarg() {
assert_eq!(matches.value_of("multiarg"), Some("flag-unset"));
assert_eq!(matches.value_of("multiarg2"), Some("flag-unset"));
let matches = app
let matches = cmd
.try_get_matches_from(vec!["bin_name", "--flag"])
.expect("match failed");

View file

@ -4,7 +4,7 @@
use clap::{load_yaml, Command};
#[test]
fn create_app_from_yaml() {
fn create_cmd_from_yaml() {
let yml = load_yaml!("app.yml");
Command::from_yaml(yml);
}
@ -12,12 +12,12 @@ fn create_app_from_yaml() {
#[test]
fn help_message() {
let yml = load_yaml!("app.yml");
let mut app = Command::from_yaml(yml);
let mut cmd = Command::from_yaml(yml);
// Generate the full help message!
let _ = app.get_matches_from_safe_borrow(Vec::<String>::new());
let _ = cmd.get_matches_from_safe_borrow(Vec::<String>::new());
let mut help_buffer = Vec::new();
app.write_help(&mut help_buffer).unwrap();
cmd.write_help(&mut help_buffer).unwrap();
let help_string = String::from_utf8(help_buffer).unwrap();
println!("{}", &help_string);
assert!(help_string.contains("tests positionals with exclusions\n"));
@ -26,12 +26,12 @@ fn help_message() {
#[test]
fn author() {
let yml = load_yaml!("app.yml");
let mut app = Command::from_yaml(yml);
let mut cmd = Command::from_yaml(yml);
// Generate the full help message!
let _ = app.get_matches_from_safe_borrow(Vec::<String>::new());
let _ = cmd.get_matches_from_safe_borrow(Vec::<String>::new());
let mut help_buffer = Vec::new();
app.write_help(&mut help_buffer).unwrap();
cmd.write_help(&mut help_buffer).unwrap();
let help_string = String::from_utf8(help_buffer).unwrap();
println!("{}", &help_string);
assert!(help_string.contains("Kevin K. <kbknapp@gmail.com>"));