目前,它看起來像要做到這一點,從Options.Applicative.Extra module創建自己的customExecParser
版本的唯一途徑。有an open issue使這更簡單。
像這樣的東西應該是非常接近你在找什麼:
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 = ...
這基本上是customExecParser
用一小塊,檢查如果參數是空的。如果是,它會顯示解析器幫助。
這可能提交已添加一個更簡單的方式來做到以上:https://github.com/pcapriotti/optparse-applicative/commit/bab98fe8ee95635a0befca6ad9365be7d31b0541 – ntc2