3

我有一个使用optparse-applicative库进行 CLI 参数解析的 Haskell 应用程序。我的 CLI 参数数据类型包含FilePaths(文件和目录),Doubles 等optparse-applicative可以处理解析错误,但我想确保某些文件和某些目录存在(或不存在),数字是>= 0等等。

可以做的是实现一堆帮助函数,比如这些:

exitIfM :: IO Bool -> Text -> IO ()
exitIfM predicateM errorMessage = whenM predicateM $ putTextLn errorMessage >> exitFailure 

exitIfNotM :: IO Bool -> Text -> IO ()
exitIfNotM predicateM errorMessage = unlessM predicateM $ putTextLn errorMessage >> exitFailure 

然后我像这样使用它:

body :: Options -> IO ()
body (Options path1 path2 path3 count) = do
    exitIfNotM (doesFileExist path1) ("File " <> (toText ledgerPath) <> " does not exist") 
    exitIfNotM (doesDirectoryExist path2) ("Directory " <> (toText skKeysPath) <> " does not exist")
    exitIfM (doesFileExist path3) ("File " <> (toText nodeExe) <> " already exist")
    exitIf (count <= 0) ("--counter should be positive")

这对我来说看起来太临时和丑陋了。此外,我编写的几乎每个应用程序都需要类似的功能。当我想在实际使用数据类型做某事之前做一堆检查时,是否有一些惯用的方法来处理这种编程模式?涉及的样板越少越好:)

4

1 回答 1

3

与其在构建选项记录验证它,也许我们可以使用应用函子组合来结合参数解析和验证:

import Control.Monad
import Data.Functor.Compose
import Control.Lens ((<&>)) -- flipped fmap
import Control.Applicative.Lift (runErrors,failure) -- form transformers
import qualified Options.Applicative as O
import System.Directory -- from directory

data Options = Options { path :: FilePath, count :: Int } deriving Show

main :: IO ()
main = do
    let pathOption = Compose (Compose (O.argument O.str (O.metavar "FILE") <&> \file ->
            do exists <- doesPathExist file
               pure $ if exists
                      then pure file
                      else failure ["Could not find file."]))
        countOption = Compose (Compose (O.argument O.auto (O.metavar "INT") <&> \i ->
            do pure $ if i < 10
                      then pure i
                      else failure ["Incorrect number."]))
        Compose (Compose parsy) = Options <$> pathOption <*> countOption
    io <- O.execParser $ O.info parsy mempty
    errs <- io
    case runErrors errs of
        Left msgs -> print msgs
        Right r -> print r

组合解析器具有类型Compose (Compose Parser IO) (Errors [String]) Options。该IO层用于执行文件存在检查,同时Errors是来自转换器的类似验证的应用程序,用于累积错误消息。运行解析器会产生一个IO动作,运行时会产生一个Errors [String] Options值。

代码有点冗长,但这些参数解析器可以打包在一个库中并重用。

一些例子形成了repl:

Λ :main "/tmp" 2
Options {path = "/tmp", count = 2}
Λ :main "/tmpx" 2
["Could not find file."]
Λ :main "/tmpx" 22
["Could not find file.","Incorrect number."]
于 2018-02-16T21:51:45.913 回答