我有一个Haskell应用程序,它使用optparse-applicative
库进行CLI参数解析。我的CLI参数的数据类型包含FilePath
s(文件和目录),Double
等等。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")
这对我来说太过于特别和丑陋。此外,我几乎每个我编写的应用程序都需要类似的功能。当我想在实际使用数据类型做一些事情之前做一堆检查时,是否有一些惯用的方法来处理这种编程模式?涉及的样板越少越好:)
答案 0 :(得分:1)
我们可以使用applicative functor composition来组合参数解析和验证,而不是在构建之后验证选项记录,而不是验证它们:
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."]