Applicative option parser

This package contains utilities and combinators to define command line option parsers.

Continuous Integration status Hackage page (downloads and API reference)

Table of Contents

Getting started

Install with

cabal install optparse-applicative

Here is a simple example of an applicative option parser:

import Options.Applicative

data Sample = Sample
  { hello :: String
  , quiet :: Bool }

sample :: Parser Sample
sample = Sample
     <$> strOption
         ( long "hello"
        <> metavar "TARGET"
        <> help "Target for the greeting" )
     <*> switch
         ( long "quiet"
        <> help "Whether to be quiet" )

The parser is built using applicative style starting from a set of basic combinators. In this example, hello is defined as an option with a String argument, while quiet is a boolean flag (called switch).

A parser can be used like this:

greet :: Sample -> IO ()
greet (Sample h False) = putStrLn $ "Hello, " ++ h
greet _ = return ()

main :: IO ()
main = execParser opts >>= greet
  where
    opts = info (helper <*> sample)
      ( fullDesc
     <> progDesc "Print a greeting for TARGET"
     <> header "hello - a test for optparse-applicative" )

The greet function is the entry point of the program, while opts is a complete description of the program, used when generating a help text. The helper combinator takes any parser, and adds a help option to it.

The hello option in this example is mandatory (since it doesn’t have a default value), so running the program without any argument will display a short option summary:

Usage: hello --hello TARGET [--quiet]

Running the program with the --help option will display the full help text:

hello - a test for optparse-applicative

Usage: hello --hello TARGET [--quiet]
  Print a greeting for TARGET

Available options:
  -h,--help                Show this help text
  --hello TARGET           Target for the greeting
  --quiet                  Whether to be quiet

containing a detailed list of options with descriptions.

The specified metavars are used as placeholders for the option arguments, and can be referred to in the program description. This makes it possible to explicitly describe the connection between the options and the behaviour of the program.

Parsers are instances of both Applicative and Alternative, and work with any generic combinator, like many and some. For example, to make a option return Nothing instead of failing when it’s not supplied, you can use the optional combinator in Control.Applicative:

optional $ strOption
   ( long "output"
  <> metavar "DIRECTORY" )

Supported options

optparse-applicative supports four kinds of options: regular options, flags, arguments and commands.

Regular options

A regular option is an option which takes a single argument, parses it, and returns a value.

A regular option can have a default value, which is used as the result if the option is not found in the command line. An option without a default value is considered mandatory, and produces an error when not found.

Regular options can have long names, or short (one-character) names, which determine when the option matches and how the argument is extracted.

An option with a long name (say “output”) is specified on the command line as

--output filename.txt

or

--output=filename.txt

while a short name option (say “o”) can be specified with

-o filename.txt

or

-ofilename.txt

Options can have more than one name, usually one long and one short, although you are free to create options with an arbitrary combination of long and short names.

Regular options returning strings are the most common, and they can be created using the strOption builder. For example,

strOption
   ( long "output"
  <> short 'o'
  <> metavar "FILE"
  <> help "Write output to FILE" )

creates a regular option with a string argument (which can be referred to as FILE in the help text and documentation), a long name “output” and a short name “o”. See below for more information on the builder syntax and modifiers.

A regular option can return an object of any type, and takes a reader parameter which specifies how the argument should be parsed. A common reader is auto, which assumes a Read instance for the return type and uses it to parse its argument. For example:

lineCount :: Parser Int
lineCount = option auto
            ( long "lines"
           <> short 'n'
           <> metavar "K"
           <> help "Output the last K lines" )

specifies a regular option with an Int argument. We added an explicit type annotation here, since without it the parser would have been polymorphic in the output type. There’s usually no need to add type annotations, however, because the type will be normally inferred from the context in which the parser is used.

You can also create a custom reader that doesn’t use the Read typeclass, and use it to parse option arguments. A custom reader is a value in the ReadM monad.

data FluxCapacitor = ...

parseFluxCapacitor :: Monad m => String -> m FluxCapacitor

option (str >>= parseFluxCapacitor)
  ( long "flux-capacitor" )

Use readerAbort or readerError within the ReadM monad to exit with an error message.

Flags

A flag is just like a regular option, but it doesn’t take any arguments: it is either present in the command line or not.

A flag has a default value and an active value. If the flag is found on the command line, the active value is returned, otherwise the default value is used. For example:

data Verbosity = Normal | Verbose

flag Normal Verbose
  ( long "verbose"
 <> short 'v'
 <> help "Enable verbose mode" )

is a flag parser returning a Verbosity value.

Simple boolean flags can be specified using the switch builder, like so:

switch
  ( long "keep-tmp-files"
 <> help "Retain all intermediate temporary files" )

There is also a flag' builder, which has no default value. For example, to add a --version switch to a program, you could write:

flag' Nothing (long "version" <> hidden) <|> (Just <$> normal_options)

Arguments

An argument parser specifies a positional command line argument.

The argument builder takes a reader parameter, and creates a parser which will return the parsed value every time it is passed a command line argument for which the reader succeeds. For example

argument str (metavar "FILE")

