docopt / docopt.hs

A command-line interface description language and parser that will make you smile
http://docopt.org/
MIT License
119 stars 24 forks source link

Docopt.hs

A Haskell port of python's docopt.


Want a command-line interface without building a parser?

How about writing your help text first, and getting a parser for free!

Save your help text to a file (i.e. USAGE.txt):

Usage:
  myprog cat <file>
  myprog echo [--caps] <string>

Options:
  -c, --caps    Caps-lock the echoed argument

Then, in your Myprog.hs:

{-# LANGUAGE QuasiQuotes #-}
import Control.Monad (when)
import Data.Char (toUpper)
import System.Environment (getArgs)
import System.Console.Docopt

patterns :: Docopt
patterns = [docoptFile|USAGE.txt|]

getArgOrExit = getArgOrExitWith patterns

main = do
  args <- parseArgsOrExit patterns =<< getArgs

  when (args `isPresent` (command "cat")) $ do
    file <- args `getArgOrExit` (argument "file")
    putStr =<< readFile file

  when (args `isPresent` (command "echo")) $ do
    let charTransform = if args `isPresent` (longOption "caps")
                          then toUpper
                          else id
    string <- args `getArgOrExit` (argument "string")
    putStrLn $ map charTransform string

That's it! No Template Haskell, no unreadable syntax, no learning yet another finicky API. Write the usage patterns you support, and docopt builds the appropriate option parser for you (internally using parsec). If your user invokes your program correctly, you query for the arguments they provided. If the arguments provided do not match a supported usage pattern, you guessed it: docopt automatically prints the help text and exits!

Installation

cabal sandbox init
cabal install docopt

API Reference

See the package on hackage

Help text format

Docopt only cares about 2 parts of your help text:

Usage Patterns

Option descriptions

Option descriptions establish:

Rules:


Differences from reference python implementation: