我正在尝试使用一个 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>,
}
基本上,结构
types
和FolderOpts
的字段FileOpts
是有问题的。
运行时错误是:
... 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"]
?
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",
],
}