使用Rust的CLAP Parser trait获取命令行参数列表

vatpfxk5  于 2023-03-30  发布在  其他
关注(0)|答案(2)|浏览(156)

我试图有一个CLI工具,根据一些指定的正则表达式编辑文件。
在调试中,例如:

cargo run -- folder ./tests/test_files -t emails ip

或者在生产中,例如:

raf folder ./tests/test_files -t emails ip

folder是一个子命令,第一个参数是folder的路径,-t--types参数应该有一个正则表达式类型列表(例如,对应于电子邮件的正则表达式,对应于IP地址的正则表达式等)。
下面是试图实现此目的的结构体列表:

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

#[derive(Debug, Parser)]
#[clap(author, version, about, name = "raf")]
pub struct Opts {
    #[clap(subcommand)]
    pub cmd: FileOrFolder,
}

#[derive(Debug, Subcommand)]
pub enum FileOrFolder {
    #[clap(name = "folder")]
    Folder(FolderOpts),
    #[clap(name = "file")]
    File(FileOpts),
}

#[derive(Args, Debug)]
pub struct FolderOpts {
    /// `path` of the directory in which all files should be redacted, e.g. ./tests/test_files
    #[clap(parse(from_os_str))]
    pub path: std::path::PathBuf,

    /// The type of redaction to be applied to the files, e.g. -t sgNRIC emails
    #[clap(short, long)]
    pub types: Vec<String>,
}

#[derive(Args, Debug)]
pub struct FileOpts {
    #[clap(parse(from_os_str))]
    pub path: std::path::PathBuf,
    #[clap(short, long)]
    pub types: Vec<String>,
}

基本上,结构体FolderOptsFileOpts的字段types是有问题的。
运行时错误为:

... raf> cargo run -- folder ./tests/test_files -t emails ip
    Finished dev [unoptimized + debuginfo] target(s) in 0.26s
     Running `target\debug\raf.exe folder ./tests/test_files -t emails ip`
error: Found argument 'ip' which wasn't expected, or isn't valid in this context

USAGE:
    raf.exe folder [OPTIONS] <PATH>

For more information try --help
error: process didn't exit successfully: `target\debug\raf.exe folder ./tests/test_files -t emails ip` (exit code: 2)

如何将-t emails, ip转换为FolderOpts.types = vec!["emails", "ip"]

f5emj3cl

f5emj3cl1#

对于clap:3.2.8,以下工作:

#[derive(Args, Debug)]
pub struct FileOpts {
    #[clap(parse(from_os_str), required=true)]
    pub path: std::path::PathBuf,
    #[clap(short, long, required=true, multiple_values=true)]
    pub types: Vec<String>,
}

您必须在派生宏中将multiple_values设置为true

njthzxwz

njthzxwz2#

对于clap 4.0或更高版本中同一选项的多个参数,您可以使用num_args

use clap::Parser;
#[derive(Debug, Parser)]
struct Opts {
    #[arg(short, long, num_args = 1..)]
    types: Vec<String>,
}

fn main() {
    let o = Opts::parse_from(["program_name", "-t", "first", "second"]);
    dbg!(o);
}

输出:

[src/main.rs:10] o = Opts {
    types: [
        "first",
        "second",
    ],
}

Playground

相关问题