Omar Abid
Omar Abid

Reputation: 15976

How can I display help after calling Clap's get_matches?

I'm having the same problem as Is there any straightforward way for Clap to display help when no command is provided?, but the solution proposed in that question is not good enough for me.

.setting(AppSettings::ArgRequiredElseHelp) stops the program if no arguments are provided, and I need the program to carry on execution even if no arguments are provided. I need the help to be displayed in addition.

Upvotes: 1

Views: 1465

Answers (1)

Stargateur
Stargateur

Reputation: 26757

You could write the string before.

use clap::{App, SubCommand};

use std::str;

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 mut help = Vec::new();
    app.write_long_help(&mut help).unwrap();

    let _ = app.get_matches();

    println!("{}", str::from_utf8(&help).unwrap());
}

Or you could use get_matches_safe

use clap::{App, AppSettings, ErrorKind, SubCommand};

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

    let matches = app.get_matches_safe();

    match matches {
        Err(e) => {
            if e.kind == ErrorKind::MissingArgumentOrSubcommand {
                println!("{}", e.message)
            }
        }
        _ => (),
    }
}

Upvotes: 3

Related Questions