2017-12-06 18 views
0

現在、コマンドライン引数の解析が必要なプロジェクトで作業しています。これまで私はthis tutorialに従ってきましたが、これは非常に有益でしたが、引数に変数(--author = example)を返す方法がわかりません。 parse [] = getContentsが原因でエラーが発生した(私はそれをコメント解除しなければならなかった)理由もわかりません。コメントoptparse-applicativeは、CLIと引数は、解析するための偉大なパッケージですThomasM.DuBuissonHaskellでのコマンドライン引数の解析

module Main where 

import qualified System.Environment as SE 
import qualified System.Exit as E 
import qualified Lib as Lib 

main = do 
    args <- SE.getArgs 
    rem <- parse args 
    Lib.someFunc 
    putStrLn rem 
    putStrLn "Hello" 

tac = unlines . reverse . lines 

parse ["--help"] = usage >> exit 
parse ["--version"] = version >> exit 
parse ["--author=xyz"] = return "xyz" 
-- parse ["--author=?"] = ? 
{- 
this is the code I am trying to figure out... how do I get parse the passed in variable name? 
-} 

-- parse []   = getContents 
{- 
the above line generates this error when I run 'main' in GHCi: 

    *Main> <stdin>: hIsEOF: illegal operation (handle is semi-closed) 
    Process intero exited abnormally with code 1 

-} 
parse fs   = concat `fmap` mapM readFile fs 

usage = putStrLn "Usage: gc2" 
version = putStrLn "gc2 -- git-cal in Haskell2010 - 0.1" 
exit = E.exitWith E.ExitSuccess 
die  = E.exitWith (E.ExitFailure 1) 
+1

'getContents'は、すべての入力を取得し、する必要がありますが、ここでoptparse-applicativeを始めることができますだけので

はあなたの例の実装でありますそれ以降の入力からは何も読まない。あなたはその契約を満足していますか?例えば ​​'Lib.someFunc'をチェックしてください。 – chi

+0

ありがとう、それは意味があります(そして、私がSystem.ProcessをLib.someFuncで使用していたためにエラーが発生したようです)。 – kuwze

+1

そこには引数解析ライブラリがあります。そのうちの1つを使用しない理由はありますか? –

答えて

3

@にフォローアップする:

は、ここに私のコードです。また、前のパッケージの上に構築されたもう1つのパッケージoptparse-simpleがあります。少し単純化するヘルパーがいくつかあります。 GHCiのから

data Options = Options 
    { author :: String 
    } 

main :: IO() 
main = do 
    let ver = "gc2 -- git-cal in Haskell2010 - 0.1" 
    args <- 
    execParser $ 
    info 
     (Options <$> 
     strOption (long "author" <> 
        short 'a' <> 
        help "Name of the author.") <* 
     infoOption ver (long "version" <> 
         short 'v' <> 
         help "Display version and exit.") <* 
     abortOption ShowHelpText (long "help" <> 
           short 'h' <> 
           help "Display this message.")) 
     (progDesc "Very powerful tool." <> fullDesc) 
    putStrLn $ author args 

と使用例:

λ> :main 
Missing: (-a|--author ARG) 

Usage: <interactive> (-a|--author ARG) [-v|--version] [-h|--help] 
    Very powerful tool. 
*** Exception: ExitFailure 1 
λ> :main --version 
gc2 -- git-cal in Haskell2010 - 0.1 
*** Exception: ExitSuccess 
λ> :main --help 
Usage: <interactive> (-a|--author ARG) [-v|--version] [-h|--help] 
    Very powerful tool. 

Available options: 
    -a,--author ARG   Name of the author. 
    -v,--version    Display version and exit. 
    -h,--help    Display this message. 
*** Exception: ExitSuccess 
λ> :main --author Me 
Me 
関連する問題