我正在尝试在 Clap 的帮助下用 Rust 编写一个 CLI。我的命令有 2 个参数,我想只指定一个或另一个,例如:
command --command_a
或 command --command_b
#[derive(Debug, clap::Args)]
#[clap(name = "command")]
pub struct MyCommand {
/// Argument1.
#[clap(long, short)]
command_a: String,
/// Argument2.
#[clap(long, short)]
command_b: String,
/// other optional events.
#[clap(name = "others", long)]
other_commands: Option<String>,
}
我可以通过添加
command_a: Option<String>
将两者设为可选,然后在代码中检查是否至少提供了一个,但我可以使用 Clap 来做到这一点吗?
ArgGroup
。要使用派生宏执行此操作,请创建一个结构体 Group
并将其存储在 MyCommand
中,并将其定义为必需但不允许多个值的组:
#[derive(Debug, clap::Args)]
#[clap(name = "command")]
pub struct MyCommand {
#[clap(flatten)]
group: Group,
#[clap(name = "others", long)]
other_commands: Option<String>,
}
#[derive(Debug, clap::Args)]
#[group(required = true, multiple = false)]
pub struct Group {
/// Argument1.
#[clap(short, long)]
command_a: Option<String>,
/// Argument2.
#[clap(short, long)]
command_b: Option<String>,
}