2 <label id="sec:GetOpt">
5 The <tt/GetOpt/ library contains Sven Panne's Haskell implementation
6 of <tt/getopt/, providing features nigh-on identical to GNU <tt/getopt/:
11 -- representing a single option:
13 = Option [Char] -- list of short option characters
14 [String] -- list of long option strings (without "--")
15 (ArgDescr a) -- argument descriptor
16 String -- explanation of option for user
20 = NoArg a -- no argument expected
21 | ReqArg (String -> a) String -- option requires argument
22 | OptArg (Maybe String -> a) String -- optional argument
24 usageInfo :: String -- header
25 -> [OptDescr a] -- options recognised
26 -> String -- nicely formatted decription of options
28 getOpt :: ArgOrder a -- non-option handling
29 -> [OptDescr a] -- options recognised
30 -> [String] -- the command-line
32 , [String] -- non-options
33 ,[String] -- error messages
39 | ReturnInOrder (String -> a)
44 <item> The command-line options recognised is described by a list of
45 <tt/OptDescr/ values. The <tt/OptDescr/ describes the long and short
46 strings that recognise the option, together with a help string and
47 info on whether the option takes extra arguments, if any.
49 From a list of option values, <tt/usageInfo/ returns a nicely
50 formatted string that enumerates the different options supported
51 together with a short message about what
53 To decode a command-line with respect to a list of options,
54 <tt/getOpt/ is used. It processes the command-line, and returns
55 the list of values that matched (and those that didn't). The first
56 argument to <tt/getOpt/ controls whether the user is to give the
57 options in any old order or not.
60 To hopefully illuminate the role of the different <tt/GetOpt/ data
61 structures, here's the command-line options for a (very simple)
68 import Maybe ( fromMaybe )
72 | Input String | Output String | LibDir String
75 options :: [OptDescr Flag]
77 [ Option ['v'] ["verbose"] (NoArg Verbose) "chatty output on stderr"
78 , Option ['V','?'] ["version"] (NoArg Version) "show version number"
79 , Option ['o'] ["output"] (OptArg outp "FILE") "output FILE"
80 , Option ['c'] [] (OptArg inp "FILE") "input FILE"
81 , Option ['L'] ["libdir"] (ReqArg LibDir "DIR") "library directory"
84 inp,outp :: Maybe String -> Flag
85 outp = Output . fromMaybe "stdout"
86 inp = Input . fromMaybe "stdout"
88 compilerOpts :: [String] -> IO ([Flag], [String])
90 case (getOpt Permute options argv) of
91 (o,n,[] ) -> return (o,n)
92 (_,_,errs) -> fail (userError (concat errs ++ usageInfo header options))
93 where header = "Usage: ic [OPTION...] files..."