TeXitoi / structopt

Parse command line arguments by defining a struct.
Other
2.71k stars 150 forks source link

Handle Vec values through env variables. #475

Closed TotalKrill closed 3 years ago

TotalKrill commented 3 years ago

I recently ran into this problem where i want to provide a list of numbers through a environment variable.

    /// The starting numbers
    #[structopt(short, long, env = "START_NUMBERS", default_value = "1")]
   numbers: Vec<u16>,

This works well throught the cli interface with --numbers 1 300 400 etc. But I get an error when providing this through an environment variable such as env START_NUMBERS="1 300 400".

I totally understand this error though, because obviously the environment variable is only a string, and "1 300 400" is not very parseable as a single string( the special case being parsing it into 1300400 )

This problem is even more palpable when trying to use this with strings, because, well strings are valid with spaces or other common deliminators.

TotalKrill commented 3 years ago

While writing this, I found that clap supports use_delimiter and value_delimiter

https://docs.rs/clap/2.32.0/clap/struct.Arg.html#method.value_delimiter

And that this translates directly into the superb structopt library, so adding that to structopt works flawlessly.

    /// The starting numbers
    #[structopt(short, long, env = "START_NUMBERS", default_value = "1", value_delimiter = " ")]
   numbers: Vec<u16>,

Closing this issue, but at least someone might find it useful in the future :)

TeXitoi commented 3 years ago

Thanks for the clean report and explaining the solution.