creates an argument accepting any string. To accept an arbitrary number of arguments, combine the argument builder with either the many or some combinator:

some (argument str (metavar "FILES..."))

Arguments are only displayed in the brief help text, so there’s no need to attach a description to them. They should be manually documented in the program description.

Note that arguments starting with - are considered options by default, and will not be considered by an argument parser.

However, parsers always accept a special argument: --. When a -- is found on the command line, all the following words are considered by argument parsers, regardless of whether they start with - or not.

Commands

A command can be used to specify a sub-parser to be used when a certain string is encountered in the command line.

Commands are useful to implement command line programs with multiple functions, each with its own set of options, and possibly some global options that apply to all of them. Typical examples are version control systems like git, or build tools like cabal.

A command can be created using the subparser builder, and commands can be added with the command modifier. For example

subparser
  ( command "add" (info addOptions
      ( progDesc "Add a file to the repository" ))
 <> command "commit" (info commitOptions
      ( progDesc "Record changes to the repository" ))
)

Each command takes a full ParserInfo structure, which will be used to extract a description for this command when generating a help text.

Note that all the parsers appearing in a command need to have the same type. For this reason, it is often best to use a sum type which has the same structure as the command itself. For example, for the parser above, you would define a type like:

data Options = Options
  { optGlobalOpt :: String
  , optGlobalFlag :: Bool
  ...
  , optCommand :: Command }

data Command
  = Add AddOptions
  | Commit CommitOptions
  ...

Alternatively, you can directly return an IO action from a parser, and execute it using join from Control.Monad.

start :: String -> IO ()
stop :: IO ()

opts :: Parser (IO ())
opts = subparser
  ( command "start" (info (start <$> argument str idm) idm)
 <> command "stop"  (info (pure stop) idm) )

main :: IO ()
main = join $ execParser (info opts idm)

Option builders

Builders allow you to define parsers using a convenient combinator-based syntax. Each builder takes a modifier as parameter, and returns a parser.

A modifier is a composition of functions which act on the option, setting values for properties or adding features, and is used to build the option from scratch and finally lift it to a single-option parser, which can then be combined with other parsers using normal Applicative combinators.

Modifiers are instances of the Monoid typeclass, so they can be combined using the composition function mappend (or simply (<>)).

See the haddock documentation for Options.Applicative.Builder for a full list of builders and modifiers.

Advanced features

How it works

A Parser a is essentially a heterogeneous list of Options, implemented with existential types.

All options are therefore known statically (i.e. before parsing, not necessarily before runtime), and can, for example, be traversed to generate a help text.

See this blog post for a more detailed explanation based on a simplified implementation.

Changes

Version 0.11.0.2 (17 Feb 2015)

  • Updated dependency bounds.

Version 0.11.0.1 (5 Oct 2014)

  • Updated documentation.

Version 0.11.0 (4 Oct 2014)

  • Added Alternative instances for Chunk and ReadM.

  • The ReadM monad is now a ReaderT for the argument being parsed. User defined readers do not need to handle their argument explicitly, but can always access it using readerAsk.

  • Argument builders now take a ReadM parameter, just like options.

  • Fixed bugs

    • #106 - argument should perhaps use ReadM

Version 0.10.0 (1 Sep 2014)

  • Parser execution and help text generation are now more modular, and allow for greater customisation.

  • More consistent API for option and argument builders: now option takes a reader as argument, and nullOption is deprecated in favour of option. The reader modifier is gone. Quick migration guide:

    • option (without a reader modifier) => option auto
    • nullOption (without a reader modifier) => option disabled
    • option/nullOption (with a reader r modifier) => option r.
  • Added convenience builder strArgument, equivalent to argument str.

  • Removed functions deprecated from at least version 0.8.0.

  • Switched test infrastructure to tasty.

  • Fixed bugs

    • #63 - Inconsistency between ‘argument’ and ‘strOption’ types

Version 0.9.1.1 (31 Jul 2014)

  • Fixed bugs
    • #97 - Version 0.9.1 fails test suite

