TeXitoi / structopt

Parse command line arguments by defining a struct.
Other
2.7k stars 149 forks source link

Is it possible to support a dynamically generated default_value in the macro? #523

Closed halfzebra closed 2 years ago

halfzebra commented 2 years ago

Hello, thanks for working on structopt! :raised_hands:

I'd like to have the current timestamp assigned as default_value but I haven't found an elegant solution to this.

Here's my current code:

#[derive(StructOpt, Debug)]
struct Opt {
    /// Defaults to timestamp if not provided
    #[structopt(long, default_value)]
    optional_field: u128,
}

fn main() {
    let mut opt = Opt::from_args();

    if opt.optional_field == 0 {
        opt.optional_field = Opt::default_optional_field();
    }
}

Is there a better way for doing this?

epage commented 2 years ago

structopt can't do this but clap can.

StructOpt only accepts a literal value for default_value and so it can't be set to a function call. structopt is in maintenance mode and clap3's derive feature is the "next version".

Clap has a default_value_t attribute that does accept Rust expressions and could be used to solve this. The old default_value attribute was a weird mixture of working with str and working with your native type. These concepts were split and default_value only works with pre-parsed str and we now have default_value_t which works with native types. See also the derive tutorial.

halfzebra commented 2 years ago

@epage Thanks for clarifying this!

It took me a few minutes to change the program to use clap instead. :+1: