最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

rust - Dependent optional arguments with clap - Stack Overflow

programmeradmin4浏览0评论

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

发布评论

评论列表(0)

  1. 暂无评论