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