clap-rs / clap

A full featured, fast Command Line Argument Parser for Rust
docs.rs/clap
Apache License 2.0
14.25k stars 1.04k forks source link

Is there currently a way to call a function to provide a default value (instead of a static string)? #1777

Closed CreepySkeleton closed 4 years ago

CreepySkeleton commented 4 years ago

Is there currently a way to call a function to provide a default value (instead of a static string)? This is in the context of Clap's proc_macro.

We have some resolution logic (config file, plus global configuration, plus some environment stuff) for default values, and that would be very useful.

For a concrete example, we have a --file argument for a server, which takes a filename and validates it's a valid path (user can write to it). If it's not passed in, it should be read from an environment variable. If that's not specified, it should be in a configuration file. If it's not there, it should be at the root of the project (if the user is running inside a project). All else, it should be a temporary file (using temp_file()). We could use an Option<PathBuf> and set it after arg matching, but it complicates the code using it (unwrapping everywhere). Simplest is to panic during arg parsing (e.g. if user has no right to the fs), else just be a PathBuf, from the clap code directly.

I know there is a parse argument to the proc_macro, but AFAIK it only applies if there is a value passed by the user, not for default values.

Originally posted by @hansl in https://github.com/clap-rs/clap/discussions/1776

pksunkara commented 4 years ago

What does clap need to do here? If we are talking about default values for args being provided by external stuff, we should already have an issue about this called hooks somewhere.

TeXitoi commented 4 years ago

@hansl does using a lazy static allow you to do what you want.

An example: https://github.com/CanalTP/mimirsbrunn/blob/master/libs/bragi/src/lib.rs#L67

pksunkara commented 4 years ago

This should be covered by the hooks suggestion in https://github.com/clap-rs/clap/issues/1634

lynn commented 6 months ago

You can now use #[clap(default_value_t = my_fn())] for this. Example on Rust Playground