我正在尝试使用一个 CLI 工具根据一些指定的正则表达式编辑文件夹中的文件。
调试中,举个例子:
cargo run -- folder ./tests/test_files -t emails ip -r
意味着编辑文件夹路径中的所有文件 =
./tests/test_files
和 -r
意味着递归地这样做。
以下是试图实现这一目标的结构列表:
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), required = true)]
pub path: std::path::PathBuf,
/// The type of redaction to be applied to the files, e.g. -t sgNRIC emails
#[clap(short, long, required = true, multiple_values = true)]
pub types: Vec<String>,
#[clap(short, long, required = false, takes_value = false)]
pub recursive: Option<bool>,
}
这是运行时出现的错误:
Finished dev [unoptimized + debuginfo] target(s) in 45.31s
Running `target\debug\raf.exe folder ./tests/test_files -t sgNRIC email -r`
error: The argument '--recursive <RECURSIVE>' requires a value but none was supplied
For more information try --help
error: process didn't exit successfully: `target\debug\raf.exe folder ./tests/test_files -t sgNRIC email -r` (exit code: 2)
我的问题是,我该如何编写结构
FolderOpts
,如果 -r
作为参数出现在 CLI 参数中,它被解析为 .recursive
= true
,如果它不存在,.recursive
= false
?
bool
选项不需要包含在 Option
中是可选的。它们默认设置为false
,如果它们的名称作为参数传递,则设置为true
。这应该有效:
#[clap(short, long)]
pub recursive: bool,