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