1 -----------------------------------------------------------------------------
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)
7 -- Maintainer : libraries@haskell.org
8 -- Stability : experimental
9 -- Portability : portable
11 -- A Haskell port of GNU's getopt library
13 -----------------------------------------------------------------------------
16 Sven Panne <Sven.Panne@informatik.uni-muenchen.de> Oct. 1996 (small
19 Two rather obscure features are missing: The Bash 2.0 non-option hack
20 (if you don't already know it, you probably don't want to hear about
21 it...) and the recognition of long options with a single dash
22 (e.g. '-help' is recognised as '--help', as long as there is no short
25 Other differences between GNU's getopt and this implementation: * To
26 enforce a coherent description of options and arguments, there are
27 explanation fields in the option/argument descriptor. * Error
28 messages are now more informative, but no longer POSIX
29 compliant... :-( And a final Haskell advertisement: The GNU C
30 implementation uses well over 1100 lines, we need only 195 here,
31 including a 46 line example! :-)
34 module System.Console.GetOpt (
38 usageInfo, -- :: String -> [OptDescr a] -> String
39 getOpt -- :: ArgOrder a -> [OptDescr a] -> [String]
40 -- -> ([a],[String],[String])
44 import Data.List ( isPrefixOf )
46 data ArgOrder a -- what to do with options following non-options:
47 = RequireOrder -- no option processing after first non-option
48 | Permute -- freely intersperse options and non-options
49 | ReturnInOrder (String -> a) -- wrap non-options into options
51 data OptDescr a = -- description of a single options:
52 Option [Char] -- list of short option characters
53 [String] -- list of long option strings (without "--")
54 (ArgDescr a) -- argument descriptor
55 String -- explanation of option for user
57 data ArgDescr a -- description of an argument option:
58 = NoArg a -- no argument expected
59 | ReqArg (String -> a) String -- option requires argument
60 | OptArg (Maybe String -> a) String -- optional argument
62 data OptKind a -- kind of cmd line arg (internal use only):
64 | NonOpt String -- a non-option
65 | EndOfOpts -- end-of-options marker (i.e. "--")
66 | OptErr String -- something went wrong...
68 usageInfo :: String -- header
69 -> [OptDescr a] -- option descriptors
70 -> String -- nicely formatted decription of options
71 usageInfo header optDescr = unlines (header:table)
72 where (ss,ls,ds) = (unzip3 . map fmtOpt) optDescr
73 table = zipWith3 paste (sameLen ss) (sameLen ls) ds
74 paste x y z = " " ++ x ++ " " ++ y ++ " " ++ z
75 sameLen xs = flushLeft ((maximum . map length) xs) xs
76 flushLeft n xs = [ take n (x ++ repeat ' ') | x <- xs ]
78 fmtOpt :: OptDescr a -> (String,String,String)
79 fmtOpt (Option sos los ad descr) = (sepBy ',' (map (fmtShort ad) sos),
80 sepBy ',' (map (fmtLong ad) los),
84 sepBy ch (x:xs) = x ++ ch:' ':sepBy ch xs
86 fmtShort :: ArgDescr a -> Char -> String
87 fmtShort (NoArg _ ) so = "-" ++ [so]
88 fmtShort (ReqArg _ ad) so = "-" ++ [so] ++ " " ++ ad
89 fmtShort (OptArg _ ad) so = "-" ++ [so] ++ "[" ++ ad ++ "]"
91 fmtLong :: ArgDescr a -> String -> String
92 fmtLong (NoArg _ ) lo = "--" ++ lo
93 fmtLong (ReqArg _ ad) lo = "--" ++ lo ++ "=" ++ ad
94 fmtLong (OptArg _ ad) lo = "--" ++ lo ++ "[=" ++ ad ++ "]"
96 getOpt :: ArgOrder a -- non-option handling
97 -> [OptDescr a] -- option descriptors
98 -> [String] -- the commandline arguments
99 -> ([a],[String],[String]) -- (options,non-options,error messages)
100 getOpt _ _ [] = ([],[],[])
101 getOpt ordering optDescr (arg:args) = procNextOpt opt ordering
102 where procNextOpt (Opt o) _ = (o:os,xs,es)
103 procNextOpt (NonOpt x) RequireOrder = ([],x:rest,[])
104 procNextOpt (NonOpt x) Permute = (os,x:xs,es)
105 procNextOpt (NonOpt x) (ReturnInOrder f) = (f x :os, xs,es)
106 procNextOpt EndOfOpts RequireOrder = ([],rest,[])
107 procNextOpt EndOfOpts Permute = ([],rest,[])
108 procNextOpt EndOfOpts (ReturnInOrder f) = (map f rest,[],[])
109 procNextOpt (OptErr e) _ = (os,xs,e:es)
111 (opt,rest) = getNext arg args optDescr
112 (os,xs,es) = getOpt ordering optDescr rest
114 -- take a look at the next cmd line arg and decide what to do with it
115 getNext :: String -> [String] -> [OptDescr a] -> (OptKind a,[String])
116 getNext ('-':'-':[]) rest _ = (EndOfOpts,rest)
117 getNext ('-':'-':xs) rest optDescr = longOpt xs rest optDescr
118 getNext ('-': x :xs) rest optDescr = shortOpt x xs rest optDescr
119 getNext a rest _ = (NonOpt a,rest)
121 -- handle long option
122 longOpt :: String -> [String] -> [OptDescr a] -> (OptKind a,[String])
123 longOpt ls rs optDescr = long ads arg rs
124 where (opt,arg) = break (=='=') ls
125 options = [ o | o@(Option _ ls _ _) <- optDescr, l <- ls, opt `isPrefixOf` l ]
126 ads = [ ad | Option _ _ ad _ <- options ]
129 long (_:_:_) _ rest = (errAmbig options optStr,rest)
130 long [NoArg a ] [] rest = (Opt a,rest)
131 long [NoArg _ ] ('=':_) rest = (errNoArg optStr,rest)
132 long [ReqArg _ d] [] [] = (errReq d optStr,[])
133 long [ReqArg f _] [] (r:rest) = (Opt (f r),rest)
134 long [ReqArg f _] ('=':xs) rest = (Opt (f xs),rest)
135 long [OptArg f _] [] rest = (Opt (f Nothing),rest)
136 long [OptArg f _] ('=':xs) rest = (Opt (f (Just xs)),rest)
137 long _ _ rest = (errUnrec optStr,rest)
139 -- handle short option
140 shortOpt :: Char -> String -> [String] -> [OptDescr a] -> (OptKind a,[String])
141 shortOpt x xs rest optDescr = short ads xs rest
142 where options = [ o | o@(Option ss _ _ _) <- optDescr, s <- ss, x == s ]
143 ads = [ ad | Option _ _ ad _ <- options ]
146 short (_:_:_) _ rest = (errAmbig options optStr,rest)
147 short (NoArg a :_) [] rest = (Opt a,rest)
148 short (NoArg a :_) xs rest = (Opt a,('-':xs):rest)
149 short (ReqArg _ d:_) [] [] = (errReq d optStr,[])
150 short (ReqArg f _:_) [] (r:rest) = (Opt (f r),rest)
151 short (ReqArg f _:_) xs rest = (Opt (f xs),rest)
152 short (OptArg f _:_) [] rest = (Opt (f Nothing),rest)
153 short (OptArg f _:_) xs rest = (Opt (f (Just xs)),rest)
154 short [] [] rest = (errUnrec optStr,rest)
155 short [] xs rest = (errUnrec optStr,('-':xs):rest)
157 -- miscellaneous error formatting
159 errAmbig :: [OptDescr a] -> String -> OptKind a
160 errAmbig ods optStr = OptErr (usageInfo header ods)
161 where header = "option `" ++ optStr ++ "' is ambiguous; could be one of:"
163 errReq :: String -> String -> OptKind a
164 errReq d optStr = OptErr ("option `" ++ optStr ++ "' requires an argument " ++ d ++ "\n")
166 errUnrec :: String -> OptKind a
167 errUnrec optStr = OptErr ("unrecognized option `" ++ optStr ++ "'\n")
169 errNoArg :: String -> OptKind a
170 errNoArg optStr = OptErr ("option `" ++ optStr ++ "' doesn't allow an argument\n")
173 -----------------------------------------------------------------------------------------
174 -- and here a small and hopefully enlightening example:
176 data Flag = Verbose | Version | Name String | Output String | Arg String deriving Show
178 options :: [OptDescr Flag]
180 [Option ['v'] ["verbose"] (NoArg Verbose) "verbosely list files",
181 Option ['V','?'] ["version","release"] (NoArg Version) "show version info",
182 Option ['o'] ["output"] (OptArg out "FILE") "use FILE for dump",
183 Option ['n'] ["name"] (ReqArg Name "USER") "only dump USER's files"]
185 out :: Maybe String -> Flag
186 out Nothing = Output "stdout"
187 out (Just o) = Output o
189 test :: ArgOrder Flag -> [String] -> String
190 test order cmdline = case getOpt order options cmdline of
191 (o,n,[] ) -> "options=" ++ show o ++ " args=" ++ show n ++ "\n"
192 (_,_,errs) -> concat errs ++ usageInfo header options
193 where header = "Usage: foobar [OPTION...] files..."
196 -- putStr (test RequireOrder ["foo","-v"])
197 -- ==> options=[] args=["foo", "-v"]
198 -- putStr (test Permute ["foo","-v"])
199 -- ==> options=[Verbose] args=["foo"]
200 -- putStr (test (ReturnInOrder Arg) ["foo","-v"])
201 -- ==> options=[Arg "foo", Verbose] args=[]
202 -- putStr (test Permute ["foo","--","-v"])
203 -- ==> options=[] args=["foo", "-v"]
204 -- putStr (test Permute ["-?o","--name","bar","--na=baz"])
205 -- ==> options=[Version, Output "stdout", Name "bar", Name "baz"] args=[]
206 -- putStr (test Permute ["--ver","foo"])
207 -- ==> option `--ver' is ambiguous; could be one of:
208 -- -v --verbose verbosely list files
209 -- -V, -? --version, --release show version info
210 -- Usage: foobar [OPTION...] files...
211 -- -v --verbose verbosely list files
212 -- -V, -? --version, --release show version info
213 -- -o[FILE] --output[=FILE] use FILE for dump
214 -- -n USER --name=USER only dump USER's files
215 -----------------------------------------------------------------------------------------