[project @ 2003-03-08 23:03:47 by panne]
[packages/old-time.git] / System / Console / GetOpt.hs
1 -----------------------------------------------------------------------------
2 -- |
3 -- Module : System.Console.GetOpt
4 -- Copyright : (c) Sven Panne Oct. 1996 (small changes Feb. 2003)
5 -- License : BSD-style (see the file libraries/base/LICENSE)
6 --
7 -- Maintainer : libraries@haskell.org
8 -- Stability : experimental
9 -- Portability : portable
10 --
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
13 -- @getopt@ library.
14 --
15 -----------------------------------------------------------------------------
16
17 {-
18 Sven Panne <Sven.Panne@informatik.uni-muenchen.de> Oct. 1996 (small
19 changes Dec. 1997)
20
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
25 option 'h').
26
27 Other differences between GNU's getopt and this implementation:
28
29 * To enforce a coherent description of options and arguments, there
30 are explanation fields in the option/argument descriptor.
31
32 * Error messages are now more informative, but no longer POSIX
33 compliant... :-(
34
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!
37 :-)
38 -}
39
40 module System.Console.GetOpt (
41 -- * GetOpt
42 getOpt,
43 usageInfo,
44 ArgOrder(..),
45 OptDescr(..),
46 ArgDescr(..),
47
48 -- * Example
49
50 -- $example
51 ) where
52
53 import Prelude
54 import Data.List ( isPrefixOf )
55
56 -- |What to do with options following non-options
57 data ArgOrder a
58 = RequireOrder -- ^ no option processing after first non-option
59 | Permute -- ^ freely intersperse options and non-options
60 | ReturnInOrder (String -> a) -- ^ wrap non-options into options
61
62 {-|
63 Each 'OptDescr' describes a single option.
64
65 The arguments to 'Option' are:
66
67 * list of short option characters
68
69 * list of long option strings (without \"--\")
70
71 * argument descriptor
72
73 * explanation of option for user
74 -}
75 data OptDescr a = -- description of a single options:
76 Option [Char] -- list of short option characters
77 [String] -- list of long option strings (without "--")
78 (ArgDescr a) -- argument descriptor
79 String -- explanation of option for user
80
81 -- |Describes whether an option takes an argument or not, and if so
82 -- how the argument is injected into a value of type @a@.
83 data ArgDescr a
84 = NoArg a -- ^ no argument expected
85 | ReqArg (String -> a) String -- ^ option requires argument
86 | OptArg (Maybe String -> a) String -- ^ optional argument
87
88 data OptKind a -- kind of cmd line arg (internal use only):
89 = Opt a -- an option
90 | NonOpt String -- a non-option
91 | EndOfOpts -- end-of-options marker (i.e. "--")
92 | OptErr String -- something went wrong...
93
94 -- | Return a string describing the usage of a command, derived from
95 -- the header (first argument) and the options described by the
96 -- second argument.
97 usageInfo :: String -- header
98 -> [OptDescr a] -- option descriptors
99 -> String -- nicely formatted decription of options
100 usageInfo header optDescr = unlines (header:table)
101 where (ss,ls,ds) = (unzip3 . map fmtOpt) optDescr
102 table = zipWith3 paste (sameLen ss) (sameLen ls) ds
103 paste x y z = " " ++ x ++ " " ++ y ++ " " ++ z
104 sameLen xs = flushLeft ((maximum . map length) xs) xs
105 flushLeft n xs = [ take n (x ++ repeat ' ') | x <- xs ]
106
107 fmtOpt :: OptDescr a -> (String,String,String)
108 fmtOpt (Option sos los ad descr) = (sepBy ',' (map (fmtShort ad) sos),
109 sepBy ',' (map (fmtLong ad) los),
110 descr)
111 where sepBy _ [] = ""
112 sepBy _ [x] = x
113 sepBy ch (x:xs) = x ++ ch:' ':sepBy ch xs
114
115 fmtShort :: ArgDescr a -> Char -> String
116 fmtShort (NoArg _ ) so = "-" ++ [so]
117 fmtShort (ReqArg _ ad) so = "-" ++ [so] ++ " " ++ ad
118 fmtShort (OptArg _ ad) so = "-" ++ [so] ++ "[" ++ ad ++ "]"
119
120 fmtLong :: ArgDescr a -> String -> String
121 fmtLong (NoArg _ ) lo = "--" ++ lo
122 fmtLong (ReqArg _ ad) lo = "--" ++ lo ++ "=" ++ ad
123 fmtLong (OptArg _ ad) lo = "--" ++ lo ++ "[=" ++ ad ++ "]"
124
125 {-|
126 Process the command-line, and return the list of values that matched
127 (and those that didn\'t). The arguments are:
128
129 * The order requirements (see 'ArgOrder')
130
131 * The option descriptions (see 'OptDescr')
132
133 * The actual command line arguments (presumably got from
134 'System.Console.Environment.getArgs').
135
136 'getOpt' returns a triple, consisting of the argument values, a list
137 of options that didn\'t match, and a list of error messages.
138 -}
139 getOpt :: ArgOrder a -- non-option handling
140 -> [OptDescr a] -- option descriptors
141 -> [String] -- the commandline arguments
142 -> ([a],[String],[String]) -- (options,non-options,error messages)
143 getOpt _ _ [] = ([],[],[])
144 getOpt ordering optDescr (arg:args) = procNextOpt opt ordering
145 where procNextOpt (Opt o) _ = (o:os,xs,es)
146 procNextOpt (NonOpt x) RequireOrder = ([],x:rest,[])
147 procNextOpt (NonOpt x) Permute = (os,x:xs,es)
148 procNextOpt (NonOpt x) (ReturnInOrder f) = (f x :os, xs,es)
149 procNextOpt EndOfOpts RequireOrder = ([],rest,[])
150 procNextOpt EndOfOpts Permute = ([],rest,[])
151 procNextOpt EndOfOpts (ReturnInOrder f) = (map f rest,[],[])
152 procNextOpt (OptErr e) _ = (os,xs,e:es)
153
154 (opt,rest) = getNext arg args optDescr
155 (os,xs,es) = getOpt ordering optDescr rest
156
157 -- take a look at the next cmd line arg and decide what to do with it
158 getNext :: String -> [String] -> [OptDescr a] -> (OptKind a,[String])
159 getNext ('-':'-':[]) rest _ = (EndOfOpts,rest)
160 getNext ('-':'-':xs) rest optDescr = longOpt xs rest optDescr
161 getNext ('-': x :xs) rest optDescr = shortOpt x xs rest optDescr
162 getNext a rest _ = (NonOpt a,rest)
163
164 -- handle long option
165 longOpt :: String -> [String] -> [OptDescr a] -> (OptKind a,[String])
166 longOpt ls rs optDescr = long ads arg rs
167 where (opt,arg) = break (=='=') ls
168 getWith p = [ o | o@(Option _ ls _ _) <- optDescr, l <- ls, opt `p` l ]
169 exact = getWith (==)
170 options = if null exact then getWith isPrefixOf else exact
171 ads = [ ad | Option _ _ ad _ <- options ]
172 optStr = ("--"++opt)
173
174 long (_:_:_) _ rest = (errAmbig options optStr,rest)
175 long [NoArg a ] [] rest = (Opt a,rest)
176 long [NoArg _ ] ('=':_) rest = (errNoArg optStr,rest)
177 long [ReqArg _ d] [] [] = (errReq d optStr,[])
178 long [ReqArg f _] [] (r:rest) = (Opt (f r),rest)
179 long [ReqArg f _] ('=':xs) rest = (Opt (f xs),rest)
180 long [OptArg f _] [] rest = (Opt (f Nothing),rest)
181 long [OptArg f _] ('=':xs) rest = (Opt (f (Just xs)),rest)
182 long _ _ rest = (errUnrec optStr,rest)
183
184 -- handle short option
185 shortOpt :: Char -> String -> [String] -> [OptDescr a] -> (OptKind a,[String])
186 shortOpt x xs rest optDescr = short ads xs rest
187 where options = [ o | o@(Option ss _ _ _) <- optDescr, s <- ss, x == s ]
188 ads = [ ad | Option _ _ ad _ <- options ]
189 optStr = '-':[x]
190
191 short (_:_:_) _ rest = (errAmbig options optStr,rest)
192 short (NoArg a :_) [] rest = (Opt a,rest)
193 short (NoArg a :_) xs rest = (Opt a,('-':xs):rest)
194 short (ReqArg _ d:_) [] [] = (errReq d optStr,[])
195 short (ReqArg f _:_) [] (r:rest) = (Opt (f r),rest)
196 short (ReqArg f _:_) xs rest = (Opt (f xs),rest)
197 short (OptArg f _:_) [] rest = (Opt (f Nothing),rest)
198 short (OptArg f _:_) xs rest = (Opt (f (Just xs)),rest)
199 short [] [] rest = (errUnrec optStr,rest)
200 short [] xs rest = (errUnrec optStr,('-':xs):rest)
201
202 -- miscellaneous error formatting
203
204 errAmbig :: [OptDescr a] -> String -> OptKind a
205 errAmbig ods optStr = OptErr (usageInfo header ods)
206 where header = "option `" ++ optStr ++ "' is ambiguous; could be one of:"
207
208 errReq :: String -> String -> OptKind a
209 errReq d optStr = OptErr ("option `" ++ optStr ++ "' requires an argument " ++ d ++ "\n")
210
211 errUnrec :: String -> OptKind a
212 errUnrec optStr = OptErr ("unrecognized option `" ++ optStr ++ "'\n")
213
214 errNoArg :: String -> OptKind a
215 errNoArg optStr = OptErr ("option `" ++ optStr ++ "' doesn't allow an argument\n")
216
217 {-
218 -----------------------------------------------------------------------------------------
219 -- and here a small and hopefully enlightening example:
220
221 data Flag = Verbose | Version | Name String | Output String | Arg String deriving Show
222
223 options :: [OptDescr Flag]
224 options =
225 [Option ['v'] ["verbose"] (NoArg Verbose) "verbosely list files",
226 Option ['V','?'] ["version","release"] (NoArg Version) "show version info",
227 Option ['o'] ["output"] (OptArg out "FILE") "use FILE for dump",
228 Option ['n'] ["name"] (ReqArg Name "USER") "only dump USER's files"]
229
230 out :: Maybe String -> Flag
231 out Nothing = Output "stdout"
232 out (Just o) = Output o
233
234 test :: ArgOrder Flag -> [String] -> String
235 test order cmdline = case getOpt order options cmdline of
236 (o,n,[] ) -> "options=" ++ show o ++ " args=" ++ show n ++ "\n"
237 (_,_,errs) -> concat errs ++ usageInfo header options
238 where header = "Usage: foobar [OPTION...] files..."
239
240 -- example runs:
241 -- putStr (test RequireOrder ["foo","-v"])
242 -- ==> options=[] args=["foo", "-v"]
243 -- putStr (test Permute ["foo","-v"])
244 -- ==> options=[Verbose] args=["foo"]
245 -- putStr (test (ReturnInOrder Arg) ["foo","-v"])
246 -- ==> options=[Arg "foo", Verbose] args=[]
247 -- putStr (test Permute ["foo","--","-v"])
248 -- ==> options=[] args=["foo", "-v"]
249 -- putStr (test Permute ["-?o","--name","bar","--na=baz"])
250 -- ==> options=[Version, Output "stdout", Name "bar", Name "baz"] args=[]
251 -- putStr (test Permute ["--ver","foo"])
252 -- ==> option `--ver' is ambiguous; could be one of:
253 -- -v --verbose verbosely list files
254 -- -V, -? --version, --release show version info
255 -- Usage: foobar [OPTION...] files...
256 -- -v --verbose verbosely list files
257 -- -V, -? --version, --release show version info
258 -- -o[FILE] --output[=FILE] use FILE for dump
259 -- -n USER --name=USER only dump USER's files
260 -----------------------------------------------------------------------------------------
261 -}
262
263 {- $example
264
265 To hopefully illuminate the role of the different data
266 structures, here\'s the command-line options for a (very simple)
267 compiler:
268
269 > module Opts where
270 >
271 > import System.Console.GetOpt
272 > import Data.Maybe ( fromMaybe )
273 >
274 > data Flag
275 > = Verbose | Version
276 > | Input String | Output String | LibDir String
277 > deriving Show
278 >
279 > options :: [OptDescr Flag]
280 > options =
281 > [ Option ['v'] ["verbose"] (NoArg Verbose) "chatty output on stderr"
282 > , Option ['V','?'] ["version"] (NoArg Version) "show version number"
283 > , Option ['o'] ["output"] (OptArg outp "FILE") "output FILE"
284 > , Option ['c'] [] (OptArg inp "FILE") "input FILE"
285 > , Option ['L'] ["libdir"] (ReqArg LibDir "DIR") "library directory"
286 > ]
287 >
288 > inp,outp :: Maybe String -> Flag
289 > outp = Output . fromMaybe "stdout"
290 > inp = Input . fromMaybe "stdout"
291 >
292 > compilerOpts :: [String] -> IO ([Flag], [String])
293 > compilerOpts argv =
294 > case (getOpt Permute options argv) of
295 > (o,n,[] ) -> return (o,n)
296 > (_,_,errs) -> ioError (userError (concat errs ++ usageInfo header options))
297 > where header = "Usage: ic [OPTION...] files..."
298
299 -}