Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rust clap re-use same arguments in different subcommand

Tags:

rust

clap

Rust Noob here :) using rust clap 3.2.23

I have to 2 subcommands:

  1. generate (This is responsible for generating item based on input parameters & storing in a backend DB)
#[derive(Args, Debug)]
#[clap(group(ArgGroup::new("qwerty").required(true).multiple(true)))]
pub struct GenerateArgs {
    
    #[clap(group = "abc", long = "id", value_name = "ID")]
    id: Option<i64>,

 
    #[clap(group = "abc", long = "regex", value_name = "REGEX")]
    regex: Option<String>,

    #[clap(
        group = "abc",
        long = "start-time",
        required = true,
        value_name = "STARTTIME",
    )]
    start_time: Option<i64>,

    #[clap(
        group = "abc",
        long = "end-time",
        value_name = "ENDTIME",
        required = true,
    )]
    end_time: Option<i64>,

}
  1. run (This is responsible for executing stored in DB using params provided as argument)
#[derive(Args, Debug)]
#[clap(group(ArgGroup::new("qwerty").required(true).multiple(true)))]
pub struct RunArgs {
    
    #[clap(group = "abc", long = "run-id", value_name = "RUNID")]
    run_id: Option<i64>,

 
    #[clap(group = "abc", long = "retry", value_name = "RETRY")]
    retry: Option<i64>,

    #[clap(
        group = "abc",
        long = "delay",
        value_name = "DELAY",
    )]
    delay: Option<i64>,

}

I want to overload the behavior of the run subcommand so that in addition to its own parameters, it can accept the same parameters of the generate sub-command. If the params of generate sub-command are provided by users to the run subcommand, the system would first generate item, store in DB & then execute the item. Therefore the user can generate & run in a single command as opposed to two different commands if they should choose to do so.

Do I need to redefine all the parameters supported by generate subcommand in run subcommand? or is there a way to re-use the parameters? Re-using would help so that I don't need to maintain changes across the two subcommands.

like image 879
alwaysAStudent Avatar asked Aug 25 '26 11:08

alwaysAStudent


1 Answers

You should be able to do this by adding a GenerateArgs field to RunArgs, decorated with #[command(flatten)]:

pub struct RunArgs {
    #[command(flatten)]
    generate_args: GenerateArgs,

    // ...
}

This assumes that GenerateArgs derives clap::Args.

like image 121
cdhowie Avatar answered Aug 28 '26 01:08

cdhowie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!