【发布时间】:2019-10-15 06:46:54
【问题描述】:
我正在学习 rust 并尝试找到类似实用程序(是的另一个),我使用 clap 并尝试支持程序参数的命令行和配置文件(这与 clap yml 文件无关) .
我正在尝试解析命令,如果没有命令传递给应用程序,我将尝试从配置文件加载它们。 现在我不知道如何以惯用的方式做到这一点。
fn main() {
let matches = App::new("findx")
.version(crate_version!())
.author(crate_authors!())
.about("find + directory operations utility")
.arg(
Arg::with_name("paths")
...
)
.arg(
Arg::with_name("patterns")
...
)
.arg(
Arg::with_name("operation")
...
)
.get_matches();
let paths;
let patterns;
let operation;
if matches.is_present("patterns") && matches.is_present("operation") {
patterns = matches.values_of("patterns").unwrap().collect();
paths = matches.values_of("paths").unwrap_or(clap::Values<&str>{"./"}).collect(); // this doesn't work
operation = match matches.value_of("operation").unwrap() { // I dont like this
"Append" => Operation::Append,
"Prepend" => Operation::Prepend,
"Rename" => Operation::Rename,
_ => {
print!("Operation unsupported");
process::exit(1);
}
};
}else if Path::new("findx.yml").is_file(){
//TODO: try load from config file
}else{
eprintln!("Command line parameters or findx.yml file must be provided");
process::exit(1);
}
if let Err(e) = findx::run(Config {
paths: paths,
patterns: patterns,
operation: operation,
}) {
eprintln!("Application error: {}", e);
process::exit(1);
}
}
有一种惯用的方法可以将Option 和Result 类型值提取到相同的范围内,我的意思是我读过的所有示例,使用match 或if let Some(x) 来消耗x 内的值模式匹配的范围,但我需要将值分配给变量。
有人可以帮我解决这个问题,或指出正确的方向吗?
最好的问候
【问题讨论】:
-
同样的问题。我想知道如何
test这个Clap和ArgMatches。get_matches_from帮了我:docs.rs/clap/2.33.3/clap/…