繁体   English   中英

Rust中使用Clap时定义子命令时如何使用全局选项?

[英]How to use global option when subcommands are defined when using Clap in Rust?

所以我正在尝试创建一个带有子命令的命令行应用程序。 现在唯一的问题是在定义子命令后我似乎无法让主命令工作。

到目前为止,我所拥有的是:

use clap::{Parser, Subcommand, Args};

#[derive(Parser)]
#[command(about="Hello world")]
pub struct Cli {
    #[clap(long,short)]
    pub name: Option<String>,
    #[command(flatten)]
    pub date: DateShared,
    #[command(subcommand)]
    pub subcommands: AppSubCommands,
}

#[derive(Subcommand)]
pub enum AppSubCommands {
    #[command(about="Address info",name="address")]
    AddressCommands(Address)
}

#[derive(Args, Debug)]
pub struct Address {
    #[command(flatten)]
    pub date: DateShared,
    #[arg(long, short)]
    pub street: Option<String>,
    #[arg(long, short)]
    pub number: Option<String>

}

#[derive(Args, Debug)]
pub struct DateShared {
    #[arg(long,short)]
    pub month: Option<String>,
    #[arg(long,short)]
    pub day: Option<String>,
}

这编译得很好。 甚至当我运行 --help 它也会显示这个

     Running `target/debug/repl --help`
Hello world

Usage: repl [OPTIONS] <COMMAND>

Commands:
  address  Address info
  help     Print this message or the help of the given subcommand(s)

Options:
  -n, --name <NAME>    
  -m, --month <MONTH>  
  -d, --day <DAY>      
  -h, --help           Print help information

其中显示了全局级别可用的选项,并且有一个address子命令。

但是当我尝试使用全局选项运行时它在运行时失败了。 例如

fn main() {
    let cli = Cli::parse();
    println!("name {:?}", cli.name.unwrap());
}

失败并出现以下情况

     Running `target/debug/repl --name finlay`
error: 'repl' requires a subcommand but one was not provided
  [subcommands: address, help]

Usage: repl [OPTIONS] <COMMAND>

For more information try '--help'

但是运行子命令有效

fn main() {
    let cli = Cli::parse();
    match cli.subcommands {
        AppSubCommands::AddressCommands(address) => println!("{}", address.date.month.unwrap()),
        _ => println!("Also all good")
    }
}

我可以使用cargo run -- address --month jan ,这样子命令就可以工作了。

那么我如何让子命令工作同时还能够运行主/父命令呢?

您将命令行界面的可选部分包装在Option中,包括可选命令。

#[derive(Parser)]
#[command(about="Hello world")]
pub struct Cli {
    #[clap(long,short)]
    pub name: Option<String>,
    #[command(flatten)]
    pub date: DateShared,
    #[command(subcommand)]
    pub subcommands: Option<AppSubCommands>,
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM