2

Given this Clap argument struct, I would like to allow users either to supply the config param, or any of the other params that are being flattened from the sub-structs. The connection param would then be required, but other flattened params are optional. Note that the watch param is allowed in both cases. How can this be done in Clap-derive v4+?

#[derive(Parser, Debug)]
#[command(about, version)]
pub struct Args {
    connection: Vec<String>,
    #[arg(short)]
    watch: bool,
    #[arg(short)]
    config: Option<PathBuf>,
    #[command(flatten)]
    srv: SrvArgs,
    #[command(flatten)]
    pg: PgArgs,
}

#[derive(clap::Args, Debug)]
#[command(about, version)]
pub struct SrvArgs {
    #[arg(short)]
    pub keep: Option<usize>,
}

#[derive(clap::Args, Debug)]
#[command(about, version)]
pub struct PgArgs {
    #[arg(short)]
    pub pool: Option<i32>,    
}

Allowed usages:

  • -c filename [-w]
  • [-p 10] [-k 5] [-w] connection [...connection]

I tried to do it by moving all fields except config and watch to another struct and using the #[arg(group = "cfg")] on both, but it doesn't work when the field also has the #[command(flatten)] attribute.

Yuri Astrakhan
  • 8,808
  • 6
  • 63
  • 97

0 Answers0