我试图有一个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>,
}
基本上,结构体FolderOpts
和FileOpts
的字段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"]
?
2条答案
按热度按时间f5emj3cl1#
对于clap:3.2.8,以下工作:
您必须在派生宏中将
multiple_values
设置为true
。njthzxwz2#
对于
clap
4.0或更高版本中同一选项的多个参数,您可以使用num_args
:输出:
Playground