Optparse-applative: display help for programs called without arguments

I am using optparse-applicative version 0.7.0.2.

I want to write a parser that accepts some required parameters, but when called without parameters, it shows both use and help, and not just use (that is, I want the call to have no parameters in order to behave like a call with --help ).

I cannot figure out how to do this, even if the documentation states that this is possible :

The hello parameter in this example is required (since it does not have a default value), so starting the program without any arguments will display the help text

Is there a working example of this? One in the main documentation does not work for me (it prints only use).

+6
source share
3 answers

Currently, it seems the only way to do this is to create your own version of customExecParser from the Options.Applicative.Extra module . There is an open problem to make it easier.

Something like this should be very close to what you are looking for:

 import Options.Applicative import Options.Applicative.Help as AH import Options.Applicative.Types as AT import System.Environment (getArgs, getProgName) import System.Exit (exitWith, ExitCode(..)) import System.IO (hPutStr, stderr) execParserWithHelp :: ParserPrefs -> ParserInfo a -> IO a execParserWithHelp pprefs pinfo = do args <- getArgs case execParserPure pprefs pinfo args of Right a -> return a Left failure -> do progn <- getProgName msg <- AT.errMessage failure progn let extra = if null args then AH.parserHelpText pprefs pinfo else "" let c = errExitCode failure case c of ExitSuccess -> putStr (msg ++ extra) _ -> hPutStr stderr (msg ++ extra) exitWith c main :: IO () main = execParserWithHelp (prefs idm) opts >>= run opts :: ParserInfo Command opts = info (commands <**> helper) idm run :: Command -> IO () run = ... 

It is basically just a customExecParser with a small block that checks if the arguments are empty. If they are, it displays the help of the parser.

+3
source

The revival of the old theme, but I added the showHelpOnEmpty prefix for this, so now it's simple. Given the p :: ParserInfo a

 run :: IO a run = customExecParser (prefs showHelpOnEmpty) p 
+3
source

If you want to print the --help output for all errors, including when the program is launched without arguments, then replace calls execParser with calls to showHelpOnErrorExecParser , defined by

 -- | A version of 'execParser' which shows full help on error. -- -- The regular 'execParser' only prints usage on error, which doesn't -- include the options, subcommands, or mention of the help switch -- @ --help@. showHelpOnErrorExecParser :: ParserInfo a -> IO a showHelpOnErrorExecParser = customExecParser (prefs showHelpOnError) 

Based on comment about the problem associated with the accepted answer.

+2
source

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


All Articles