Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you provide a specific error message with optparse-applicative when multiple mutually exclusive options are provided?

It's easy to specify mutually exclusive options with optparse-applicative:

data Exclusive = E1 | E2

exclusiveParser :: Parser ExclusiveOption
exclusiveParser = 
        (flag' E1 (short 'e1')
    <|> (flag' E2 (short 'e2')

The above parser will parse either -e1 or -e2, but not both. The default optparse-applicative action when both -e1 and -e2 are provided is to print the application's usage message. I would like to provide the user with a specific error message informing them that they cannot provide both -e1 and -e2, but I don't see an obvious way to do that.

Any suggestions (or solutions) would be appreciated?

like image 845
Christopher Lewis Avatar asked May 13 '15 20:05

Christopher Lewis


1 Answers

I'm not familiar with optparse-applicative, so I'm not sure what error-printing facilities it provides. (Sometimes parser combinator libraries offer a primitive that changes the error that's printed, but I didn't see anything for that on a quick skim of the optparse-applicative docs. Entirely possible that I missed it.)

But in case nothing is available from the library itself, you could always print your own message by accepting both flags; e.g.

data Exclusive = E1 | E2 | Both
exclusiveParser
     =  (flag' E1 (short 'e'))
    <|> (flag' E2 (short 'f'))
    <|> (flag' Both (short 'e') <* flag' Both (short 'f'))

Then in your top-level handler (i.e. once the options are all parsed), if you see Both, you can issue an error message of your own crafting at that moment.

like image 63
Daniel Wagner Avatar answered Sep 24 '22 22:09

Daniel Wagner