1 -----------------------------------------------------------------------------
3 -- Module : System.Console.GetOpt
4 -- Copyright : (c) Sven Panne 2002-2005
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 | UnreqOpt String -- an un-recognized option
92 | NonOpt String -- a non-option
93 | EndOfOpts -- end-of-options marker (i.e. "--")
94 | OptErr String -- something went wrong...
96 -- | Return a string describing the usage of a command, derived from
97 -- the header (first argument) and the options described by the
99 usageInfo :: String -- header
100 -> [OptDescr a] -- option descriptors
101 -> String -- nicely formatted decription of options
102 usageInfo header optDescr = unlines (header:table)
103 where (ss,ls,ds) = (unzip3 . concatMap fmtOpt) optDescr
104 table = zipWith3 paste (sameLen ss) (sameLen ls) ds
105 paste x y z = " " ++ x ++ " " ++ y ++ " " ++ z
106 sameLen xs = flushLeft ((maximum . map length) xs) xs
107 flushLeft n xs = [ take n (x ++ repeat ' ') | x <- xs ]
109 fmtOpt :: OptDescr a -> [(String,String,String)]
110 fmtOpt (Option sos los ad descr) =
112 [] -> [(sosFmt,losFmt,"")]
113 (d:ds) -> (sosFmt,losFmt,d) : [ ("","",d') | d' <- ds ]
114 where sepBy _ [] = ""
116 sepBy ch (x:xs) = x ++ ch:' ':sepBy ch xs
117 sosFmt = sepBy ',' (map (fmtShort ad) sos)
118 losFmt = sepBy ',' (map (fmtLong ad) los)
120 fmtShort :: ArgDescr a -> Char -> String
121 fmtShort (NoArg _ ) so = "-" ++ [so]
122 fmtShort (ReqArg _ ad) so = "-" ++ [so] ++ " " ++ ad
123 fmtShort (OptArg _ ad) so = "-" ++ [so] ++ "[" ++ ad ++ "]"
125 fmtLong :: ArgDescr a -> String -> String
126 fmtLong (NoArg _ ) lo = "--" ++ lo
127 fmtLong (ReqArg _ ad) lo = "--" ++ lo ++ "=" ++ ad
128 fmtLong (OptArg _ ad) lo = "--" ++ lo ++ "[=" ++ ad ++ "]"
131 Process the command-line, and return the list of values that matched
132 (and those that didn\'t). The arguments are:
134 * The order requirements (see 'ArgOrder')
136 * The option descriptions (see 'OptDescr')
138 * The actual command line arguments (presumably got from
139 'System.Environment.getArgs').
141 'getOpt' returns a triple consisting of the option arguments, a list
142 of non-options, and a list of error messages.
144 getOpt :: ArgOrder a -- non-option handling
145 -> [OptDescr a] -- option descriptors
146 -> [String] -- the command-line arguments
147 -> ([a],[String],[String]) -- (options,non-options,error messages)
148 getOpt ordering optDescr args = (os,xs,es ++ map errUnrec us)
149 where (os,xs,us,es) = getOpt' ordering optDescr args
152 This is almost the same as 'getOpt', but returns a quadruple
153 consisting of the option arguments, a list of non-options, a list of
154 unrecognized options, and a list of error messages.
156 getOpt' :: ArgOrder a -- non-option handling
157 -> [OptDescr a] -- option descriptors
158 -> [String] -- the command-line arguments
159 -> ([a],[String], [String] ,[String]) -- (options,non-options,unrecognized,error messages)
160 getOpt' _ _ [] = ([],[],[],[])
161 getOpt' ordering optDescr (arg:args) = procNextOpt opt ordering
162 where procNextOpt (Opt o) _ = (o:os,xs,us,es)
163 procNextOpt (UnreqOpt u) _ = (os,xs,u:us,es)
164 procNextOpt (NonOpt x) RequireOrder = ([],x:rest,us,[])
165 procNextOpt (NonOpt x) Permute = (os,x:xs,us,es)
166 procNextOpt (NonOpt x) (ReturnInOrder f) = (f x :os, xs,us,es)
167 procNextOpt EndOfOpts RequireOrder = ([],rest,[],[])
168 procNextOpt EndOfOpts Permute = ([],rest,[],[])
169 procNextOpt EndOfOpts (ReturnInOrder f) = (map f rest,[],[],[])
170 procNextOpt (OptErr e) _ = (os,xs,us,e:es)
172 (opt,rest) = getNext arg args optDescr
173 (os,xs,us,es) = getOpt' ordering optDescr rest
175 -- take a look at the next cmd line arg and decide what to do with it
176 getNext :: String -> [String] -> [OptDescr a] -> (OptKind a,[String])
177 getNext ('-':'-':[]) rest _ = (EndOfOpts,rest)
178 getNext ('-':'-':xs) rest optDescr = longOpt xs rest optDescr
179 getNext ('-': x :xs) rest optDescr = shortOpt x xs rest optDescr
180 getNext a rest _ = (NonOpt a,rest)
182 -- handle long option
183 longOpt :: String -> [String] -> [OptDescr a] -> (OptKind a,[String])
184 longOpt ls rs optDescr = long ads arg rs
185 where (opt,arg) = break (=='=') ls
186 getWith p = [ o | o@(Option _ xs _ _) <- optDescr, x <- xs, opt `p` x ]
188 options = if null exact then getWith isPrefixOf else exact
189 ads = [ ad | Option _ _ ad _ <- options ]
192 long (_:_:_) _ rest = (errAmbig options optStr,rest)
193 long [NoArg a ] [] rest = (Opt a,rest)
194 long [NoArg _ ] ('=':_) rest = (errNoArg optStr,rest)
195 long [ReqArg _ d] [] [] = (errReq d optStr,[])
196 long [ReqArg f _] [] (r:rest) = (Opt (f r),rest)
197 long [ReqArg f _] ('=':xs) rest = (Opt (f xs),rest)
198 long [OptArg f _] [] rest = (Opt (f Nothing),rest)
199 long [OptArg f _] ('=':xs) rest = (Opt (f (Just xs)),rest)
200 long _ _ rest = (UnreqOpt ("--"++ls),rest)
202 -- handle short option
203 shortOpt :: Char -> String -> [String] -> [OptDescr a] -> (OptKind a,[String])
204 shortOpt y ys rs optDescr = short ads ys rs
205 where options = [ o | o@(Option ss _ _ _) <- optDescr, s <- ss, y == s ]
206 ads = [ ad | Option _ _ ad _ <- options ]
209 short (_:_:_) _ rest = (errAmbig options optStr,rest)
210 short (NoArg a :_) [] rest = (Opt a,rest)
211 short (NoArg a :_) xs rest = (Opt a,('-':xs):rest)
212 short (ReqArg _ d:_) [] [] = (errReq d optStr,[])
213 short (ReqArg f _:_) [] (r:rest) = (Opt (f r),rest)
214 short (ReqArg f _:_) xs rest = (Opt (f xs),rest)
215 short (OptArg f _:_) [] rest = (Opt (f Nothing),rest)
216 short (OptArg f _:_) xs rest = (Opt (f (Just xs)),rest)
217 short [] [] rest = (UnreqOpt optStr,rest)
218 short [] xs rest = (UnreqOpt optStr,('-':xs):rest)
220 -- miscellaneous error formatting
222 errAmbig :: [OptDescr a] -> String -> OptKind a
223 errAmbig ods optStr = OptErr (usageInfo header ods)
224 where header = "option `" ++ optStr ++ "' is ambiguous; could be one of:"
226 errReq :: String -> String -> OptKind a
227 errReq d optStr = OptErr ("option `" ++ optStr ++ "' requires an argument " ++ d ++ "\n")
229 errUnrec :: String -> String
230 errUnrec optStr = "unrecognized option `" ++ optStr ++ "'\n"
232 errNoArg :: String -> OptKind a
233 errNoArg optStr = OptErr ("option `" ++ optStr ++ "' doesn't allow an argument\n")
236 -----------------------------------------------------------------------------------------
237 -- and here a small and hopefully enlightening example:
239 data Flag = Verbose | Version | Name String | Output String | Arg String deriving Show
241 options :: [OptDescr Flag]
243 [Option ['v'] ["verbose"] (NoArg Verbose) "verbosely list files",
244 Option ['V','?'] ["version","release"] (NoArg Version) "show version info",
245 Option ['o'] ["output"] (OptArg out "FILE") "use FILE for dump",
246 Option ['n'] ["name"] (ReqArg Name "USER") "only dump USER's files"]
248 out :: Maybe String -> Flag
249 out Nothing = Output "stdout"
250 out (Just o) = Output o
252 test :: ArgOrder Flag -> [String] -> String
253 test order cmdline = case getOpt order options cmdline of
254 (o,n,[] ) -> "options=" ++ show o ++ " args=" ++ show n ++ "\n"
255 (_,_,errs) -> concat errs ++ usageInfo header options
256 where header = "Usage: foobar [OPTION...] files..."
259 -- putStr (test RequireOrder ["foo","-v"])
260 -- ==> options=[] args=["foo", "-v"]
261 -- putStr (test Permute ["foo","-v"])
262 -- ==> options=[Verbose] args=["foo"]
263 -- putStr (test (ReturnInOrder Arg) ["foo","-v"])
264 -- ==> options=[Arg "foo", Verbose] args=[]
265 -- putStr (test Permute ["foo","--","-v"])
266 -- ==> options=[] args=["foo", "-v"]
267 -- putStr (test Permute ["-?o","--name","bar","--na=baz"])
268 -- ==> options=[Version, Output "stdout", Name "bar", Name "baz"] args=[]
269 -- putStr (test Permute ["--ver","foo"])
270 -- ==> option `--ver' is ambiguous; could be one of:
271 -- -v --verbose verbosely list files
272 -- -V, -? --version, --release show version info
273 -- Usage: foobar [OPTION...] files...
274 -- -v --verbose verbosely list files
275 -- -V, -? --version, --release show version info
276 -- -o[FILE] --output[=FILE] use FILE for dump
277 -- -n USER --name=USER only dump USER's files
278 -----------------------------------------------------------------------------------------
283 To hopefully illuminate the role of the different data
284 structures, here\'s the command-line options for a (very simple)
289 > import System.Console.GetOpt
290 > import Data.Maybe ( fromMaybe )
293 > = Verbose | Version
294 > | Input String | Output String | LibDir String
297 > options :: [OptDescr Flag]
299 > [ Option ['v'] ["verbose"] (NoArg Verbose) "chatty output on stderr"
300 > , Option ['V','?'] ["version"] (NoArg Version) "show version number"
301 > , Option ['o'] ["output"] (OptArg outp "FILE") "output FILE"
302 > , Option ['c'] [] (OptArg inp "FILE") "input FILE"
303 > , Option ['L'] ["libdir"] (ReqArg LibDir "DIR") "library directory"
306 > inp,outp :: Maybe String -> Flag
307 > outp = Output . fromMaybe "stdout"
308 > inp = Input . fromMaybe "stdin"
310 > compilerOpts :: [String] -> IO ([Flag], [String])
311 > compilerOpts argv =
312 > case getOpt Permute options argv of
313 > (o,n,[] ) -> return (o,n)
314 > (_,_,errs) -> ioError (userError (concat errs ++ usageInfo header options))
315 > where header = "Usage: ic [OPTION...] files..."