Is there any straightforward way for Clap to display help when no command is provided?

本小妞迷上赌 提交于 2019-12-22 04:46:15

问题


I'm using the Clap crate for parsing command line parameters. I've defined a subcommand ls that should list files. Clap also defines a help subcommand that displays information about the application and its usage.

If no command is provided, nothing gets displayed at all, but I want the app to display help in that case.

I've tried this code, which looks pretty straightforward, but it doesn't work:

extern crate clap;

use clap::{App, SubCommand};

fn main() {
    let mut app = App::new("myapp")
        .version("0.0.1")
        .about("My first CLI APP")
        .subcommand(SubCommand::with_name("ls").about("List anything"));
    let matches = app.get_matches();

    if let Some(cmd) = matches.subcommand_name() {
        match cmd {
            "ls" => println!("List something here"),
            _ => eprintln!("unknown command"),
        }
    } else {
        app.print_long_help();
    }
}

I get an error that app is used after move:

error[E0382]: use of moved value: `app`
  --> src/main.rs:18:9
   |
10 |     let matches = app.get_matches();
   |                   --- value moved here
...
18 |         app.print_long_help();
   |         ^^^ value used here after move
   |
   = note: move occurs because `app` has type `clap::App<'_, '_>`, which does not implement the `Copy` trait

Reading through the documentation of Clap, I've found that the clap::ArgMatches that's returned in get_matches() has a method usage that returns the string for usage part, but, unfortunately, only this part and nothing else.


回答1:


Use clap::AppSettings::ArgRequiredElseHelp:

App::new("myprog")
    .setting(AppSettings::ArgRequiredElseHelp)

See also:

  • Method call on clap::App moving ownership more than once


来源:https://stackoverflow.com/questions/49290526/is-there-any-straightforward-way-for-clap-to-display-help-when-no-command-is-pro

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!