如何根据structopt中另一个参数的存在使参数可选?

kmp*_*kmp 4 rust structopt

我有一个命令行工具,有两个可能的参数:

  • --version (将打印出版本号并退出)
  • --out (这是输入魔法的输出文件的路径).

如果用户通过--version我不关心,--out因为我打印版本,我已经完成,如果他们没有通过--version我想要--out被要求.

这就是我所拥有的,但我想知道是否有任何方法只使用structopt?

看起来我可能最终需要将所有参数都设为可选,并且自己进行所有验证......

#![feature(custom_attribute)]
#[macro_use]
extern crate structopt;

use structopt::StructOpt;
use std::path::PathBuf;

#[derive(Debug, StructOpt)]
#[structopt(name = "structopt_playing", about = "Just playing")]
struct Opt {
    #[structopt(short = "v", long = "version")]
    version: bool,

    #[structopt(short = "o", long = "out", parse(from_os_str))]
    output_file: Option<PathBuf>,
}

const VERSION: &'static str = env!("CARGO_PKG_VERSION");

fn main() {

    let opt = Opt::from_args();
    if opt.version {
        println!("Version: {}", VERSION);
        return;
    }

    if !opt.output_file.is_some() {
        println!("Oh, now I feel like I'm alone...you need to pass --out");
        return;
    }

    println!("Now I'm going to need to do something with {:?}", 
        opt.output_file.unwrap());
}
Run Code Online (Sandbox Code Playgroud)

She*_*ter 9

用途required_unless:

#[derive(Debug, StructOpt)]
#[structopt(name = "structopt_playing", about = "Just playing")]
struct Opt {
    #[structopt(short = "v", long = "version")]
    version: bool,

    #[structopt(short = "o", long = "out", parse(from_os_str), required_unless = "version")]
    //                                                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^
    output_file: Option<PathBuf>,
}
Run Code Online (Sandbox Code Playgroud)
$ ./target/debug/stropt
error: The following required arguments were not provided:
    --out <output_file>

USAGE:
    stropt --out <output_file>

For more information try --help

$ ./target/debug/stropt --out hello
Now I'm going to need to do something with "hello"

$ ./target/debug/stropt --version
Version: 0.1.0
Run Code Online (Sandbox Code Playgroud)

Clap提供了大量相关配置选项:

  • required_unless
  • required_unless_all
  • required_unless_one
  • conflicts_with
  • conflicts_with_all
  • requires
  • requires_if
  • requires_ifs
  • required_if
  • required_ifs
  • requires_all

附注:您根本不需要#![feature(custom_attribute)]在此代码中使用.