[project @ 1998-12-02 13:17:09 by simonm]
[ghc-hetmet.git] / ghc / lib / exts / GetOpt.lhs
1 A Haskell port of GNU's getopt library 
2
3 Sven Panne <Sven.Panne@informatik.uni-muenchen.de> Oct. 1996 (small
4 changes Dec. 1997)
5
6 Two rather obscure features are missing: The Bash 2.0 non-option hack
7 (if you don't already know it, you probably don't want to hear about
8 it...) and the recognition of long options with a single dash
9 (e.g. '-help' is recognised as '--help', as long as there is no short
10 option 'h').
11
12 Other differences between GNU's getopt and this implementation: * To
13 enforce a coherent description of options and arguments, there are
14 explanation fields in the option/argument descriptor.  * Error
15 messages are now more informative, but no longer POSIX
16 compliant... :-( And a final Haskell advertisement: The GNU C
17 implementation uses well over 1100 lines, we need only 195 here,
18 including a 46 line example! :-)
19
20 \begin{code}
21 module GetOpt (ArgOrder(..), OptDescr(..), ArgDescr(..), usageInfo, getOpt) where
22
23 import List(isPrefixOf)
24
25 data ArgOrder a                        -- what to do with options following non-options:
26    = RequireOrder                      --    no option processing after first non-option
27    | Permute                           --    freely intersperse options and non-options
28    | ReturnInOrder (String -> a)       --    wrap non-options into options
29
30 data OptDescr a =                      -- description of a single options:
31    Option [Char]                       --    list of short option characters
32           [String]                     --    list of long option strings (without "--")
33           (ArgDescr a)                 --    argument descriptor
34           String                       --    explanation of option for user
35
36 data ArgDescr a                        -- description of an argument option:
37    = NoArg                   a         --    no argument expected
38    | ReqArg (String       -> a) String --    option requires argument
39    | OptArg (Maybe String -> a) String --    optional argument
40
41 data OptKind a                         -- kind of cmd line arg (internal use only):
42    = Opt       a                       --    an option
43    | NonOpt    String                  --    a non-option
44    | EndOfOpts                         --    end-of-options marker (i.e. "--")
45    | OptErr    String                  --    something went wrong...
46
47 usageInfo :: String                    -- header
48           -> [OptDescr a]              -- option descriptors
49           -> String                    -- nicely formatted decription of options
50 usageInfo header optDescr = unlines (header:table)
51    where (ss,ls,ds)     = (unzip3 . map fmtOpt) optDescr
52          table          = zipWith3 paste (sameLen ss) (sameLen ls) (sameLen ds)
53          paste x y z    = "  " ++ x ++ "  " ++ y ++ "  " ++ z
54          sameLen xs     = flushLeft ((maximum . map length) xs) xs
55          flushLeft n xs = [ take n (x ++ repeat ' ') | x <- xs ]
56
57 fmtOpt :: OptDescr a -> (String,String,String)
58 fmtOpt (Option sos los ad descr) = (sepBy ", " (map (fmtShort ad) sos),
59                                     sepBy ", " (map (fmtLong  ad) los),
60                                     descr)
61    where sepBy sep []     = ""
62          sepBy sep [x]    = x
63          sepBy sep (x:xs) = x ++ sep ++ sepBy sep xs
64
65 fmtShort :: ArgDescr a -> Char -> String
66 fmtShort (NoArg  _   ) so = "-" ++ [so]
67 fmtShort (ReqArg _ ad) so = "-" ++ [so] ++ " " ++ ad
68 fmtShort (OptArg _ ad) so = "-" ++ [so] ++ "[" ++ ad ++ "]"
69
70 fmtLong :: ArgDescr a -> String -> String
71 fmtLong (NoArg  _   ) lo = "--" ++ lo
72 fmtLong (ReqArg _ ad) lo = "--" ++ lo ++ "=" ++ ad
73 fmtLong (OptArg _ ad) lo = "--" ++ lo ++ "[=" ++ ad ++ "]"
74
75 getOpt :: ArgOrder a                   -- non-option handling
76        -> [OptDescr a]                 -- option descriptors
77        -> [String]                     -- the commandline arguments
78        -> ([a],[String],[String])      -- (options,non-options,error messages)
79 getOpt _        _        []         =  ([],[],[])
80 getOpt ordering optDescr (arg:args) = procNextOpt opt ordering
81    where procNextOpt (Opt o)    _                 = (o:os,xs,es)
82          procNextOpt (NonOpt x) RequireOrder      = ([],x:rest,[])
83          procNextOpt (NonOpt x) Permute           = (os,x:xs,es)
84          procNextOpt (NonOpt x) (ReturnInOrder f) = (f x :os, xs,es)
85          procNextOpt EndOfOpts  RequireOrder      = ([],rest,[])
86          procNextOpt EndOfOpts  Permute           = ([],rest,[])
87          procNextOpt EndOfOpts  (ReturnInOrder f) = (map f rest,[],[])
88          procNextOpt (OptErr e) _                 = (os,xs,e:es)
89
90          (opt,rest) = getNext arg args optDescr
91          (os,xs,es) = getOpt ordering optDescr rest
92
93 -- take a look at the next cmd line arg and decide what to do with it
94 getNext :: String -> [String] -> [OptDescr a] -> (OptKind a,[String])
95 getNext ('-':'-':[]) rest _        = (EndOfOpts,rest)
96 getNext ('-':'-':xs) rest optDescr = longOpt xs rest optDescr
97 getNext ('-': x :xs) rest optDescr = shortOpt x xs rest optDescr
98 getNext a            rest _        = (NonOpt a,rest)
99
100 -- handle long option
101 longOpt :: String -> [String] -> [OptDescr a] -> (OptKind a,[String])
102 longOpt xs rest optDescr = long ads arg rest
103    where (opt,arg) = break (=='=') xs
104          options   = [ o  | o@(Option _ ls _ _) <- optDescr, l <- ls, opt `isPrefixOf` l ]
105          ads       = [ ad | Option _ _ ad _ <- options ]
106          optStr    = ("--"++opt)
107
108          long (_:_:_)      _        rest     = (errAmbig options optStr,rest)
109          long [NoArg  a  ] []       rest     = (Opt a,rest)
110          long [NoArg  a  ] ('=':xs) rest     = (errNoArg optStr,rest)
111          long [ReqArg f d] []       []       = (errReq d optStr,[])
112          long [ReqArg f _] []       (r:rest) = (Opt (f r),rest)
113          long [ReqArg f _] ('=':xs) rest     = (Opt (f xs),rest)
114          long [OptArg f _] []       rest     = (Opt (f Nothing),rest)
115          long [OptArg f _] ('=':xs) rest     = (Opt (f (Just xs)),rest)
116          long _            _        rest     = (errUnrec optStr,rest)
117
118 -- handle short option
119 shortOpt :: Char -> String -> [String] -> [OptDescr a] -> (OptKind a,[String])
120 shortOpt x xs rest optDescr = short ads xs rest
121   where options = [ o  | o@(Option ss _ _ _) <- optDescr, s <- ss, x == s ]
122         ads     = [ ad | Option _ _ ad _ <- options ]
123         optStr  = '-':[x]
124
125         short (_:_:_)        _  rest     = (errAmbig options optStr,rest)
126         short (NoArg  a  :_) [] rest     = (Opt a,rest)
127         short (NoArg  a  :_) xs rest     = (Opt a,('-':xs):rest)
128         short (ReqArg f d:_) [] []       = (errReq d optStr,[])
129         short (ReqArg f _:_) [] (r:rest) = (Opt (f r),rest)
130         short (ReqArg f _:_) xs rest     = (Opt (f xs),rest)
131         short (OptArg f _:_) [] rest     = (Opt (f Nothing),rest)
132         short (OptArg f _:_) xs rest     = (Opt (f (Just xs)),rest)
133         short []             [] rest     = (errUnrec optStr,rest)
134         short []             xs rest     = (errUnrec optStr,('-':xs):rest)
135
136 -- miscellaneous error formatting
137
138 errAmbig :: [OptDescr a] -> String -> OptKind a
139 errAmbig ods optStr = OptErr (usageInfo header ods)
140    where header = "option `" ++ optStr ++ "' is ambiguous; could be one of:"
141
142 errReq :: String -> String -> OptKind a
143 errReq d optStr = OptErr ("option `" ++ optStr ++ "' requires an argument " ++ d ++ "\n")
144
145 errUnrec :: String -> OptKind a
146 errUnrec optStr = OptErr ("unrecognized option `" ++ optStr ++ "'\n")
147
148 errNoArg :: String -> OptKind a
149 errNoArg optStr = OptErr ("option `" ++ optStr ++ "' doesn't allow an argument\n")
150
151 {-
152 -----------------------------------------------------------------------------------------
153 -- and here a small and hopefully enlightening example:
154
155 data Flag = Verbose | Version | Name String | Output String | Arg String   deriving Show
156
157 options :: [OptDescr Flag]
158 options =
159    [Option ['v']     ["verbose"]           (NoArg Verbose)      "verbosely list files",
160     Option ['V','?'] ["version","release"] (NoArg Version)      "show version info",
161     Option ['o']     ["output"]            (OptArg out "FILE")  "use FILE for dump",
162     Option ['n']     ["name"]              (ReqArg Name "USER") "only dump USER's files"]
163
164 out :: Maybe String -> Flag
165 out Nothing  = Output "stdout"
166 out (Just o) = Output o
167
168 test :: ArgOrder Flag -> [String] -> String
169 test order cmdline = case getOpt order options cmdline of
170                         (o,n,[]  ) -> "options=" ++ show o ++ "  args=" ++ show n ++ "\n"
171                         (_,_,errs) -> concat errs ++ usageInfo header options
172    where header = "Usage: foobar [OPTION...] files..."
173
174 -- example runs:
175 -- putStr (test RequireOrder ["foo","-v"])
176 --    ==> options=[]  args=["foo", "-v"]
177 -- putStr (test Permute ["foo","-v"])
178 --    ==> options=[Verbose]  args=["foo"]
179 -- putStr (test (ReturnInOrder Arg) ["foo","-v"])
180 --    ==> options=[Arg "foo", Verbose]  args=[]
181 -- putStr (test Permute ["foo","--","-v"])
182 --    ==> options=[]  args=["foo", "-v"]
183 -- putStr (test Permute ["-?o","--name","bar","--na=baz"])
184 --    ==> options=[Version, Output "stdout", Name "bar", Name "baz"]  args=[]
185 -- putStr (test Permute ["--ver","foo"])
186 --    ==> option `--ver' is ambiguous; could be one of:
187 --          -v      --verbose             verbosely list files
188 --          -V, -?  --version, --release  show version info   
189 --        Usage: foobar [OPTION...] files...
190 --          -v        --verbose             verbosely list files  
191 --          -V, -?    --version, --release  show version info     
192 --          -o[FILE]  --output[=FILE]       use FILE for dump     
193 --          -n USER   --name=USER           only dump USER's files
194 -----------------------------------------------------------------------------------------
195 -}
196 \end{code}