4098c30e78b04da1b0264f20a843b186f9c9e310
[ghc-base.git] / System / Console / GetOpt.hs
1 -----------------------------------------------------------------------------
2 -- |
3 -- Module      :  System.Console.GetOpt
4 -- Copyright   :  (c) Sven Panne 2002-2005
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, getOpt',
43    usageInfo,
44    ArgOrder(..),
45    OptDescr(..),
46    ArgDescr(..),
47
48    -- * Example
49
50    -- $example
51 ) where
52
53 import Prelude -- necessary to get dependencies right
54
55 import Data.List ( isPrefixOf )
56
57 -- |What to do with options following non-options
58 data ArgOrder a
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
62
63 {-|
64 Each 'OptDescr' describes a single option.
65
66 The arguments to 'Option' are:
67
68 * list of short option characters
69
70 * list of long option strings (without \"--\")
71
72 * argument descriptor
73
74 * explanation of option for user
75 -}
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
81
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@.
84 data ArgDescr a
85    = NoArg                   a         -- ^   no argument expected
86    | ReqArg (String       -> a) String -- ^   option requires argument
87    | OptArg (Maybe String -> a) String -- ^   optional argument
88
89 data OptKind a                -- kind of cmd line arg (internal use only):
90    = Opt       a                --    an option
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...
95
96 -- | Return a string describing the usage of a command, derived from
97 -- the header (first argument) and the options described by the 
98 -- second argument.
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 ]
108
109 fmtOpt :: OptDescr a -> [(String,String,String)]
110 fmtOpt (Option sos los ad descr) =
111    case lines descr of
112      []     -> [(sosFmt,losFmt,"")]
113      (d:ds) ->  (sosFmt,losFmt,d) : [ ("","",d') | d' <- ds ]
114    where sepBy _  []     = ""
115          sepBy _  [x]    = x
116          sepBy ch (x:xs) = x ++ ch:' ':sepBy ch xs
117          sosFmt = sepBy ',' (map (fmtShort ad) sos)
118          losFmt = sepBy ',' (map (fmtLong  ad) los)
119
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 ++ "]"
124
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 ++ "]"
129
130 {-|
131 Process the command-line, and return the list of values that matched
132 (and those that didn\'t). The arguments are:
133
134 * The order requirements (see 'ArgOrder')
135
136 * The option descriptions (see 'OptDescr')
137
138 * The actual command line arguments (presumably got from 
139   'System.Environment.getArgs').
140
141 'getOpt' returns a triple consisting of the option arguments, a list
142 of non-options, and a list of error messages.
143 -}
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
150
151 {-|
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.
155 -}
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)
171
172          (opt,rest) = getNext arg args optDescr
173          (os,xs,us,es) = getOpt' ordering optDescr rest
174
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)
181
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 ]
187          exact     = getWith (==)
188          options   = if null exact then getWith isPrefixOf else exact
189          ads       = [ ad | Option _ _ ad _ <- options ]
190          optStr    = ("--"++opt)
191
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 optStr,rest)
201
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 ]
207         optStr  = '-':[y]
208
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)
219
220 -- miscellaneous error formatting
221
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:"
225
226 errReq :: String -> String -> OptKind a
227 errReq d optStr = OptErr ("option `" ++ optStr ++ "' requires an argument " ++ d ++ "\n")
228
229 errUnrec :: String -> String
230 errUnrec optStr = "unrecognized option `" ++ optStr ++ "'\n"
231
232 errNoArg :: String -> OptKind a
233 errNoArg optStr = OptErr ("option `" ++ optStr ++ "' doesn't allow an argument\n")
234
235 {-
236 -----------------------------------------------------------------------------------------
237 -- and here a small and hopefully enlightening example:
238
239 data Flag = Verbose | Version | Name String | Output String | Arg String   deriving Show
240
241 options :: [OptDescr Flag]
242 options =
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"]
247
248 out :: Maybe String -> Flag
249 out Nothing  = Output "stdout"
250 out (Just o) = Output o
251
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..."
257
258 -- example runs:
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 -----------------------------------------------------------------------------------------
279 -}
280
281 {- $example
282
283 To hopefully illuminate the role of the different data
284 structures, here\'s the command-line options for a (very simple)
285 compiler:
286
287 >    module Opts where
288 >    
289 >    import System.Console.GetOpt
290 >    import Data.Maybe ( fromMaybe )
291 >    
292 >    data Flag 
293 >     = Verbose  | Version 
294 >     | Input String | Output String | LibDir String
295 >       deriving Show
296 >    
297 >    options :: [OptDescr Flag]
298 >    options =
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"
304 >     ]
305 >    
306 >    inp,outp :: Maybe String -> Flag
307 >    outp = Output . fromMaybe "stdout"
308 >    inp  = Input  . fromMaybe "stdin"
309 >    
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..."
316
317 -}