Jim*_*Jim 3 command-line-interface rust clap
我正在尝试使用一个 CLI 工具来根据某些指定的正则表达式编辑文件夹中的文件。
在调试时,举个例子:
cargo run -- folder ./tests/test_files -t emails ip -r
Run Code Online (Sandbox Code Playgroud)
这意味着编辑文件夹 path = 中的所有文件,./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>,
}
Run Code Online (Sandbox Code Playgroud)
这是运行时发生的错误:
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)
Run Code Online (Sandbox Code Playgroud)
我的问题是,如何编写结构,FolderOpts以便如果-r作为 CLI 参数中的参数出现,则将其解析为.recursive= true,如果不存在,则将其解析为.recursive= false?
bool选项不需要包含在其中Option即可成为可选。如果它们的名称作为参数传递false,则它们默认设置为。true这应该有效:
#[clap(short, long)]
pub recursive: bool,
Run Code Online (Sandbox Code Playgroud)