Skip to content

Instantly share code, notes, and snippets.

@ddribin
Created May 21, 2011 15:29
Show Gist options
  • Save ddribin/984609 to your computer and use it in GitHub Desktop.
Save ddribin/984609 to your computer and use it in GitHub Desktop.
module Options
( Options
, parseArgs
) where
import System.Console.GetOpt
import Data.Maybe ( fromMaybe )
data Options = Options
{ optVerbose :: Bool
, optShowVersion :: Bool
, optOutput :: Maybe FilePath
, optInput :: Maybe FilePath
, optTempDir :: FilePath
, optLibDirs :: [FilePath]
} deriving Show
defaultOptions = Options
{ optVerbose = False
, optShowVersion = False
, optOutput = Nothing
, optInput = Nothing
, optTempDir = "/tmp"
, optLibDirs = []
}
setVerbose v opts = opts { optVerbose = v }
setShowVersion v opts = opts { optShowVersion = v }
setOutput f opts = opts { optOutput = Just f' }
where f' = fromMaybe "output" f
setInput f opts = opts { optInput = Just f' }
where f' = fromMaybe "-" f
setTempDir d opts = opts { optTempDir = d }
addLibDir d opts = opts { optLibDirs = optLibDirs opts ++ [d] }
options :: [OptDescr (Options -> Options)]
options =
[ Option ['v'] ["verbose"] (NoArg (setVerbose True)) "chatty output on stderr"
, Option ['V','?'] ["version"] (NoArg (setShowVersion True)) "show version number"
, Option ['o'] ["output"] (OptArg setOutput "FILE") "output FILE"
, Option ['c'] [] (OptArg setInput "FILE") "input FILE"
, Option ['t'] ["temp"] (ReqArg setTempDir "DIR") "temporary directory"
, Option ['L'] ["libdir"] (ReqArg addLibDir "DIR") "library directory"
]
parseArgs :: [String] -> IO (Options, [String])
parseArgs args =
case getOpt RequireOrder options args of
(o,n,[] ) -> return (foldl (flip id) defaultOptions o, n)
(_,_,errs) -> ioError (userError (concat errs ++ usageInfo header options))
where header = "Usage: ic [OPTION...] files..."
#!/usr/bin/env runhaskell
module Main( main ) where
import System( getArgs )
import Options( parseArgs )
main = do
args <- getArgs
( options, nonOpts ) <- parseArgs args
putStrLn $ show options
putStrLn $ "Rest: " ++ show nonOpts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment