Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

optparse-applicative: Require at least one argument

I'm using the optparse-applicative library in an application that takes multiple strings on the command line and performs an action on each one. My first try was this:

arguments Just
    ( metavar "EXPR"
    & help "Expressions to render, in zero-based De Bruijn index notation" )

Unfortunately, this allows running the program with no arguments, even though it doesn't make much sense.

My second attempt involved parsing the first argument separately, then consing it to the remainder of the list:

(:) <$> argument Just ( metavar "EXPR" )
    <*> arguments Just ( metavar "EXPR" )

This should have worked, but it didn't: when called with --help, the parser gobbles it up and processes it instead of displaying the help text.

So my question is: how do I configure optparse to require at least one argument?

like image 522
Lambda Fairy Avatar asked Sep 18 '12 07:09

Lambda Fairy


1 Answers

Okay – I've reported this issue to the author of the library (Paolo Capriotti). He replied:

The problem here is that arguments has some special logic to:

  • initially ignore arguments starting with '-'
  • accept '--'
  • accept arguments starting with '-' after '--' is encountered

Given this desired behavior, arguments cannot simply be implemented as many argument.

What we can do to make common use cases like the one in this Issue easier to deal with, is to add a bunch of convenience builders, like:

  • arguments1, non-empty argument list, with the same behavior as arguments
  • argument', parse 1 argument, ignoring things starting with '-'

This way, many argument' would be similar to arguments (without the special handling of --), and some argument' to arguments1.

Suggestions for better names are welcome. :)

In other words, he added a new function arguments1 to do what I described. That function has been available since version 0.5.

So now my code looks like this:

arguments1 Just
    ( metavar "EXPR"
   <> help "Expressions to render, in zero-based De Bruijn index notation" )

Thanks, Paolo!

like image 172
Lambda Fairy Avatar answered Nov 02 '22 16:11

Lambda Fairy