I have already a commands enum
. I want to add optional arguments which would apply to all subcommands, if set.
use clap::Parser;
use clap::{ValueEnum, Subcommand};
#[derive(Subcommand)]
pub enum Command {
Add,
Remove,
Edit,
List,
}
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum)]
pub enum Datasources {
SqlLite,
Memory,
}
#[derive(Parser)]
#[command(version, about = "my cli", long_about = None)]
pub struct CLI {
#[command(subcommand)]
pub command: Command,
#[arg(value_enum)]
#[clap(group = "ds")]
pub datasource: Option<Datasources>,
#[arg(short,long, num_args(0..))]
#[clap(group = "ds")]
pub path: String,
}
fn main() {
let cli = CLI::parse();
let ds = match cli.datasource {
None => Datasources::SqlLite,
Some(ds) => ds,
};
}
The SqlLite
datasource would have a default path value, say $HOME/my_db.sql
. But, the user could set it to something different if they want.
In short, you can run the CLI with no options, and it would choose SqlLite
per default. If SqlLite
is used, you can optionally provide a path, or it takes the default one.
I have struggled to find the solution to this. The above requires the path
option to be set, but that's not what I want. The group
attribute seems to have no effect, but I am pretty sure I am using that wrong.
Playground