argh icon indicating copy to clipboard operation
argh copied to clipboard

Feature Request: choices

Open bbstilson opened this issue 2 years ago • 5 comments

Similar to the click arg parse library from Python, it would be nice if argh had a similar feature. I am new to rust, so I can't suggest a good interface, but perhaps something like:

#[derive(FromArgs, Debug)]
struct Args {
    #[argh(choice, choices = vec!["foo", "bar", "baz"])]
    thing_type: String
}

but an enum might be a better option:

#[derive(Debug)]
enum Choice {
    Foo, Bar, Baz
}

#[derive(FromArgs, Debug)]
struct Args {
    #[argh(choice, choices = Choice)]
    thing_type: Choice
}

Perhaps this is possible already, but I couldn't figure out how to do so given the example and readme. Happy to close this if it is already possible.

Thanks!

bbstilson avatar Aug 01 '22 01:08 bbstilson

Yeah this would be interesting. We don’t have a built in way to do this at the moment, but you could use a helper function to do it. See this test for an example: https://github.com/google/argh/blob/master/argh/tests/lib.rs#L67. You’d just have to manually parse the argument into your enum.

erickt avatar Oct 12 '22 05:10 erickt

My preference for this would be another proc macro to annotate enums with, similar to how sub-commands are defined, except that these enums would not be allowed to have any data associated. Clap has this feature and calls it ValueEnum:

https://docs.rs/clap/latest/clap/trait.ValueEnum.html

athre0z avatar Dec 20 '22 17:12 athre0z

@bbstilson this is definitely possible with current argh. The intended way you're supposed to do this is by defining an enum with your "choices" then implementing FromStr on it. If your String input is only supposed to represent a finite number of values you should re-think storing it as a String, that's what enum was created for.

Good Luck!

grantshandy avatar Feb 23 '23 19:02 grantshandy

This would be very nice for ergonomics. It would also mean that --help could include accepted values for the argument.

thcrt avatar Dec 16 '23 22:12 thcrt

Yeah. Currently, setting up an enum with FromStr leads to invalid choice-inputs producing very unhelpful error messages like this one:

Error parsing option '-f' with value 'bbq': 

Run trace-cli.exe --help for more information.

...where the help menu then fails to actually provide any more information, so the message is just leading the users on a wild goose chase. Thus, for now, I'm taking in string input and running parsing-into-enum on it later, within the function-that-uses-that-arg, with a manually-specified helpful error message. But, if more properly supported enum-choices-input were enabled, that'd be very nice as an upgrade over that sort of manual handling.

twilight-flower avatar Feb 02 '24 14:02 twilight-flower