Version 0.9.1 (30 Jul 2014)

  • Documentation tweaks.

  • Added low-level function to handle parse results (pull request #94).

  • ParserResult now has a Show instance (see issue #95).

  • Fixed bugs

    • #93 - Formatting problem for several sub-parsers

Version 0.9.0 (23 May 2014)

  • The option returned by abortOption is now visible by default.

Version 0.8.1 (5 May 2014)

  • Fixed bugs
    • #74 - Missing newline

Version 0.8.0.1 (19 Mar 2014)

  • Fixed bugs
    • #73 - Release 0.8.0 is broken

Version 0.8.0 (16 Mar 2014)

  • Help page formatting. Added columns preference modifier, which can be used to specify the number of columns in the output terminal.

  • Deprecated arguments and arguments1 builders. Using many and some on a parser built using argument now returns a multiple argument parsers that behaves correctly with respect to --.

  • Fixed bugs

    • #60 - runParser can’t be called
    • #64 - –help behaviour

Version 0.7.0.2 (18 Oct 2013)

  • Fixed bugs
    • #51 - Build fails with ghc 6.12.3 and ghc 7.0.4

Version 0.7.0.1 (18 Oct 2013)

  • Minor docs fixes

Version 0.7.0 (17 Oct 2013)

  • Added builders for options that always fail. This makes it easier to create options that just print an error message or display some brief information and then exit (like --version).

  • Added execParserMaybe and customExecParserMaybe functions (pull request #49).

  • Fixed bugs

    • #47 - Current master prints help text instead of error
    • #48 - Can we have an eitherReader convenience function?
    • #50 - In order parsing problems.
    • #22 - Strict (no-intersperse) arguments

Version 0.6.0 (11 Oct 2013)

  • Arguments are now always parsed in order.

  • Fixed bugs

    • #40 - Add context information to error messages
    • #41 - Readme uses old reader API
    • #38 - Internal types leaking into public API
    • #44 - Can the build input restriction process == 1.1.* be relaxed?
    • #28 - Help for subcommands

Version 0.5.2.1 (24 Dic 2012)

  • Minor docs fixes.

Version 0.5.2 (23 Dic 2012)

  • Fixed compatibility with GHC 7.2.

Version 0.5.1 (23 Dic 2012)

  • There is a new parser preference noBacktrack, that controls whether how a failure in a subparser is propagated. By default, an unknown option in a subparser causes the option to be looked up in parent parsers. When noBacktrack is used, this behavior is disabled. This is useful to implement subcommands that have no relations with their parent commands.

  • Fixed bugs

    • #35 - Artifacts of “hidden”
    • #31 - Backtracking on commands
    • #25 - Allow for using Maybe in options types to specify optional arguments
    • #34 - No simple/obvious way to add a –version switch
    • #29 - Document Mod
    • #26 - Improve docs for the Arrow interface

Version 0.5.0 (22 Dic 2012)

  • Fewer GHC extensions required.

  • Improved error handling: unrecognized options now result in an error message.

  • By default, the full help text is not displayed on parse errors anymore. This behavior can be controlled with the prefShowHelpOnError field of ParserPrefs.

  • The (&) operator is now deprecated. Modifiers can still be combined using (<>) or mappend.

  • Fixed bugs

    • #37 - Use (<>) instead of (&) in documentation

Version 0.4.3 (09 Dic 2012)

  • Updated dependency bounds.

Version 0.4.2 (26 Nov 2012)

  • Fixed bugs
    • #27 - Please include the test source files in the cabal sdist tarball

Version 0.4.1 (04 Sep 2012)

  • Fixed bugs
    • #19 - Regression

Version 0.4.0 (05 Aug 2012)

  • Brief help text for nested commands now shows the full command line.

  • Fixed inefficiency in the arguments parsers for long argument lists.

  • Added automatic bash completion.

  • Added disambiguate modifier for prefs, which enabled automatic disambiguation of option abbreviations. With disambiguation on, a command line like:

      foo --out
    

    will match an option called --output, as long as its the only one starting with the string out.

  • Added briefDesc modifier.

  • Fixed bugs

    • #8 - Long options not disambiguated
    • #10 - Shell completions
    • #16 - Possible memory leak?

Version 0.3.2 (31 Jul 2012)

  • Fixed bug where both branches of an alternative could be matched.

  • Improved brief help text for alternatives.

Version 0.3.1 (30 Jul 2012)

  • Added new showDefault and showDefaultWith modifiers, which will result in the default value (if present) to be displayed in the help text.

  • Fixed bugs

    • #12 - Optionally display default values in help

Version 0.3.0 (30 Jul 2012)

  • Option modifiers are now instances of Monoid instead of Category.

  • Dropped dependencies on data-default and data-lens.

  • Fixed bugs

    • #14 - “arguments” can no longer take a list as a default

Version 0.2.0 (23 Jul 2012)

  • Parser is now an instance of Alternative. This makes it possible to build certain complex parsers that were not definable before. See tests/Examples/Alternatives.hs for a simple example.

  • Removed multi modifier. You can now use the many or some methods from Alternative, instead, to create parsers for options that can appear more than once.

  • Added new flag' builder that returns a flag without a default value. Although flags without default values were not useful before, with the addition of Alternative combinators, they do have valid use cases.

  • Added new internal modifier for options. An internal option is completely invisible in the help text.

  • Added a new customExecParser function, which takes an additional ParserPrefs parameter. At the moment, ParserPrefs can only be used to control how many-valued option metavars are displayed in the help text. Setting its multiSuffix field to e.g. ... will result in an arguments parser description like [METAVAR]....

  • Fixed bugs

    • #6 - “arguments” swallows options
    • #5 - Help formatting for “arguments” misleading

Version 0.1.1 (21 Jul 2012)

  • New arrow interface

  • Fixed bugs * #7 - “arguments” reads positional arguments in reverse

Version 0.1.0 (07 Jul 2012)

  • Improved error reporting internals

  • Removed template-haskell dependency

  • Fixed bugs: * #3 - No help for subparsers * #4 - Extra empty lines around command list

Version 0.0.1 (09 Jun 2012)

  • Initial release.