你好,我正在使用 clap 构建一个 cli
我想要实现的目标很简单: 我有 2 组参数
fruits
和 vegetables
我有一个子命令 create
来创建新的水果或蔬菜
我可以有 2 个单独的命令来创建水果和蔬菜,但我更喜欢只有一个命令并传递一个参数来创建水果 (--fruit) 或蔬菜 (--vegetable)
my_cli create --fruit // will create a fruit
my_cli create --vegetable // will create a vegetable
创建水果--重量-国家需要参数 创建蔬菜 --type --destination 需要参数
如果我运行
my_cli create --fruit --type "root vegetable"
它应该会弹出一个错误,因为 --fruit 将与蔬菜组中的所有参数冲突,与 --vegetable 与水果组中的参数相同
这是我的代码
#[derive(Parser)]
#[command(author, version, about, long_about = None)]
pub struct Cli {
#[command(subcommand)]
pub command: Commands,
/// Apply command on fruit
#[arg(
short,
long,
global = true,
conflicts_with = "vegetable",
default_value = "true",
default_value_if("vegetable", "true", "false"),
display_order = 0
)]
pub fruit: bool,
/// Apply command on vegetable
#[arg(
short,
long,
global = true,
conflicts_with = "fruit",
default_value = "false",
default_value_if("fruit", "true", "false"),
display_order = 0
)]
pub vegetable: bool,
}
#[derive(Subcommand)]
pub enum Commands {
/// Create a new fruit or vegetable
Create(CreateArgs),
}
#[derive(Args, Debug)]
pub struct CreateArgs {
/// Type
#[arg(long, display_order = 1, group = "vegetable_group")]
pub type: Option<String>,
/// Destination
#[arg(long, display_order = 1, group = "vegetable_group")]
pub destination: Option<String>,
/// Weight
#[arg(long, display_order = 1, group = "fruit_group")]
pub weight: Option<String>,
/// Country
#[arg(long, display_order = 1, group = "fruit_group")]
pub country: Option<String>,
}
如何使一组参数与另一组参数发生冲突?
我可以对所有参数做这样的事情,但对于很多参数来说,这是不相关的
/// Destination
#[arg(long, display_order = 1, group = "vegetable_group", conflicts_with_all(["weight", "country"])]
pub destination: Option<String>,