-
I am trying to use as the default value a file located within home: let home_dir = dirs::home_dir()?
let config_file = home_dir.join(".config").join("s3m").join("config.yml"); I want to use it as the default value for the config, for example: .arg(
Arg::new("config")
.default_value(config_file)
.long("config")
.num_args(1)
.short('c')
.value_parser(validator_is_file())
.value_name("config.yml")
) But when trying to build I get:
I also tried
Any ideas about how to set the default value to an existing path/Pathbuf? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 4 replies
-
|
Beta Was this translation helpful? Give feedback.
-
The problem that I had is that my validator was not returning Pathbuf, this fixed: pub fn validator_is_file() -> ValueParser {
ValueParser::from(move |s: &str| -> std::result::Result<PathBuf, String> {
if fs::metadata(s).map_err(|e| e.to_string())?.is_file() {
Ok(PathBuf::from(s))
} else {
Err(format!("Cannot read the file: {}", s))
}
})
} And using the Arg like this:
Then to get the let config_file: PathBuf = matches
.get_one::<PathBuf>("config")
.map(|c| c.into())
.unwrap_or_else(|| {
eprintln!("no config file found");
exit(1);
}); Is there any room to make it cleaner or best practices to follow? |
Beta Was this translation helpful? Give feedback.
Wow, github mobile made this hard to follow and respond to the correct thing.
Overall, I've taken the approach that the builder API is the lower level, more complex API. Without a custom value parser (using just built-ins), you automatically get alignment between the
value_parser
and theget_one
calls. With a custom value parser, there can be mistakes like this. Using something like clio'sOsStrParser
can help.So with that background, there are likely things we can improve.