module Options.Applicative.Extra (
helper,
execParser,
execParserPure,
usage,
ParserFailure(..),
) where
import Data.Lens.Common
import Options.Applicative.Common
import Options.Applicative.Builder
import Options.Applicative.Help
import Options.Applicative.Utils
import Options.Applicative.Types
import System.Environment
import System.Exit
import System.IO
helper :: Parser (a -> a)
helper = nullOption
( long "help"
& short 'h'
& help "Show this help text"
& value id
& hide )
data ParserFailure = ParserFailure
{ errMessage :: String -> String
, errExitCode :: ExitCode
}
execParser :: ParserInfo a -> IO a
execParser pinfo = do
args <- getArgs
case execParserPure pinfo args of
Right a -> return a
Left failure -> do
progn <- getProgName
hPutStr stderr (errMessage failure progn)
exitWith (errExitCode failure)
execParserPure :: ParserInfo a
-> [String]
-> Either ParserFailure a
execParserPure pinfo args =
case runParser parser args of
Just (a, []) -> Right a
_ -> Left ParserFailure
{ errMessage = \progn -> parserHelpText (add_usage progn pinfo)
, errExitCode = ExitFailure (pinfo^.infoFailureCode) }
where
parser = pinfo^.infoParser
add_usage progn = modL infoHeader $ \h -> vcat [h, usage parser progn]
usage :: Parser a -> String -> String
usage p progn = foldr (<+>) ""
[ "Usage:"
, progn
, briefDesc p ]