Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
CreepySkeleton opened this issue Apr 1, 2020 · 4 comments

Comments

@CreepySkeleton
Copy link
Contributor

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 #1776

@pksunkara
Copy link
Member

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
Copy link
Contributor

TeXitoi commented Apr 1, 2020

@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
Copy link
Member

This should be covered by the hooks suggestion in #1634

@lynn
Copy link

lynn commented Apr 16, 2024

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants