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