1

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.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Omar Abid
  • 15,753
  • 28
  • 77
  • 108
  • stupid question but why ? – Stargateur Feb 23 '19 at 01:14
  • So you just want [`print_help`](https://docs.rs/clap/2.32.0/clap/struct.App.html#method.print_help)/[`print_long_help`](https://docs.rs/clap/2.32.0/clap/struct.App.html#method.print_long_help)? – mcarton Feb 23 '19 at 01:17
  • @Stargateur I need to run migrations even if the program isn't executed (otherwise the tests would not run). If you have a better idea let me know. – Omar Abid Feb 23 '19 at 09:21

1 Answers1

3

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)
            }
        }
        _ => (),
    }
}
Stargateur
  • 24,473
  • 8
  • 65
  • 91
  • I ended up rewriting my program so now I'm using the ArgsRequiredElseHelp. I hope the answer comes useful to other people though. – Omar Abid Feb 23 '19 at 21:44
  • @OmarAbid my answer was not enough for your case ? I through it was. – Stargateur Feb 24 '19 at 03:19
  • @Stragateur Your answer was enough and in fact it is a valid solution. However, looking again at the code I decided that I could do a better architecture and I ended up writing it so that it adheres to Clap instead of trying to work around it. – Omar Abid Feb 24 '19 at 17:22