Update base for latest Safe Haskell.
[packages/base.git] / System / Console / GetOpt.hs
1 {-# LANGUAGE Safe #-}
2
3 -----------------------------------------------------------------------------
4 -- |
5 -- Module : System.Console.GetOpt
6 -- Copyright : (c) Sven Panne 2002-2005
7 -- License : BSD-style (see the file libraries/base/LICENSE)
8 --
9 -- Maintainer : libraries@haskell.org
10 -- Stability : experimental
11 -- Portability : portable
12 --
13 -- This library provides facilities for parsing the command-line options
14 -- in a standalone program. It is essentially a Haskell port of the GNU
15 -- @getopt@ library.
16 --
17 -----------------------------------------------------------------------------
18
19 {-
20 Sven Panne <Sven.Panne@informatik.uni-muenchen.de> Oct. 1996 (small
21 changes Dec. 1997)
22
23 Two rather obscure features are missing: The Bash 2.0 non-option hack
24 (if you don't already know it, you probably don't want to hear about
25 it...) and the recognition of long options with a single dash
26 (e.g. '-help' is recognised as '--help', as long as there is no short
27 option 'h').
28
29 Other differences between GNU's getopt and this implementation:
30
31 * To enforce a coherent description of options and arguments, there
32 are explanation fields in the option/argument descriptor.
33
34 * Error messages are now more informative, but no longer POSIX
35 compliant... :-(
36
37 And a final Haskell advertisement: The GNU C implementation uses well
38 over 1100 lines, we need only 195 here, including a 46 line example!
39 :-)
40 -}
41
42 module System.Console.GetOpt (
43 -- * GetOpt
44 getOpt, getOpt',
45 usageInfo,
46 ArgOrder(..),
47 OptDescr(..),
48 ArgDescr(..),
49
50 -- * Examples
51
52 -- |To hopefully illuminate the role of the different data structures,
53 -- here are the command-line options for a (very simple) compiler,
54 -- done in two different ways.
55 -- The difference arises because the type of 'getOpt' is
56 -- parameterized by the type of values derived from flags.
57
58 -- ** Interpreting flags as concrete values
59 -- $example1
60
61 -- ** Interpreting flags as transformations of an options record
62 -- $example2
63 ) where
64
65 import Prelude -- necessary to get dependencies right
66
67 import Data.List ( isPrefixOf, find )
68
69 -- |What to do with options following non-options
70 data ArgOrder a
71 = RequireOrder -- ^ no option processing after first non-option
72 | Permute -- ^ freely intersperse options and non-options
73 | ReturnInOrder (String -> a) -- ^ wrap non-options into options
74
75 {-|
76 Each 'OptDescr' describes a single option.
77
78 The arguments to 'Option' are:
79
80 * list of short option characters
81
82 * list of long option strings (without \"--\")
83
84 * argument descriptor
85
86 * explanation of option for user
87 -}
88 data OptDescr a = -- description of a single options:
89 Option [Char] -- list of short option characters
90 [String] -- list of long option strings (without "--")
91 (ArgDescr a) -- argument descriptor
92 String -- explanation of option for user
93
94 -- |Describes whether an option takes an argument or not, and if so
95 -- how the argument is injected into a value of type @a@.
96 data ArgDescr a
97 = NoArg a -- ^ no argument expected
98 | ReqArg (String -> a) String -- ^ option requires argument
99 | OptArg (Maybe String -> a) String -- ^ optional argument
100
101 data OptKind a -- kind of cmd line arg (internal use only):
102 = Opt a -- an option
103 | UnreqOpt String -- an un-recognized option
104 | NonOpt String -- a non-option
105 | EndOfOpts -- end-of-options marker (i.e. "--")
106 | OptErr String -- something went wrong...
107
108 -- | Return a string describing the usage of a command, derived from
109 -- the header (first argument) and the options described by the
110 -- second argument.
111 usageInfo :: String -- header
112 -> [OptDescr a] -- option descriptors
113 -> String -- nicely formatted decription of options
114 usageInfo header optDescr = unlines (header:table)
115 where (ss,ls,ds) = (unzip3 . concatMap fmtOpt) optDescr
116 table = zipWith3 paste (sameLen ss) (sameLen ls) ds
117 paste x y z = " " ++ x ++ " " ++ y ++ " " ++ z
118 sameLen xs = flushLeft ((maximum . map length) xs) xs
119 flushLeft n xs = [ take n (x ++ repeat ' ') | x <- xs ]
120
121 fmtOpt :: OptDescr a -> [(String,String,String)]
122 fmtOpt (Option sos los ad descr) =
123 case lines descr of
124 [] -> [(sosFmt,losFmt,"")]
125 (d:ds) -> (sosFmt,losFmt,d) : [ ("","",d') | d' <- ds ]
126 where sepBy _ [] = ""
127 sepBy _ [x] = x
128 sepBy ch (x:xs) = x ++ ch:' ':sepBy ch xs
129 sosFmt = sepBy ',' (map (fmtShort ad) sos)
130 losFmt = sepBy ',' (map (fmtLong ad) los)
131
132 fmtShort :: ArgDescr a -> Char -> String
133 fmtShort (NoArg _ ) so = "-" ++ [so]
134 fmtShort (ReqArg _ ad) so = "-" ++ [so] ++ " " ++ ad
135 fmtShort (OptArg _ ad) so = "-" ++ [so] ++ "[" ++ ad ++ "]"
136
137 fmtLong :: ArgDescr a -> String -> String
138 fmtLong (NoArg _ ) lo = "--" ++ lo
139 fmtLong (ReqArg _ ad) lo = "--" ++ lo ++ "=" ++ ad
140 fmtLong (OptArg _ ad) lo = "--" ++ lo ++ "[=" ++ ad ++ "]"
141
142 {-|
143 Process the command-line, and return the list of values that matched
144 (and those that didn\'t). The arguments are:
145
146 * The order requirements (see 'ArgOrder')
147
148 * The option descriptions (see 'OptDescr')
149
150 * The actual command line arguments (presumably got from
151 'System.Environment.getArgs').
152
153 'getOpt' returns a triple consisting of the option arguments, a list
154 of non-options, and a list of error messages.
155 -}
156 getOpt :: ArgOrder a -- non-option handling
157 -> [OptDescr a] -- option descriptors
158 -> [String] -- the command-line arguments
159 -> ([a],[String],[String]) -- (options,non-options,error messages)
160 getOpt ordering optDescr args = (os,xs,es ++ map errUnrec us)
161 where (os,xs,us,es) = getOpt' ordering optDescr args
162
163 {-|
164 This is almost the same as 'getOpt', but returns a quadruple
165 consisting of the option arguments, a list of non-options, a list of
166 unrecognized options, and a list of error messages.
167 -}
168 getOpt' :: ArgOrder a -- non-option handling
169 -> [OptDescr a] -- option descriptors
170 -> [String] -- the command-line arguments
171 -> ([a],[String], [String] ,[String]) -- (options,non-options,unrecognized,error messages)
172 getOpt' _ _ [] = ([],[],[],[])
173 getOpt' ordering optDescr (arg:args) = procNextOpt opt ordering
174 where procNextOpt (Opt o) _ = (o:os,xs,us,es)
175 procNextOpt (UnreqOpt u) _ = (os,xs,u:us,es)
176 procNextOpt (NonOpt x) RequireOrder = ([],x:rest,[],[])
177 procNextOpt (NonOpt x) Permute = (os,x:xs,us,es)
178 procNextOpt (NonOpt x) (ReturnInOrder f) = (f x :os, xs,us,es)
179 procNextOpt EndOfOpts RequireOrder = ([],rest,[],[])
180 procNextOpt EndOfOpts Permute = ([],rest,[],[])
181 procNextOpt EndOfOpts (ReturnInOrder f) = (map f rest,[],[],[])
182 procNextOpt (OptErr e) _ = (os,xs,us,e:es)
183
184 (opt,rest) = getNext arg args optDescr
185 (os,xs,us,es) = getOpt' ordering optDescr rest
186
187 -- take a look at the next cmd line arg and decide what to do with it
188 getNext :: String -> [String] -> [OptDescr a] -> (OptKind a,[String])
189 getNext ('-':'-':[]) rest _ = (EndOfOpts,rest)
190 getNext ('-':'-':xs) rest optDescr = longOpt xs rest optDescr
191 getNext ('-': x :xs) rest optDescr = shortOpt x xs rest optDescr
192 getNext a rest _ = (NonOpt a,rest)
193
194 -- handle long option
195 longOpt :: String -> [String] -> [OptDescr a] -> (OptKind a,[String])
196 longOpt ls rs optDescr = long ads arg rs
197 where (opt,arg) = break (=='=') ls
198 getWith p = [ o | o@(Option _ xs _ _) <- optDescr
199 , find (p opt) xs /= Nothing ]
200 exact = getWith (==)
201 options = if null exact then getWith isPrefixOf else exact
202 ads = [ ad | Option _ _ ad _ <- options ]
203 optStr = ("--"++opt)
204
205 long (_:_:_) _ rest = (errAmbig options optStr,rest)
206 long [NoArg a ] [] rest = (Opt a,rest)
207 long [NoArg _ ] ('=':_) rest = (errNoArg optStr,rest)
208 long [ReqArg _ d] [] [] = (errReq d optStr,[])
209 long [ReqArg f _] [] (r:rest) = (Opt (f r),rest)
210 long [ReqArg f _] ('=':xs) rest = (Opt (f xs),rest)
211 long [OptArg f _] [] rest = (Opt (f Nothing),rest)
212 long [OptArg f _] ('=':xs) rest = (Opt (f (Just xs)),rest)
213 long _ _ rest = (UnreqOpt ("--"++ls),rest)
214
215 -- handle short option
216 shortOpt :: Char -> String -> [String] -> [OptDescr a] -> (OptKind a,[String])
217 shortOpt y ys rs optDescr = short ads ys rs
218 where options = [ o | o@(Option ss _ _ _) <- optDescr, s <- ss, y == s ]
219 ads = [ ad | Option _ _ ad _ <- options ]
220 optStr = '-':[y]
221
222 short (_:_:_) _ rest = (errAmbig options optStr,rest)
223 short (NoArg a :_) [] rest = (Opt a,rest)
224 short (NoArg a :_) xs rest = (Opt a,('-':xs):rest)
225 short (ReqArg _ d:_) [] [] = (errReq d optStr,[])
226 short (ReqArg f _:_) [] (r:rest) = (Opt (f r),rest)
227 short (ReqArg f _:_) xs rest = (Opt (f xs),rest)
228 short (OptArg f _:_) [] rest = (Opt (f Nothing),rest)
229 short (OptArg f _:_) xs rest = (Opt (f (Just xs)),rest)
230 short [] [] rest = (UnreqOpt optStr,rest)
231 short [] xs rest = (UnreqOpt optStr,('-':xs):rest)
232
233 -- miscellaneous error formatting
234
235 errAmbig :: [OptDescr a] -> String -> OptKind a
236 errAmbig ods optStr = OptErr (usageInfo header ods)
237 where header = "option `" ++ optStr ++ "' is ambiguous; could be one of:"
238
239 errReq :: String -> String -> OptKind a
240 errReq d optStr = OptErr ("option `" ++ optStr ++ "' requires an argument " ++ d ++ "\n")
241
242 errUnrec :: String -> String
243 errUnrec optStr = "unrecognized option `" ++ optStr ++ "'\n"
244
245 errNoArg :: String -> OptKind a
246 errNoArg optStr = OptErr ("option `" ++ optStr ++ "' doesn't allow an argument\n")
247
248 {-
249 -----------------------------------------------------------------------------------------
250 -- and here a small and hopefully enlightening example:
251
252 data Flag = Verbose | Version | Name String | Output String | Arg String deriving Show
253
254 options :: [OptDescr Flag]
255 options =
256 [Option ['v'] ["verbose"] (NoArg Verbose) "verbosely list files",
257 Option ['V','?'] ["version","release"] (NoArg Version) "show version info",
258 Option ['o'] ["output"] (OptArg out "FILE") "use FILE for dump",
259 Option ['n'] ["name"] (ReqArg Name "USER") "only dump USER's files"]
260
261 out :: Maybe String -> Flag
262 out Nothing = Output "stdout"
263 out (Just o) = Output o
264
265 test :: ArgOrder Flag -> [String] -> String
266 test order cmdline = case getOpt order options cmdline of
267 (o,n,[] ) -> "options=" ++ show o ++ " args=" ++ show n ++ "\n"
268 (_,_,errs) -> concat errs ++ usageInfo header options
269 where header = "Usage: foobar [OPTION...] files..."
270
271 -- example runs:
272 -- putStr (test RequireOrder ["foo","-v"])
273 -- ==> options=[] args=["foo", "-v"]
274 -- putStr (test Permute ["foo","-v"])
275 -- ==> options=[Verbose] args=["foo"]
276 -- putStr (test (ReturnInOrder Arg) ["foo","-v"])
277 -- ==> options=[Arg "foo", Verbose] args=[]
278 -- putStr (test Permute ["foo","--","-v"])
279 -- ==> options=[] args=["foo", "-v"]
280 -- putStr (test Permute ["-?o","--name","bar","--na=baz"])
281 -- ==> options=[Version, Output "stdout", Name "bar", Name "baz"] args=[]
282 -- putStr (test Permute ["--ver","foo"])
283 -- ==> option `--ver' is ambiguous; could be one of:
284 -- -v --verbose verbosely list files
285 -- -V, -? --version, --release show version info
286 -- Usage: foobar [OPTION...] files...
287 -- -v --verbose verbosely list files
288 -- -V, -? --version, --release show version info
289 -- -o[FILE] --output[=FILE] use FILE for dump
290 -- -n USER --name=USER only dump USER's files
291 -----------------------------------------------------------------------------------------
292 -}
293
294 {- $example1
295
296 A simple choice for the type associated with flags is to define a type
297 @Flag@ as an algebraic type representing the possible flags and their
298 arguments:
299
300 > module Opts1 where
301 >
302 > import System.Console.GetOpt
303 > import Data.Maybe ( fromMaybe )
304 >
305 > data Flag
306 > = Verbose | Version
307 > | Input String | Output String | LibDir String
308 > deriving Show
309 >
310 > options :: [OptDescr Flag]
311 > options =
312 > [ Option ['v'] ["verbose"] (NoArg Verbose) "chatty output on stderr"
313 > , Option ['V','?'] ["version"] (NoArg Version) "show version number"
314 > , Option ['o'] ["output"] (OptArg outp "FILE") "output FILE"
315 > , Option ['c'] [] (OptArg inp "FILE") "input FILE"
316 > , Option ['L'] ["libdir"] (ReqArg LibDir "DIR") "library directory"
317 > ]
318 >
319 > inp,outp :: Maybe String -> Flag
320 > outp = Output . fromMaybe "stdout"
321 > inp = Input . fromMaybe "stdin"
322 >
323 > compilerOpts :: [String] -> IO ([Flag], [String])
324 > compilerOpts argv =
325 > case getOpt Permute options argv of
326 > (o,n,[] ) -> return (o,n)
327 > (_,_,errs) -> ioError (userError (concat errs ++ usageInfo header options))
328 > where header = "Usage: ic [OPTION...] files..."
329
330 Then the rest of the program will use the constructed list of flags
331 to determine it\'s behaviour.
332
333 -}
334
335 {- $example2
336
337 A different approach is to group the option values in a record of type
338 @Options@, and have each flag yield a function of type
339 @Options -> Options@ transforming this record.
340
341 > module Opts2 where
342 >
343 > import System.Console.GetOpt
344 > import Data.Maybe ( fromMaybe )
345 >
346 > data Options = Options
347 > { optVerbose :: Bool
348 > , optShowVersion :: Bool
349 > , optOutput :: Maybe FilePath
350 > , optInput :: Maybe FilePath
351 > , optLibDirs :: [FilePath]
352 > } deriving Show
353 >
354 > defaultOptions = Options
355 > { optVerbose = False
356 > , optShowVersion = False
357 > , optOutput = Nothing
358 > , optInput = Nothing
359 > , optLibDirs = []
360 > }
361 >
362 > options :: [OptDescr (Options -> Options)]
363 > options =
364 > [ Option ['v'] ["verbose"]
365 > (NoArg (\ opts -> opts { optVerbose = True }))
366 > "chatty output on stderr"
367 > , Option ['V','?'] ["version"]
368 > (NoArg (\ opts -> opts { optShowVersion = True }))
369 > "show version number"
370 > , Option ['o'] ["output"]
371 > (OptArg ((\ f opts -> opts { optOutput = Just f }) . fromMaybe "output")
372 > "FILE")
373 > "output FILE"
374 > , Option ['c'] []
375 > (OptArg ((\ f opts -> opts { optInput = Just f }) . fromMaybe "input")
376 > "FILE")
377 > "input FILE"
378 > , Option ['L'] ["libdir"]
379 > (ReqArg (\ d opts -> opts { optLibDirs = optLibDirs opts ++ [d] }) "DIR")
380 > "library directory"
381 > ]
382 >
383 > compilerOpts :: [String] -> IO (Options, [String])
384 > compilerOpts argv =
385 > case getOpt Permute options argv of
386 > (o,n,[] ) -> return (foldl (flip id) defaultOptions o, n)
387 > (_,_,errs) -> ioError (userError (concat errs ++ usageInfo header options))
388 > where header = "Usage: ic [OPTION...] files..."
389
390 Similarly, each flag could yield a monadic function transforming a record,
391 of type @Options -> IO Options@ (or any other monad), allowing option
392 processing to perform actions of the chosen monad, e.g. printing help or
393 version messages, checking that file arguments exist, etc.
394
395 -}
396