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

It is easy to specify mutually exclusive optparse-applicative options:

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

The parser above will parse either -e1 or -e1 , but not both. The default optparse applicative action, when -e1 and -e1 provided, is to print a message about using the application. I would like to provide the user with a special error message telling them that they cannot provide both -e1 and -e2 , but I do not see an obvious way to do this.

Any suggestions (or solutions) will be appreciated?

+6
source share
1 answer

I am not familiar with optparse-applyative, so I'm not sure what error printing tool it provides. (Sometimes parser combiner libraries offer a primitive that changes the printed error, but I did not see anything for this in the quick part of the document using optparse. It is possible that I skipped it.)

But in the event that nothing is available from the library itself, you can always print your own message by accepting both flags; eg.

 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., after all the parameters have been parsed), if you see Both , you can issue an error message about your own creation at this time.

+2
source

Source: https://habr.com/ru/post/987160/


All Articles