1 -----------------------------------------------------------------------------
3 -- Module : System.Console.GetOpt
4 -- Copyright : (c) Sven Panne Oct. 1996 (small changes Feb. 2003)
5 -- License : BSD-style (see the file libraries/base/LICENSE)
7 -- Maintainer : libraries@haskell.org
8 -- Stability : experimental
9 -- Portability : portable
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
15 -----------------------------------------------------------------------------
18 Sven Panne <Sven.Panne@informatik.uni-muenchen.de> Oct. 1996 (small
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
27 Other differences between GNU's getopt and this implementation:
29 * To enforce a coherent description of options and arguments, there
30 are explanation fields in the option/argument descriptor.
32 * Error messages are now more informative, but no longer POSIX
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!
40 module System.Console.GetOpt (
54 import Data.List ( isPrefixOf )
56 -- |What to do with options following non-options
58 = RequireOrder -- ^ no option processing after first non-option
59 | Permute -- ^ freely intersperse options and non-options
60 | ReturnInOrder (String -> a) -- ^ wrap non-options into options
63 Each 'OptDescr' describes a single option.
65 The arguments to 'Option' are:
67 * list of short option characters
69 * list of long option strings (without \"--\")
73 * explanation of option for user
75 data OptDescr a = -- description of a single options:
76 Option [Char] -- list of short option characters
77 [String] -- list of long option strings (without "--")
78 (ArgDescr a) -- argument descriptor
79 String -- explanation of option for user
81 -- |Describes whether an option takes an argument or not, and if so
82 -- how the argument is injected into a value of type @a@.
84 = NoArg a -- ^ no argument expected
85 | ReqArg (String -> a) String -- ^ option requires argument
86 | OptArg (Maybe String -> a) String -- ^ optional argument
88 data OptKind a -- kind of cmd line arg (internal use only):
90 | NonOpt String -- a non-option
91 | EndOfOpts -- end-of-options marker (i.e. "--")
92 | OptErr String -- something went wrong...
94 -- | Return a string describing the usage of a command, derived from
95 -- the header (first argument) and the options described by the
97 usageInfo :: String -- header
98 -> [OptDescr a] -- option descriptors
99 -> String -- nicely formatted decription of options
100 usageInfo header optDescr = unlines (header:table)
101 where (ss,ls,ds) = (unzip3 . map fmtOpt) optDescr
102 table = zipWith3 paste (sameLen ss) (sameLen ls) ds
103 paste x y z = " " ++ x ++ " " ++ y ++ " " ++ z
104 sameLen xs = flushLeft ((maximum . map length) xs) xs
105 flushLeft n xs = [ take n (x ++ repeat ' ') | x <- xs ]
107 fmtOpt :: OptDescr a -> (String,String,String)
108 fmtOpt (Option sos los ad descr) = (sepBy ',' (map (fmtShort ad) sos),
109 sepBy ',' (map (fmtLong ad) los),
111 where sepBy _ [] = ""
113 sepBy ch (x:xs) = x ++ ch:' ':sepBy ch xs
115 fmtShort :: ArgDescr a -> Char -> String
116 fmtShort (NoArg _ ) so = "-" ++ [so]
117 fmtShort (ReqArg _ ad) so = "-" ++ [so] ++ " " ++ ad
118 fmtShort (OptArg _ ad) so = "-" ++ [so] ++ "[" ++ ad ++ "]"
120 fmtLong :: ArgDescr a -> String -> String
121 fmtLong (NoArg _ ) lo = "--" ++ lo
122 fmtLong (ReqArg _ ad) lo = "--" ++ lo ++ "=" ++ ad
123 fmtLong (OptArg _ ad) lo = "--" ++ lo ++ "[=" ++ ad ++ "]"
126 Process the command-line, and return the list of values that matched
127 (and those that didn\'t). The arguments are:
129 * The order requirements (see 'ArgOrder')
131 * The option descriptions (see 'OptDescr')
133 * The actual command line arguments (presumably got from
134 'System.Environment.getArgs').
136 'getOpt' returns a triple, consisting of the argument values, a list
137 of options that didn\'t match, and a list of error messages.
139 getOpt :: ArgOrder a -- non-option handling
140 -> [OptDescr a] -- option descriptors
141 -> [String] -- the commandline arguments
142 -> ([a],[String],[String]) -- (options,non-options,error messages)
143 getOpt _ _ [] = ([],[],[])
144 getOpt ordering optDescr (arg:args) = procNextOpt opt ordering
145 where procNextOpt (Opt o) _ = (o:os,xs,es)
146 procNextOpt (NonOpt x) RequireOrder = ([],x:rest,[])
147 procNextOpt (NonOpt x) Permute = (os,x:xs,es)
148 procNextOpt (NonOpt x) (ReturnInOrder f) = (f x :os, xs,es)
149 procNextOpt EndOfOpts RequireOrder = ([],rest,[])
150 procNextOpt EndOfOpts Permute = ([],rest,[])
151 procNextOpt EndOfOpts (ReturnInOrder f) = (map f rest,[],[])
152 procNextOpt (OptErr e) _ = (os,xs,e:es)
154 (opt,rest) = getNext arg args optDescr
155 (os,xs,es) = getOpt ordering optDescr rest
157 -- take a look at the next cmd line arg and decide what to do with it
158 getNext :: String -> [String] -> [OptDescr a] -> (OptKind a,[String])
159 getNext ('-':'-':[]) rest _ = (EndOfOpts,rest)
160 getNext ('-':'-':xs) rest optDescr = longOpt xs rest optDescr
161 getNext ('-': x :xs) rest optDescr = shortOpt x xs rest optDescr
162 getNext a rest _ = (NonOpt a,rest)
164 -- handle long option
165 longOpt :: String -> [String] -> [OptDescr a] -> (OptKind a,[String])
166 longOpt ls rs optDescr = long ads arg rs
167 where (opt,arg) = break (=='=') ls
168 getWith p = [ o | o@(Option _ ls _ _) <- optDescr, l <- ls, opt `p` l ]
170 options = if null exact then getWith isPrefixOf else exact
171 ads = [ ad | Option _ _ ad _ <- options ]
174 long (_:_:_) _ rest = (errAmbig options optStr,rest)
175 long [NoArg a ] [] rest = (Opt a,rest)
176 long [NoArg _ ] ('=':_) rest = (errNoArg optStr,rest)
177 long [ReqArg _ d] [] [] = (errReq d optStr,[])
178 long [ReqArg f _] [] (r:rest) = (Opt (f r),rest)
179 long [ReqArg f _] ('=':xs) rest = (Opt (f xs),rest)
180 long [OptArg f _] [] rest = (Opt (f Nothing),rest)
181 long [OptArg f _] ('=':xs) rest = (Opt (f (Just xs)),rest)
182 long _ _ rest = (errUnrec optStr,rest)
184 -- handle short option
185 shortOpt :: Char -> String -> [String] -> [OptDescr a] -> (OptKind a,[String])
186 shortOpt x xs rest optDescr = short ads xs rest
187 where options = [ o | o@(Option ss _ _ _) <- optDescr, s <- ss, x == s ]
188 ads = [ ad | Option _ _ ad _ <- options ]
191 short (_:_:_) _ rest = (errAmbig options optStr,rest)
192 short (NoArg a :_) [] rest = (Opt a,rest)
193 short (NoArg a :_) xs rest = (Opt a,('-':xs):rest)
194 short (ReqArg _ d:_) [] [] = (errReq d optStr,[])
195 short (ReqArg f _:_) [] (r:rest) = (Opt (f r),rest)
196 short (ReqArg f _:_) xs rest = (Opt (f xs),rest)
197 short (OptArg f _:_) [] rest = (Opt (f Nothing),rest)
198 short (OptArg f _:_) xs rest = (Opt (f (Just xs)),rest)
199 short [] [] rest = (errUnrec optStr,rest)
200 short [] xs rest = (errUnrec optStr,('-':xs):rest)
202 -- miscellaneous error formatting
204 errAmbig :: [OptDescr a] -> String -> OptKind a
205 errAmbig ods optStr = OptErr (usageInfo header ods)
206 where header = "option `" ++ optStr ++ "' is ambiguous; could be one of:"
208 errReq :: String -> String -> OptKind a
209 errReq d optStr = OptErr ("option `" ++ optStr ++ "' requires an argument " ++ d ++ "\n")
211 errUnrec :: String -> OptKind a
212 errUnrec optStr = OptErr ("unrecognized option `" ++ optStr ++ "'\n")
214 errNoArg :: String -> OptKind a
215 errNoArg optStr = OptErr ("option `" ++ optStr ++ "' doesn't allow an argument\n")
218 -----------------------------------------------------------------------------------------
219 -- and here a small and hopefully enlightening example:
221 data Flag = Verbose | Version | Name String | Output String | Arg String deriving Show
223 options :: [OptDescr Flag]
225 [Option ['v'] ["verbose"] (NoArg Verbose) "verbosely list files",
226 Option ['V','?'] ["version","release"] (NoArg Version) "show version info",
227 Option ['o'] ["output"] (OptArg out "FILE") "use FILE for dump",
228 Option ['n'] ["name"] (ReqArg Name "USER") "only dump USER's files"]
230 out :: Maybe String -> Flag
231 out Nothing = Output "stdout"
232 out (Just o) = Output o
234 test :: ArgOrder Flag -> [String] -> String
235 test order cmdline = case getOpt order options cmdline of
236 (o,n,[] ) -> "options=" ++ show o ++ " args=" ++ show n ++ "\n"
237 (_,_,errs) -> concat errs ++ usageInfo header options
238 where header = "Usage: foobar [OPTION...] files..."
241 -- putStr (test RequireOrder ["foo","-v"])
242 -- ==> options=[] args=["foo", "-v"]
243 -- putStr (test Permute ["foo","-v"])
244 -- ==> options=[Verbose] args=["foo"]
245 -- putStr (test (ReturnInOrder Arg) ["foo","-v"])
246 -- ==> options=[Arg "foo", Verbose] args=[]
247 -- putStr (test Permute ["foo","--","-v"])
248 -- ==> options=[] args=["foo", "-v"]
249 -- putStr (test Permute ["-?o","--name","bar","--na=baz"])
250 -- ==> options=[Version, Output "stdout", Name "bar", Name "baz"] args=[]
251 -- putStr (test Permute ["--ver","foo"])
252 -- ==> option `--ver' is ambiguous; could be one of:
253 -- -v --verbose verbosely list files
254 -- -V, -? --version, --release show version info
255 -- Usage: foobar [OPTION...] files...
256 -- -v --verbose verbosely list files
257 -- -V, -? --version, --release show version info
258 -- -o[FILE] --output[=FILE] use FILE for dump
259 -- -n USER --name=USER only dump USER's files
260 -----------------------------------------------------------------------------------------
265 To hopefully illuminate the role of the different data
266 structures, here\'s the command-line options for a (very simple)
271 > import System.Console.GetOpt
272 > import Data.Maybe ( fromMaybe )
275 > = Verbose | Version
276 > | Input String | Output String | LibDir String
279 > options :: [OptDescr Flag]
281 > [ Option ['v'] ["verbose"] (NoArg Verbose) "chatty output on stderr"
282 > , Option ['V','?'] ["version"] (NoArg Version) "show version number"
283 > , Option ['o'] ["output"] (OptArg outp "FILE") "output FILE"
284 > , Option ['c'] [] (OptArg inp "FILE") "input FILE"
285 > , Option ['L'] ["libdir"] (ReqArg LibDir "DIR") "library directory"
288 > inp,outp :: Maybe String -> Flag
289 > outp = Output . fromMaybe "stdout"
290 > inp = Input . fromMaybe "stdout"
292 > compilerOpts :: [String] -> IO ([Flag], [String])
293 > compilerOpts argv =
294 > case (getOpt Permute options argv) of
295 > (o,n,[] ) -> return (o,n)
296 > (_,_,errs) -> ioError (userError (concat errs ++ usageInfo header options))
297 > where header = "Usage: ic [OPTION...] files..."