Clap: how to group & require top level subcommands

Hi,

How can I emulate the git cli interface? When I simply running git, it shows all the available subcommands. At least one of the subcommand is necessary.

For example, in the below code, when I run the applications as git clone, I need to specify either opt1 or opt2, or clap throws error. But clone itself is not mandatory. Simple running git will exit without any error or help messages. How can I have clap say that simply running git without a subcommand is an error ? Basically, how can I group subcommands when they are the top level items ?

    let matches = App::new("git")
        .about("Git VCS")
        .version(crate_version!())
        .author(crate_authors!())
        .subcommand(SubCommand::with_name("clone")
                    .arg(Arg::with_name("opt1")
                         .help("Initialize the library")
                    )
                    .arg(Arg::with_name("opt2")
                         .help("Uninitialize the library")
                    )
                    .group(ArgGroup::with_name("clone_ops")
                           .args(&["opt1", "opt2"])
                           .required(true)
                    )
        )
        .get_matches();

1 Like

There's a setting to enforce requiring at least one subcommand. Is this what you need?

let matches = App::new("git")
    .setting(AppSettings::SubcommandRequiredElseHelp)
    .subcommand(...)
6 Likes

Exactly! Thank you so much!