Change the order in parsing subcommands / positional argument in Rust Clap?

150 Views Asked by At

The following code works but does not do what I want

use std::path::PathBuf;
use clap::{Args, Parser, Subcommand};

#[derive(Parser)]
#[command(author, version, about, long_about = None)]
struct Cli {

    #[command(subcommand)]
    command: Commands,

    dir: PathBuf,
}

#[derive(Subcommand)]
enum Commands {
    Add,
    Scrub,
    Check,
}

It parses the command line arguments as <DIR> <COMMAND> but I would like <COMMAND> <DIR> instead.

One option would be to do

#[derive(Args)]
struct CommandArgs {
    dir: PathBuf,
}

#[derive(Subcommand)]
enum Commands {
    Add(CommandArgs), 
    Scrub(CommandArgs),
    Check(CommandArgs),
}

But the fact that the CLI expect <COMMAND> <DIR> is totally hidden in --help. One has to put the command first to find out about the positional argument. But all my commands have a <DIR> parameter, so I would like the --help to reflect that.

How can I achieve this?

0

There are 0 best solutions below