我正在学习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
值模式匹配,但我需要将值分配给变量。
有人可以帮我这个忙,或为我指明正确的方向吗?
最佳问候
我个人认为使用match语句并将其折叠或放置在另一个函数中没什么错。但是,如果要删除它,则有很多选项。
[.default_value_if()
可以使用impl
的clap::Arg
方法,并且根据匹配的匹配臂而具有不同的默认值。