Search code examples
rustcommand-line-interfaceclap

How can I make multiple subcommands that do the same thing


#[derive(Parser)]
struct Cli {
    #[clap(subcommand)]
    subcommand: Subcommand,
}


#[derive(clap::Subcommand)]
enum Subcommand {
    Index {
        #[clap(parse(from_os_str))]
        path: path::PathBuf,
    },
    Show {
        item: Option<String>,
    },
    Cd {
        term: String,
    },
    List,
    Init {
        shell: InitShell,
    },
    Search {
        term: Option<String>,
    },
    Add {
        category: String,
        title: String,
    },
}

fn main(){
    let cli = Cli::parse();

    match cli.subcommand{
        Subcommand::Index=>{/*code here*/}
        Subcommand::Show=>{/*and here*/}
        Subcommand::Display=>{/*and also here*/}
        Subcommand::Cd=>{}
        Subcommand::List=>{}
    // ... more matches
    }
}

When I run my program with --help, the subcommands section looks like this:

SUBCOMMANDS:
    add
    cd
    help
    index
    init
    list
    search
    show

I would like to define some aliases, such as ls for list or display for show, so that the help looks something like this:

SUBCOMMANDS:
    add
    cd, path
    help
    index
    init
    list, ls
    search
    show, display

I can see that cargo does something like this, with cargo build equal to cargo b.

I looked at the clap documentation and was able to find an alias function for the builder api, but I could not find how to do this with the derive api. Is is this possible, and if so, how can I do it?


Solution

  • The Clap derive docs say (under Possible Value Attributes):

    Possible Value Attributes

    These correspond to a [PossibleValue][crate::PossibleValue].

    Raw attributes: Any [PossibleValue method][crate::PossibleValue] can also be used as an attribute, see Terminology for syntax.

    • e.g. #[clap(alias("foo"))] would translate to pv.alias("foo")

    You also say you wish the aliases to show up under help. In that case, you want to use visible_alias instead:

    #[clap(visible_alias("foo"))]