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