1 -----------------------------------------------------------------------------
3 -- Module : System.Console.GetOpt
4 -- Copyright : (c) Sven Panne 2002-2004
5 -- License : BSD-style (see the file libraries/base/LICENSE)
7 -- Maintainer : libraries@haskell.org
8 -- Stability : experimental
9 -- Portability : portable
11 -- This library provides facilities for parsing the command-line options
12 -- in a standalone program. It is essentially a Haskell port of the GNU
15 -----------------------------------------------------------------------------
18 Sven Panne <Sven.Panne@informatik.uni-muenchen.de> Oct. 1996 (small
21 Two rather obscure features are missing: The Bash 2.0 non-option hack
22 (if you don't already know it, you probably don't want to hear about
23 it...) and the recognition of long options with a single dash
24 (e.g. '-help' is recognised as '--help', as long as there is no short
27 Other differences between GNU's getopt and this implementation:
29 * To enforce a coherent description of options and arguments, there
30 are explanation fields in the option/argument descriptor.
32 * Error messages are now more informative, but no longer POSIX
35 And a final Haskell advertisement: The GNU C implementation uses well
36 over 1100 lines, we need only 195 here, including a 46 line example!
40 module System.Console.GetOpt (
53 import Prelude -- necessary to get dependencies right
55 import Data.List ( isPrefixOf )
57 -- |What to do with options following non-options
59 = RequireOrder -- ^ no option processing after first non-option
60 | Permute -- ^ freely intersperse options and non-options
61 | ReturnInOrder (String -> a) -- ^ wrap non-options into options
64 Each 'OptDescr' describes a single option.
66 The arguments to 'Option' are:
68 * list of short option characters
70 * list of long option strings (without \"--\")
74 * explanation of option for user
76 data OptDescr a = -- description of a single options:
77 Option [Char] -- list of short option characters
78 [String] -- list of long option strings (without "--")
79 (ArgDescr a) -- argument descriptor
80 String -- explanation of option for user
82 -- |Describes whether an option takes an argument or not, and if so
83 -- how the argument is injected into a value of type @a@.
85 = NoArg a -- ^ no argument expected
86 | ReqArg (String -> a) String -- ^ option requires argument
87 | OptArg (Maybe String -> a) String -- ^ optional argument
89 data OptKind a -- kind of cmd line arg (internal use only):
91 | NonOpt String -- a non-option
92 | EndOfOpts -- end-of-options marker (i.e. "--")
93 | OptErr String -- something went wrong...
95 -- | Return a string describing the usage of a command, derived from
96 -- the header (first argument) and the options described by the
98 usageInfo :: String -- header
99 -> [OptDescr a] -- option descriptors
100 -> String -- nicely formatted decription of options
101 usageInfo header optDescr = unlines (header:table)
102 where (ss,ls,ds) = (unzip3 . concatMap fmtOpt) optDescr
103 table = zipWith3 paste (sameLen ss) (sameLen ls) ds
104 paste x y z = " " ++ x ++ " " ++ y ++ " " ++ z
105 sameLen xs = flushLeft ((maximum . map length) xs) xs
106 flushLeft n xs = [ take n (x ++ repeat ' ') | x <- xs ]
108 fmtOpt :: OptDescr a -> [(String,String,String)]
109 fmtOpt (Option sos los ad descr) =
111 [] -> [(sosFmt,losFmt,"")]
112 (d:ds) -> (sosFmt,losFmt,d) : [ ("","",d') | d' <- ds ]
113 where sepBy _ [] = ""
115 sepBy ch (x:xs) = x ++ ch:' ':sepBy ch xs
116 sosFmt = sepBy ',' (map (fmtShort ad) sos)
117 losFmt = sepBy ',' (map (fmtLong ad) los)
119 fmtShort :: ArgDescr a -> Char -> String
120 fmtShort (NoArg _ ) so = "-" ++ [so]
121 fmtShort (ReqArg _ ad) so = "-" ++ [so] ++ " " ++ ad
122 fmtShort (OptArg _ ad) so = "-" ++ [so] ++ "[" ++ ad ++ "]"
124 fmtLong :: ArgDescr a -> String -> String
125 fmtLong (NoArg _ ) lo = "--" ++ lo
126 fmtLong (ReqArg _ ad) lo = "--" ++ lo ++ "=" ++ ad
127 fmtLong (OptArg _ ad) lo = "--" ++ lo ++ "[=" ++ ad ++ "]"
130 Process the command-line, and return the list of values that matched
131 (and those that didn\'t). The arguments are:
133 * The order requirements (see 'ArgOrder')
135 * The option descriptions (see 'OptDescr')
137 * The actual command line arguments (presumably got from
138 'System.Environment.getArgs').
140 'getOpt' returns a triple, consisting of the argument values, a list
141 of options that didn\'t match, and a list of error messages.
143 getOpt :: ArgOrder a -- non-option handling
144 -> [OptDescr a] -- option descriptors
145 -> [String] -- the commandline arguments
146 -> ([a],[String],[String]) -- (options,non-options,error messages)
147 getOpt _ _ [] = ([],[],[])
148 getOpt ordering optDescr (arg:args) = procNextOpt opt ordering
149 where procNextOpt (Opt o) _ = (o:os,xs,es)
150 procNextOpt (NonOpt x) RequireOrder = ([],x:rest,[])
151 procNextOpt (NonOpt x) Permute = (os,x:xs,es)
152 procNextOpt (NonOpt x) (ReturnInOrder f) = (f x :os, xs,es)
153 procNextOpt EndOfOpts RequireOrder = ([],rest,[])
154 procNextOpt EndOfOpts Permute = ([],rest,[])
155 procNextOpt EndOfOpts (ReturnInOrder f) = (map f rest,[],[])
156 procNextOpt (OptErr e) _ = (os,xs,e:es)
158 (opt,rest) = getNext arg args optDescr
159 (os,xs,es) = getOpt ordering optDescr rest
161 -- take a look at the next cmd line arg and decide what to do with it
162 getNext :: String -> [String] -> [OptDescr a] -> (OptKind a,[String])
163 getNext ('-':'-':[]) rest _ = (EndOfOpts,rest)
164 getNext ('-':'-':xs) rest optDescr = longOpt xs rest optDescr
165 getNext ('-': x :xs) rest optDescr = shortOpt x xs rest optDescr
166 getNext a rest _ = (NonOpt a,rest)
168 -- handle long option
169 longOpt :: String -> [String] -> [OptDescr a] -> (OptKind a,[String])
170 longOpt ls rs optDescr = long ads arg rs
171 where (opt,arg) = break (=='=') ls
172 getWith p = [ o | o@(Option _ ls _ _) <- optDescr, l <- ls, opt `p` l ]
174 options = if null exact then getWith isPrefixOf else exact
175 ads = [ ad | Option _ _ ad _ <- options ]
178 long (_:_:_) _ rest = (errAmbig options optStr,rest)
179 long [NoArg a ] [] rest = (Opt a,rest)
180 long [NoArg _ ] ('=':_) rest = (errNoArg optStr,rest)
181 long [ReqArg _ d] [] [] = (errReq d optStr,[])
182 long [ReqArg f _] [] (r:rest) = (Opt (f r),rest)
183 long [ReqArg f _] ('=':xs) rest = (Opt (f xs),rest)
184 long [OptArg f _] [] rest = (Opt (f Nothing),rest)
185 long [OptArg f _] ('=':xs) rest = (Opt (f (Just xs)),rest)
186 long _ _ rest = (errUnrec optStr,rest)
188 -- handle short option
189 shortOpt :: Char -> String -> [String] -> [OptDescr a] -> (OptKind a,[String])
190 shortOpt x xs rest optDescr = short ads xs rest
191 where options = [ o | o@(Option ss _ _ _) <- optDescr, s <- ss, x == s ]
192 ads = [ ad | Option _ _ ad _ <- options ]
195 short (_:_:_) _ rest = (errAmbig options optStr,rest)
196 short (NoArg a :_) [] rest = (Opt a,rest)
197 short (NoArg a :_) xs rest = (Opt a,('-':xs):rest)
198 short (ReqArg _ d:_) [] [] = (errReq d optStr,[])
199 short (ReqArg f _:_) [] (r:rest) = (Opt (f r),rest)
200 short (ReqArg f _:_) xs rest = (Opt (f xs),rest)
201 short (OptArg f _:_) [] rest = (Opt (f Nothing),rest)
202 short (OptArg f _:_) xs rest = (Opt (f (Just xs)),rest)
203 short [] [] rest = (errUnrec optStr,rest)
204 short [] xs rest = (errUnrec optStr,('-':xs):rest)
206 -- miscellaneous error formatting
208 errAmbig :: [OptDescr a] -> String -> OptKind a
209 errAmbig ods optStr = OptErr (usageInfo header ods)
210 where header = "option `" ++ optStr ++ "' is ambiguous; could be one of:"
212 errReq :: String -> String -> OptKind a
213 errReq d optStr = OptErr ("option `" ++ optStr ++ "' requires an argument " ++ d ++ "\n")
215 errUnrec :: String -> OptKind a
216 errUnrec optStr = OptErr ("unrecognized option `" ++ optStr ++ "'\n")
218 errNoArg :: String -> OptKind a
219 errNoArg optStr = OptErr ("option `" ++ optStr ++ "' doesn't allow an argument\n")
222 -----------------------------------------------------------------------------------------
223 -- and here a small and hopefully enlightening example:
225 data Flag = Verbose | Version | Name String | Output String | Arg String deriving Show
227 options :: [OptDescr Flag]
229 [Option ['v'] ["verbose"] (NoArg Verbose) "verbosely list files",
230 Option ['V','?'] ["version","release"] (NoArg Version) "show version info",
231 Option ['o'] ["output"] (OptArg out "FILE") "use FILE for dump",
232 Option ['n'] ["name"] (ReqArg Name "USER") "only dump USER's files"]
234 out :: Maybe String -> Flag
235 out Nothing = Output "stdout"
236 out (Just o) = Output o
238 test :: ArgOrder Flag -> [String] -> String
239 test order cmdline = case getOpt order options cmdline of
240 (o,n,[] ) -> "options=" ++ show o ++ " args=" ++ show n ++ "\n"
241 (_,_,errs) -> concat errs ++ usageInfo header options
242 where header = "Usage: foobar [OPTION...] files..."
245 -- putStr (test RequireOrder ["foo","-v"])
246 -- ==> options=[] args=["foo", "-v"]
247 -- putStr (test Permute ["foo","-v"])
248 -- ==> options=[Verbose] args=["foo"]
249 -- putStr (test (ReturnInOrder Arg) ["foo","-v"])
250 -- ==> options=[Arg "foo", Verbose] args=[]
251 -- putStr (test Permute ["foo","--","-v"])
252 -- ==> options=[] args=["foo", "-v"]
253 -- putStr (test Permute ["-?o","--name","bar","--na=baz"])
254 -- ==> options=[Version, Output "stdout", Name "bar", Name "baz"] args=[]
255 -- putStr (test Permute ["--ver","foo"])
256 -- ==> option `--ver' is ambiguous; could be one of:
257 -- -v --verbose verbosely list files
258 -- -V, -? --version, --release show version info
259 -- Usage: foobar [OPTION...] files...
260 -- -v --verbose verbosely list files
261 -- -V, -? --version, --release show version info
262 -- -o[FILE] --output[=FILE] use FILE for dump
263 -- -n USER --name=USER only dump USER's files
264 -----------------------------------------------------------------------------------------
269 To hopefully illuminate the role of the different data
270 structures, here\'s the command-line options for a (very simple)
275 > import System.Console.GetOpt
276 > import Data.Maybe ( fromMaybe )
279 > = Verbose | Version
280 > | Input String | Output String | LibDir String
283 > options :: [OptDescr Flag]
285 > [ Option ['v'] ["verbose"] (NoArg Verbose) "chatty output on stderr"
286 > , Option ['V','?'] ["version"] (NoArg Version) "show version number"
287 > , Option ['o'] ["output"] (OptArg outp "FILE") "output FILE"
288 > , Option ['c'] [] (OptArg inp "FILE") "input FILE"
289 > , Option ['L'] ["libdir"] (ReqArg LibDir "DIR") "library directory"
292 > inp,outp :: Maybe String -> Flag
293 > outp = Output . fromMaybe "stdout"
294 > inp = Input . fromMaybe "stdout"
296 > compilerOpts :: [String] -> IO ([Flag], [String])
297 > compilerOpts argv =
298 > case (getOpt Permute options argv) of
299 > (o,n,[] ) -> return (o,n)
300 > (_,_,errs) -> ioError (userError (concat errs ++ usageInfo header options))
301 > where header = "Usage: ic [OPTION...] files..."