1aa1b7effc16842551e65f174ec70c20f110f483
[packages/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/core/LICENSE)
6 --
7 -- Maintainer : libraries@haskell.org
8 -- Stability : experimental
9 -- Portability : portable
10 --
11 -- $Id: GetOpt.hs,v 1.2 2001/07/04 11:30:52 simonmar Exp $
12 --
13 -- A Haskell port of GNU's 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 ArgOrder(..),
38 OptDescr(..),
39 ArgDescr(..),
40 usageInfo, -- :: String -> [OptDescr a] -> String
41 getOpt -- :: ArgOrder a -> [OptDescr a] -> [String]
42 -- -> ([a],[String],[String])
43 ) where
44
45 import Prelude
46 import Data.List ( isPrefixOf )
47
48 data ArgOrder a -- what to do with options following non-options:
49 = RequireOrder -- no option processing after first non-option
50 | Permute -- freely intersperse options and non-options
51 | ReturnInOrder (String -> a) -- wrap non-options into options
52
53 data OptDescr a = -- description of a single options:
54 Option [Char] -- list of short option characters
55 [String] -- list of long option strings (without "--")
56 (ArgDescr a) -- argument descriptor
57 String -- explanation of option for user
58
59 data ArgDescr a -- description of an argument option:
60 = NoArg a -- no argument expected
61 | ReqArg (String -> a) String -- option requires argument
62 | OptArg (Maybe String -> a) String -- optional argument
63
64 data OptKind a -- kind of cmd line arg (internal use only):
65 = Opt a -- an option
66 | NonOpt String -- a non-option
67 | EndOfOpts -- end-of-options marker (i.e. "--")
68 | OptErr String -- something went wrong...
69
70 usageInfo :: String -- header
71 -> [OptDescr a] -- option descriptors
72 -> String -- nicely formatted decription of options
73 usageInfo header optDescr = unlines (header:table)
74 where (ss,ls,ds) = (unzip3 . map fmtOpt) optDescr
75 table = zipWith3 paste (sameLen ss) (sameLen ls) ds
76 paste x y z = " " ++ x ++ " " ++ y ++ " " ++ z
77 sameLen xs = flushLeft ((maximum . map length) xs) xs
78 flushLeft n xs = [ take n (x ++ repeat ' ') | x <- xs ]
79
80 fmtOpt :: OptDescr a -> (String,String,String)
81 fmtOpt (Option sos los ad descr) = (sepBy ',' (map (fmtShort ad) sos),
82 sepBy ',' (map (fmtLong ad) los),
83 descr)
84 where sepBy _ [] = ""
85 sepBy _ [x] = x
86 sepBy ch (x:xs) = x ++ ch:' ':sepBy ch xs
87
88 fmtShort :: ArgDescr a -> Char -> String
89 fmtShort (NoArg _ ) so = "-" ++ [so]
90 fmtShort (ReqArg _ ad) so = "-" ++ [so] ++ " " ++ ad
91 fmtShort (OptArg _ ad) so = "-" ++ [so] ++ "[" ++ ad ++ "]"
92
93 fmtLong :: ArgDescr a -> String -> String
94 fmtLong (NoArg _ ) lo = "--" ++ lo
95 fmtLong (ReqArg _ ad) lo = "--" ++ lo ++ "=" ++ ad
96 fmtLong (OptArg _ ad) lo = "--" ++ lo ++ "[=" ++ ad ++ "]"
97
98 getOpt :: ArgOrder a -- non-option handling
99 -> [OptDescr a] -- option descriptors
100 -> [String] -- the commandline arguments
101 -> ([a],[String],[String]) -- (options,non-options,error messages)
102 getOpt _ _ [] = ([],[],[])
103 getOpt ordering optDescr (arg:args) = procNextOpt opt ordering
104 where procNextOpt (Opt o) _ = (o:os,xs,es)
105 procNextOpt (NonOpt x) RequireOrder = ([],x:rest,[])
106 procNextOpt (NonOpt x) Permute = (os,x:xs,es)
107 procNextOpt (NonOpt x) (ReturnInOrder f) = (f x :os, xs,es)
108 procNextOpt EndOfOpts RequireOrder = ([],rest,[])
109 procNextOpt EndOfOpts Permute = ([],rest,[])
110 procNextOpt EndOfOpts (ReturnInOrder f) = (map f rest,[],[])
111 procNextOpt (OptErr e) _ = (os,xs,e:es)
112
113 (opt,rest) = getNext arg args optDescr
114 (os,xs,es) = getOpt ordering optDescr rest
115
116 -- take a look at the next cmd line arg and decide what to do with it
117 getNext :: String -> [String] -> [OptDescr a] -> (OptKind a,[String])
118 getNext ('-':'-':[]) rest _ = (EndOfOpts,rest)
119 getNext ('-':'-':xs) rest optDescr = longOpt xs rest optDescr
120 getNext ('-': x :xs) rest optDescr = shortOpt x xs rest optDescr
121 getNext a rest _ = (NonOpt a,rest)
122
123 -- handle long option
124 longOpt :: String -> [String] -> [OptDescr a] -> (OptKind a,[String])
125 longOpt ls rs optDescr = long ads arg rs
126 where (opt,arg) = break (=='=') ls
127 options = [ o | o@(Option _ ls _ _) <- optDescr, l <- ls, opt `isPrefixOf` l ]
128 ads = [ ad | Option _ _ ad _ <- options ]
129 optStr = ("--"++opt)
130
131 long (_:_:_) _ rest = (errAmbig options optStr,rest)
132 long [NoArg a ] [] rest = (Opt a,rest)
133 long [NoArg _ ] ('=':_) rest = (errNoArg optStr,rest)
134 long [ReqArg _ d] [] [] = (errReq d optStr,[])
135 long [ReqArg f _] [] (r:rest) = (Opt (f r),rest)
136 long [ReqArg f _] ('=':xs) rest = (Opt (f xs),rest)
137 long [OptArg f _] [] rest = (Opt (f Nothing),rest)
138 long [OptArg f _] ('=':xs) rest = (Opt (f (Just xs)),rest)
139 long _ _ rest = (errUnrec optStr,rest)
140
141 -- handle short option
142 shortOpt :: Char -> String -> [String] -> [OptDescr a] -> (OptKind a,[String])
143 shortOpt x xs rest optDescr = short ads xs rest
144 where options = [ o | o@(Option ss _ _ _) <- optDescr, s <- ss, x == s ]
145 ads = [ ad | Option _ _ ad _ <- options ]
146 optStr = '-':[x]
147
148 short (_:_:_) _ rest = (errAmbig options optStr,rest)
149 short (NoArg a :_) [] rest = (Opt a,rest)
150 short (NoArg a :_) xs rest = (Opt a,('-':xs):rest)
151 short (ReqArg _ d:_) [] [] = (errReq d optStr,[])
152 short (ReqArg f _:_) [] (r:rest) = (Opt (f r),rest)
153 short (ReqArg f _:_) xs rest = (Opt (f xs),rest)
154 short (OptArg f _:_) [] rest = (Opt (f Nothing),rest)
155 short (OptArg f _:_) xs rest = (Opt (f (Just xs)),rest)
156 short [] [] rest = (errUnrec optStr,rest)
157 short [] xs rest = (errUnrec optStr,('-':xs):rest)
158
159 -- miscellaneous error formatting
160
161 errAmbig :: [OptDescr a] -> String -> OptKind a
162 errAmbig ods optStr = OptErr (usageInfo header ods)
163 where header = "option `" ++ optStr ++ "' is ambiguous; could be one of:"
164
165 errReq :: String -> String -> OptKind a
166 errReq d optStr = OptErr ("option `" ++ optStr ++ "' requires an argument " ++ d ++ "\n")
167
168 errUnrec :: String -> OptKind a
169 errUnrec optStr = OptErr ("unrecognized option `" ++ optStr ++ "'\n")
170
171 errNoArg :: String -> OptKind a
172 errNoArg optStr = OptErr ("option `" ++ optStr ++ "' doesn't allow an argument\n")
173
174 {-
175 -----------------------------------------------------------------------------------------
176 -- and here a small and hopefully enlightening example:
177
178 data Flag = Verbose | Version | Name String | Output String | Arg String deriving Show
179
180 options :: [OptDescr Flag]
181 options =
182 [Option ['v'] ["verbose"] (NoArg Verbose) "verbosely list files",
183 Option ['V','?'] ["version","release"] (NoArg Version) "show version info",
184 Option ['o'] ["output"] (OptArg out "FILE") "use FILE for dump",
185 Option ['n'] ["name"] (ReqArg Name "USER") "only dump USER's files"]
186
187 out :: Maybe String -> Flag
188 out Nothing = Output "stdout"
189 out (Just o) = Output o
190
191 test :: ArgOrder Flag -> [String] -> String
192 test order cmdline = case getOpt order options cmdline of
193 (o,n,[] ) -> "options=" ++ show o ++ " args=" ++ show n ++ "\n"
194 (_,_,errs) -> concat errs ++ usageInfo header options
195 where header = "Usage: foobar [OPTION...] files..."
196
197 -- example runs:
198 -- putStr (test RequireOrder ["foo","-v"])
199 -- ==> options=[] args=["foo", "-v"]
200 -- putStr (test Permute ["foo","-v"])
201 -- ==> options=[Verbose] args=["foo"]
202 -- putStr (test (ReturnInOrder Arg) ["foo","-v"])
203 -- ==> options=[Arg "foo", Verbose] args=[]
204 -- putStr (test Permute ["foo","--","-v"])
205 -- ==> options=[] args=["foo", "-v"]
206 -- putStr (test Permute ["-?o","--name","bar","--na=baz"])
207 -- ==> options=[Version, Output "stdout", Name "bar", Name "baz"] args=[]
208 -- putStr (test Permute ["--ver","foo"])
209 -- ==> option `--ver' is ambiguous; could be one of:
210 -- -v --verbose verbosely list files
211 -- -V, -? --version, --release show version info
212 -- Usage: foobar [OPTION...] files...
213 -- -v --verbose verbosely list files
214 -- -V, -? --version, --release show version info
215 -- -o[FILE] --output[=FILE] use FILE for dump
216 -- -n USER --name=USER only dump USER's files
217 -----------------------------------------------------------------------------------------
218 -}