2 # optparse.rb - command-line option analysis with the OptionParser class.
5 # Documentation:: Nobu Nakada and Gavin Sinclair.
7 # See OptionParser for documentation.
11 # == Developer Documentation (not for RDoc output)
15 # - OptionParser:: front end
16 # - OptionParser::Switch:: each switches
17 # - OptionParser::List:: options list
18 # - OptionParser::ParseError:: errors on parsing
19 # - OptionParser::AmbiguousOption
20 # - OptionParser::NeedlessArgument
21 # - OptionParser::MissingArgument
22 # - OptionParser::InvalidOption
23 # - OptionParser::InvalidArgument
24 # - OptionParser::AmbiguousArgument
26 # === Object relationship diagram
29 # | OptionParser |<>-----+
30 # +--------------+ | +--------+
32 # on_head -------->+---------------+ / +--------+
33 # accept/reject -->| List |<|>-
34 # | |<|>- +----------+
35 # on ------------->+---------------+ `-| argument |
37 # +---------------+ |==========|
38 # on_tail -------->| | |pattern |
39 # +---------------+ |----------|
40 # OptionParser.accept ->| DefaultList | |converter |
41 # reject |(shared between| +----------+
49 # OptionParser is a class for command-line option analysis. It is much more
50 # advanced, yet also easier to use, than GetoptLong, and is a more Ruby-oriented
55 # 1. The argument specification and the code to handle it are written in the
57 # 2. It can output an option summary; you don't need to maintain this string
59 # 3. Optional and mandatory arguments are specified very gracefully.
60 # 4. Arguments can be automatically converted to a specified class.
61 # 5. Arguments can be restricted to a certain set.
63 # All of these features are demonstrated in the examples below.
70 # OptionParser.new do |opts|
71 # opts.banner = "Usage: example.rb [options]"
73 # opts.on("-v", "--[no-]verbose", "Run verbosely") do |v|
74 # options[:verbose] = v
81 # === Complete example
83 # The following example is a complete Ruby program. You can run it and see the
84 # effect of specifying various options. This is probably the best way to learn
85 # the features of +optparse+.
88 # require 'optparse/time'
92 # class OptparseExample
94 # CODES = %w[iso-2022-jp shift_jis euc-jp utf8 binary]
95 # CODE_ALIASES = { "jis" => "iso-2022-jp", "sjis" => "shift_jis" }
98 # # Return a structure describing the options.
100 # def self.parse(args)
101 # # The options specified on the command line will be collected in *options*.
102 # # We set default values here.
103 # options = OpenStruct.new
104 # options.library = []
105 # options.inplace = false
106 # options.encoding = "utf8"
107 # options.transfer_type = :auto
108 # options.verbose = false
110 # opts = OptionParser.new do |opts|
111 # opts.banner = "Usage: example.rb [options]"
114 # opts.separator "Specific options:"
116 # # Mandatory argument.
117 # opts.on("-r", "--require LIBRARY",
118 # "Require the LIBRARY before executing your script") do |lib|
119 # options.library << lib
122 # # Optional argument; multi-line description.
123 # opts.on("-i", "--inplace [EXTENSION]",
124 # "Edit ARGV files in place",
125 # " (make backup if EXTENSION supplied)") do |ext|
126 # options.inplace = true
127 # options.extension = ext || ''
128 # options.extension.sub!(/\A\.?(?=.)/, ".") # Ensure extension begins with dot.
131 # # Cast 'delay' argument to a Float.
132 # opts.on("--delay N", Float, "Delay N seconds before executing") do |n|
136 # # Cast 'time' argument to a Time object.
137 # opts.on("-t", "--time [TIME]", Time, "Begin execution at given time") do |time|
138 # options.time = time
141 # # Cast to octal integer.
142 # opts.on("-F", "--irs [OCTAL]", OptionParser::OctalInteger,
143 # "Specify record separator (default \\0)") do |rs|
144 # options.record_separator = rs
147 # # List of arguments.
148 # opts.on("--list x,y,z", Array, "Example 'list' of arguments") do |list|
149 # options.list = list
152 # # Keyword completion. We are specifying a specific set of arguments (CODES
153 # # and CODE_ALIASES - notice the latter is a Hash), and the user may provide
154 # # the shortest unambiguous text.
155 # code_list = (CODE_ALIASES.keys + CODES).join(',')
156 # opts.on("--code CODE", CODES, CODE_ALIASES, "Select encoding",
157 # " (#{code_list})") do |encoding|
158 # options.encoding = encoding
161 # # Optional argument with keyword completion.
162 # opts.on("--type [TYPE]", [:text, :binary, :auto],
163 # "Select transfer type (text, binary, auto)") do |t|
164 # options.transfer_type = t
168 # opts.on("-v", "--[no-]verbose", "Run verbosely") do |v|
169 # options.verbose = v
173 # opts.separator "Common options:"
175 # # No argument, shows at tail. This will print an options summary.
177 # opts.on_tail("-h", "--help", "Show this message") do
182 # # Another typical switch to print the version.
183 # opts.on_tail("--version", "Show version") do
184 # puts OptionParser::Version.join('.')
193 # end # class OptparseExample
195 # options = OptparseExample.parse(ARGV)
198 # === Further documentation
200 # The above examples should be enough to learn how to use this class. If you
201 # have any questions, email me (gsinclair@soyabean.com.au) and I will update
206 RCSID = %w$Id$[1..-1].each {|s| s.freeze}.freeze
207 Version = (RCSID[1].split('.').collect {|s| s.to_i}.extend(Comparable).freeze if RCSID[1])
208 LastModified = (Time.gm(*RCSID[2, 2].join('-').scan(/\d+/).collect {|s| s.to_i}) if RCSID[2])
211 NoArgument = [NO_ARGUMENT = :NONE, nil].freeze
212 RequiredArgument = [REQUIRED_ARGUMENT = :REQUIRED, true].freeze
213 OptionalArgument = [OPTIONAL_ARGUMENT = :OPTIONAL, false].freeze
217 # Keyword completion module. This allows partial arguments to be specified
218 # and resolved against a list of acceptable values.
221 def complete(key, icase = false, pat = nil)
222 pat ||= Regexp.new('\A' + Regexp.quote(key).gsub(/\w+\b/, '\&\w*'),
231 kn = defined?(k.id2name) ? k.id2name : k
235 candidates << [k, v, kn]
237 candidates = candidates.sort_by {|k, v, kn| kn.size}
238 if candidates.size == 1
239 canon, sw, * = candidates[0]
240 elsif candidates.size > 1
241 canon, sw, cn = candidates.shift
242 candidates.each do |k, v, kn|
244 if String === cn and String === kn
246 canon, sw, cn = k, v, kn
248 elsif kn.rindex(cn, 0)
252 throw :ambiguous, key
256 block_given? or return key, *sw
261 def convert(opt = nil, val = nil, *)
268 # Map from option/keyword string to object with completion.
270 class OptionMap < Hash
276 # Individual switch class. Not important to the user.
278 # Defined within Switch are several Switch-derived classes: NoArgument,
279 # RequiredArgument, etc.
282 attr_reader :pattern, :conv, :short, :long, :arg, :desc, :block
285 # Guesses argument style from +arg+. Returns corresponding
286 # OptionParser::Switch class (OptionalArgument, etc.).
293 t = Switch::OptionalArgument
295 t = Switch::PlacedArgument
297 t = Switch::RequiredArgument
299 self >= t or incompatible_argument_styles(arg, t)
303 def self.incompatible_argument_styles(arg, t)
304 raise ArgumentError, "#{arg}: incompatible argument styles\n #{self}, #{t}"
311 def initialize(pattern = nil, conv = nil,
312 short = nil, long = nil, arg = nil,
313 desc = ([] if short or long), block = Proc.new)
314 raise if Array === pattern
315 @pattern, @conv, @short, @long, @arg, @desc, @block =
316 pattern, conv, short, long, arg, desc, block
320 # Parses +arg+ and returns rest of +arg+ and matched portion to the
321 # argument pattern. Yields when the pattern doesn't match substring.
324 pattern or return nil, [arg]
325 unless m = pattern.match(arg)
326 yield(InvalidArgument, arg)
334 return nil, m unless String === s
336 raise InvalidArgument, arg unless arg.rindex(s, 0)
337 return nil, m if s.length == arg.length
338 yield(InvalidArgument, arg) # didn't match whole arg
339 return arg[s.length..-1], m
344 # Parses argument, converts and returns +arg+, +block+ and result of
345 # conversion. Yields at semi-error condition instead of raising an
348 def conv_arg(arg, val = [])
350 val = conv.call(*val)
352 val = proc {|v| v}.call(*val)
354 return arg, block, val
359 # Produces the summary text. Each line of the summary is yielded to the
360 # block (without newline).
362 # +sdone+:: Already summarized short style options keyed hash.
363 # +ldone+:: Already summarized long style options keyed hash.
364 # +width+:: Width of left side (option part). In other words, the right
365 # side (description part) starts after +width+ columns.
366 # +max+:: Maximum width of left side -> the options are filled within
368 # +indent+:: Prefix string indents all summarized lines.
370 def summarize(sdone = [], ldone = [], width = 1, max = width - 1, indent = "")
371 sopts, lopts = [], [], nil
372 @short.each {|s| sdone.fetch(s) {sopts << s}; sdone[s] = true} if @short
373 @long.each {|s| ldone.fetch(s) {lopts << s}; ldone[s] = true} if @long
374 return if sopts.empty? and lopts.empty? # completely hidden
376 left = [sopts.join(', ')]
379 while s = lopts.shift
380 l = left[-1].length + s.length
381 l += arg.length if left.size == 1 && arg
382 l < max or sopts.empty? or left << ''
383 left[-1] << if left[-1].empty? then ' ' * 4 else ', ' end << s
386 left[0] << arg if arg
387 mlen = left.collect {|ss| ss.length}.max.to_i
388 while mlen > width and l = left.shift
389 mlen = left.collect {|ss| ss.length}.max.to_i if l.length == mlen
393 while begin l = left.shift; r = right.shift; l or r end
394 l = l.to_s.ljust(width) + ' ' + r if r and !r.empty?
401 def add_banner(to) # :nodoc:
402 unless @short or @long
404 to << " [" + s + "]..." unless s.empty?
409 def match_nonswitch?(str) # :nodoc:
410 @pattern =~ str unless @short or @long
414 # Main name of the switch.
417 (long.first || short.first).sub(/\A-+(?:\[no-\])?/, '')
421 # Switch that takes no arguments.
423 class NoArgument < self
426 # Raises an exception if any arguments given.
429 yield(NeedlessArgument, arg) if arg
433 def self.incompatible_argument_styles(*)
442 # Switch that takes an argument.
444 class RequiredArgument < self
447 # Raises an exception if argument is not present.
451 raise MissingArgument if argv.empty?
454 conv_arg(*parse_arg(arg, &method(:raise)))
459 # Switch that can omit argument.
461 class OptionalArgument < self
464 # Parses argument if given, or uses default value.
466 def parse(arg, argv, &error)
468 conv_arg(*parse_arg(arg, &error))
476 # Switch that takes an argument, which does not begin with '-'.
478 class PlacedArgument < self
481 # Returns nil if argument is not present or begins with '-'.
483 def parse(arg, argv, &error)
484 if !(val = arg) and (argv.empty? or /\A-/ =~ (val = argv[0]))
485 return nil, block, nil
487 opt = (val = parse_arg(val, &error))[1]
500 # Simple option list providing mapping from short and/or long option
501 # string to OptionParser::Switch and mapping from acceptable argument to
502 # matching pattern and converter pair. Also provides summary feature.
505 # Map from acceptable argument types to pattern and converter pairs.
508 # Map from short style option switches to actual switch objects.
511 # Map from long style option switches to actual switch objects.
514 # List of all switches and summary string.
518 # Just initializes all instance variables.
522 @short = OptionMap.new
523 @long = OptionMap.new
528 # See OptionParser.accept.
530 def accept(t, pat = /.*/nm, &block)
532 pat.respond_to?(:match) or raise TypeError, "has no `match'"
534 pat = t if t.respond_to?(:match)
537 block = pat.method(:convert).to_proc if pat.respond_to?(:convert)
539 @atype[t] = [pat, block]
543 # See OptionParser.reject.
550 # Adds +sw+ according to +sopts+, +lopts+ and +nlopts+.
552 # +sw+:: OptionParser::Switch instance to be added.
553 # +sopts+:: Short style option list.
554 # +lopts+:: Long style option list.
555 # +nlopts+:: Negated long style options list.
557 def update(sw, sopts, lopts, nsw = nil, nlopts = nil)
558 sopts.each {|o| @short[o] = sw} if sopts
559 lopts.each {|o| @long[o] = sw} if lopts
560 nlopts.each {|o| @long[o] = nsw} if nsw and nlopts
561 used = @short.invert.update(@long.invert)
562 @list.delete_if {|o| Switch === o and !used[o]}
567 # Inserts +switch+ at the head of the list, and associates short, long
568 # and negated long options. Arguments are:
570 # +switch+:: OptionParser::Switch instance to be inserted.
571 # +short_opts+:: List of short style options.
572 # +long_opts+:: List of long style options.
573 # +nolong_opts+:: List of long style options with "no-" prefix.
575 # prepend(switch, short_opts, long_opts, nolong_opts)
579 @list.unshift(args[0])
583 # Appends +switch+ at the tail of the list, and associates short, long
584 # and negated long options. Arguments are:
586 # +switch+:: OptionParser::Switch instance to be inserted.
587 # +short_opts+:: List of short style options.
588 # +long_opts+:: List of long style options.
589 # +nolong_opts+:: List of long style options with "no-" prefix.
591 # append(switch, short_opts, long_opts, nolong_opts)
599 # Searches +key+ in +id+ list. The result is returned or yielded if a
600 # block is given. If it isn't found, nil is returned.
603 if list = __send__(id)
604 val = list.fetch(key) {return nil}
605 block_given? ? yield(val) : val
610 # Searches list +id+ for +opt+ and the optional patterns for completion
611 # +pat+. If +icase+ is true, the search is case insensitive. The result
612 # is returned or yielded if a block is given. If it isn't found, nil is
615 def complete(id, opt, icase = false, *pat, &block)
616 __send__(id).complete(opt, icase, *pat, &block)
620 # Iterates over each option, passing the option to the +block+.
622 def each_option(&block)
627 # Creates the summary table, passing each line to the +block+ (without
628 # newline). The arguments +args+ are passed along to the summarize
629 # method which is called on every option.
631 def summarize(*args, &block)
633 if opt.respond_to?(:summarize) # perhaps OptionParser::Switch
634 opt.summarize(*args, &block)
637 elsif opt.respond_to?(:each_line)
638 opt.each_line(&block)
645 def add_banner(to) # :nodoc:
647 if opt.respond_to?(:add_banner)
656 # Hash with completion search feature. See OptionParser::Completion.
658 class CompletingHash < Hash
662 # Completion for hash key.
665 *values = fetch(key) {
666 raise AmbiguousArgument, catch(:ambiguous) {return complete(key)}
675 # Enumeration of acceptable argument styles. Possible values are:
677 # NO_ARGUMENT:: The switch takes no arguments. (:NONE)
678 # REQUIRED_ARGUMENT:: The switch requires an argument. (:REQUIRED)
679 # OPTIONAL_ARGUMENT:: The switch requires an optional argument. (:OPTIONAL)
681 # Use like --switch=argument (long style) or -Xargument (short style). For
682 # short style, only portion matched to argument pattern is dealed as
686 NoArgument.each {|el| ArgumentStyle[el] = Switch::NoArgument}
687 RequiredArgument.each {|el| ArgumentStyle[el] = Switch::RequiredArgument}
688 OptionalArgument.each {|el| ArgumentStyle[el] = Switch::OptionalArgument}
692 # Switches common used such as '--', and also provides default
695 DefaultList = List.new
696 DefaultList.short['-'] = Switch::NoArgument.new {}
697 DefaultList.long[''] = Switch::NoArgument.new {throw :terminate}
700 # Default options for ARGV, which never appear in option summary.
706 # Shows option summary.
708 Officious['help'] = proc do |parser|
709 Switch::NoArgument.new do
717 # Shows version string if Version is defined.
719 Officious['version'] = proc do |parser|
720 Switch::OptionalArgument.new do |pkg|
723 require 'optparse/version'
726 show_version(*pkg.split(/,/)) or
727 abort("#{parser.program_name}: no version found in package #{pkg}")
731 v = parser.ver or abort("#{parser.program_name}: version unknown")
744 # Initializes a new instance and evaluates the optional block in context
745 # of the instance. Arguments +args+ are passed to #new, see there for
746 # description of parameters.
748 # This method is *deprecated*, its behavior corresponds to the older #new
751 def self.with(*args, &block)
753 opts.instance_eval(&block)
758 # Returns an incremented value of +default+ according to +arg+.
760 def self.inc(arg, default = nil)
769 self.class.inc(*args)
773 # Initializes the instance and yields itself if called with a block.
775 # +banner+:: Banner message.
776 # +width+:: Summary width.
777 # +indent+:: Summary indent.
779 def initialize(banner = nil, width = 32, indent = ' ' * 4)
780 @stack = [DefaultList, List.new, List.new]
783 @summary_width = width
784 @summary_indent = indent
787 yield self if block_given?
790 def add_officious # :nodoc:
792 Officious.each do |opt, block|
793 list.long[opt] ||= block.call(self)
798 # Terminates option parsing. Optional parameter +arg+ is a string pushed
799 # back to be the first non-option argument.
801 def terminate(arg = nil)
802 self.class.terminate(arg)
804 def self.terminate(arg = nil)
805 throw :terminate, arg
808 @stack = [DefaultList]
809 def self.top() DefaultList end
812 # Directs to accept specified class +t+. The argument string is passed to
813 # the block in which it should be converted to the desired class.
815 # +t+:: Argument class specifier, any object including Class.
816 # +pat+:: Pattern for argument, defaults to +t+ if it responds to match.
818 # accept(t, pat, &block)
820 def accept(*args, &blk) top.accept(*args, &blk) end
824 def self.accept(*args, &blk) top.accept(*args, &blk) end
827 # Directs to reject specified class argument.
829 # +t+:: Argument class specifier, any object including Class.
833 def reject(*args, &blk) top.reject(*args, &blk) end
837 def self.reject(*args, &blk) top.reject(*args, &blk) end
843 # Heading banner preceding summary.
846 # Program name to be emitted in error message and default banner,
848 attr_writer :program_name
850 # Width for option list portion of summary. Must be Numeric.
851 attr_accessor :summary_width
853 # Indentation for summary. Must be String (or have + String method).
854 attr_accessor :summary_indent
856 # Strings to be parsed in default.
857 attr_accessor :default_argv
860 # Heading banner preceding summary.
864 @banner = "Usage: #{program_name} [options]"
865 visit(:add_banner, @banner)
871 # Program name to be emitted in error message and default banner, defaults
875 @program_name || File.basename($0, '.*')
878 # for experimental cascading :-)
879 alias set_banner banner=
880 alias set_program_name program_name=
881 alias set_summary_width summary_width=
882 alias set_summary_indent summary_indent=
893 @version || (defined?(::Version) && ::Version)
900 @release || (defined?(::Release) && ::Release) || (defined?(::RELEASE) && ::RELEASE)
904 # Returns version string from program_name, version and release.
908 str = "#{program_name} #{[v].join('.')}"
909 str << " (#{v})" if v = release
915 super("#{program_name}: #{mesg}")
919 super("#{program_name}: #{mesg}")
923 # Subject of #on / #on_head, #accept / #reject
930 # Subject of #on_tail.
940 @stack.push(List.new)
949 # Removes the last List.
956 # Puts option summary into +to+ and returns +to+. Yields each line if
959 # +to+:: Output destination, which must have method <<. Defaults to [].
960 # +width+:: Width of left side, defaults to @summary_width.
961 # +max+:: Maximum length allowed for left side, defaults to +width+ - 1.
962 # +indent+:: Indentation, defaults to @summary_indent.
964 def summarize(to = [], width = @summary_width, max = width - 1, indent = @summary_indent, &blk)
965 visit(:summarize, {}, {}, width, max, indent, &(blk || proc {|l| to << l + $/}))
970 # Returns option summary string.
972 def help; summarize(banner.to_s.sub(/\n?\z/, "\n")) end
976 # Returns option summary list.
978 def to_a; summarize(banner.to_a.dup) end
981 # Checks if an argument is given twice, in which case an ArgumentError is
982 # raised. Called from OptionParser#switch only.
984 # +obj+:: New argument.
985 # +prv+:: Previously specified argument.
986 # +msg+:: Exception message.
988 def notwice(obj, prv, msg)
989 unless !prv or prv == obj
991 raise ArgumentError, "argument #{msg} given twice: #{obj}"
1002 # Creates an OptionParser::Switch from the parameters. The parsed argument
1003 # value is passed to the given block, where it can be processed.
1005 # See at the beginning of OptionParser for some full examples.
1007 # +opts+ can include the following elements:
1010 # One of the following:
1011 # :NONE, :REQUIRED, :OPTIONAL
1013 # [Argument pattern:]
1014 # Acceptable option argument format, must be pre-defined with
1015 # OptionParser.accept or OptionParser#accept, or Regexp. This can appear
1016 # once or assigned as String if not present, otherwise causes an
1017 # ArgumentError. Examples:
1018 # Float, Time, Array
1020 # [Possible argument values:]
1022 # [:text, :binary, :auto]
1023 # %w[iso-2022-jp shift_jis euc-jp utf8 binary]
1024 # { "jis" => "iso-2022-jp", "sjis" => "shift_jis" }
1026 # [Long style switch:]
1027 # Specifies a long style switch which takes a mandatory, optional or no
1028 # argument. It's a string of the following form:
1029 # "--switch=MANDATORY" or "--switch MANDATORY"
1030 # "--switch[=OPTIONAL]"
1033 # [Short style switch:]
1034 # Specifies short style switch which takes a mandatory, optional or no
1035 # argument. It's a string of the following form:
1039 # There is also a special form which matches character range (not full
1040 # set of regular expression):
1042 # "-[a-z][OPTIONAL]"
1045 # [Argument style and description:]
1046 # Instead of specifying mandatory or optional arguments directly in the
1047 # switch parameter, this separate parameter can be used.
1052 # Description string for the option.
1056 # Handler for the parsed argument value. Either give a block or pass a
1057 # Proc or Method as an argument.
1059 def make_switch(opts, block = nil)
1060 short, long, nolong, style, pattern, conv, not_pattern, not_conv, not_style = [], [], []
1061 ldesc, sdesc, desc, arg = [], [], []
1062 default_style = Switch::NoArgument
1063 default_pattern = nil
1069 next if search(:atype, o) do |pat, c|
1070 klass = notwice(o, klass, 'type')
1071 if not_style and not_style != Switch::NoArgument
1072 not_pattern, not_conv = pat, c
1074 default_pattern, conv = pat, c
1078 # directly specified pattern(any object possible to match)
1079 if !(String === o) and o.respond_to?(:match)
1080 pattern = notwice(o, pattern, 'pattern')
1081 conv = pattern.method(:convert).to_proc if pattern.respond_to?(:convert)
1088 block = notwice(o, block, 'block')
1093 pattern = CompletingHash.new
1094 conv = pattern.method(:convert).to_proc if pattern.respond_to?(:convert)
1096 raise ArgumentError, "argument pattern given twice"
1098 o.each {|pat, *v| pattern[pat] = v.fetch(0) {pat}}
1100 raise ArgumentError, "unsupported argument type: #{o}"
1101 when *ArgumentStyle.keys
1102 style = notwice(ArgumentStyle[o], style, 'style')
1103 when /^--no-([^\[\]=\s]*)(.+)?/
1105 o = notwice(a ? Object : TrueClass, klass, 'type')
1106 not_pattern, not_conv = search(:atype, o) unless not_style
1107 not_style = (not_style || default_style).guess(arg = a) if a
1108 default_style = Switch::NoArgument
1109 default_pattern, conv = search(:atype, FalseClass) unless default_pattern
1110 ldesc << "--no-#{q}"
1111 long << 'no-' + (q = q.downcase)
1113 when /^--\[no-\]([^\[\]=\s]*)(.+)?/
1115 o = notwice(a ? Object : TrueClass, klass, 'type')
1117 default_style = default_style.guess(arg = a)
1118 default_pattern, conv = search(:atype, o) unless default_pattern
1120 ldesc << "--[no-]#{q}"
1121 long << (o = q.downcase)
1122 not_pattern, not_conv = search(:atype, FalseClass) unless not_style
1123 not_style = Switch::NoArgument
1125 when /^--([^\[\]=\s]*)(.+)?/
1128 o = notwice(NilClass, klass, 'type')
1129 default_style = default_style.guess(arg = a)
1130 default_pattern, conv = search(:atype, o) unless default_pattern
1133 long << (o = q.downcase)
1134 when /^-(\[\^?\]?(?:[^\\\]]|\\.)*\])(.+)?/
1136 o = notwice(Object, klass, 'type')
1138 default_style = default_style.guess(arg = a)
1139 default_pattern, conv = search(:atype, o) unless default_pattern
1142 short << Regexp.new(q)
1146 o = notwice(NilClass, klass, 'type')
1147 default_style = default_style.guess(arg = a)
1148 default_pattern, conv = search(:atype, o) unless default_pattern
1153 style = notwice(default_style.guess(arg = o), style, 'style')
1154 default_pattern, conv = search(:atype, Object) unless default_pattern
1160 default_pattern, conv = search(:atype, default_style.pattern) unless default_pattern
1161 if !(short.empty? and long.empty?)
1162 s = (style || default_style).new(pattern || default_pattern,
1163 conv, sdesc, ldesc, arg, desc, block)
1165 raise ArgumentError, "no switch given" if style or pattern
1169 s = (style || default_style).new(pattern,
1170 conv, nil, nil, arg, desc, block)
1172 return s, short, long,
1173 (not_style.new(not_pattern, not_conv, sdesc, ldesc, nil, desc, block) if not_style),
1177 def define(*opts, &block)
1178 top.append(*(sw = make_switch(opts, block)))
1183 # Add option switch and handler. See #make_switch for an explanation of
1186 def on(*opts, &block)
1187 define(*opts, &block)
1190 alias def_option define
1192 def define_head(*opts, &block)
1193 top.prepend(*(sw = make_switch(opts, block)))
1198 # Add option switch like with #on, but at head of summary.
1200 def on_head(*opts, &block)
1201 define_head(*opts, &block)
1204 alias def_head_option define_head
1206 def define_tail(*opts, &block)
1207 base.append(*(sw = make_switch(opts, block)))
1212 # Add option switch like with #on, but at tail of summary.
1214 def on_tail(*opts, &block)
1215 define_tail(*opts, &block)
1218 alias def_tail_option define_tail
1221 # Add separator in summary.
1223 def separator(string)
1224 top.append(string, nil, nil)
1228 # Parses command line arguments +argv+ in order. When a block is given,
1229 # each non-option argument is yielded.
1231 # Returns the rest of +argv+ left unparsed.
1233 def order(*argv, &block)
1234 argv = argv[0].dup if argv.size == 1 and Array === argv[0]
1235 order!(argv, &block)
1239 # Same as #order, but removes switches destructively.
1241 def order!(argv = default_argv, &nonopt)
1242 parse_in_order(argv, &nonopt)
1245 def parse_in_order(argv = default_argv, setter = nil, &nonopt) # :nodoc:
1246 opt, arg, val, rest = nil
1247 nonopt ||= proc {|a| throw :terminate, a}
1248 argv.unshift(arg) if arg = catch(:terminate) {
1249 while arg = argv.shift
1252 when /\A--([^=]*)(?:=(.*))?/nm
1255 sw, = complete(:long, opt, true)
1257 raise $!.set_option(arg, true)
1260 opt, cb, val = sw.parse(rest, argv) {|*exc| raise(*exc)}
1261 val = cb.call(val) if cb
1262 setter.call(sw.switch_name, val) if setter
1264 raise $!.set_option(arg, rest)
1268 when /\A-(.)((=).*|.+)?/nm
1269 opt, has_arg, eq, val, rest = $1, $3, $3, $2, $2
1271 sw, = search(:short, opt)
1274 sw, = complete(:short, opt)
1275 # short option matched.
1276 val = arg.sub(/\A-/, '')
1278 rescue InvalidOption
1279 # if no short options match, try completion with long
1281 sw, = complete(:long, opt)
1286 raise $!.set_option(arg, true)
1289 opt, cb, val = sw.parse(val, argv) {|*exc| raise(*exc) if eq}
1290 raise InvalidOption, arg if has_arg and !eq and arg == "-#{opt}"
1291 argv.unshift(opt) if opt and (opt = opt.sub(/\A-*/, '-')) != '-'
1292 val = cb.call(val) if cb
1293 setter.call(sw.switch_name, val) if setter
1295 raise $!.set_option(arg, arg.length > 2)
1298 # non-option argument
1301 visit(:each_option) do |sw0|
1303 sw.block.call(arg) if Switch === sw and sw.match_nonswitch?(arg)
1313 visit(:search, :short, nil) {|sw| sw.block.call(*argv) if !sw.pattern}
1317 private :parse_in_order
1320 # Parses command line arguments +argv+ in permutation mode and returns
1321 # list of non-option arguments.
1324 argv = argv[0].dup if argv.size == 1 and Array === argv[0]
1329 # Same as #permute, but removes switches destructively.
1331 def permute!(argv = default_argv)
1333 order!(argv, &nonopts.method(:<<))
1334 argv[0, 0] = nonopts
1339 # Parses command line arguments +argv+ in order when environment variable
1340 # POSIXLY_CORRECT is set, and in permutation mode otherwise.
1343 argv = argv[0].dup if argv.size == 1 and Array === argv[0]
1348 # Same as #parse, but removes switches destructively.
1350 def parse!(argv = default_argv)
1351 if ENV.include?('POSIXLY_CORRECT')
1359 # Wrapper method for getopts.rb.
1361 # params = ARGV.getopts("ab:", "foo", "bar:")
1362 # # params[:a] = true # -a
1363 # # params[:b] = "1" # -b1
1364 # # params[:foo] = "1" # --foo
1365 # # params[:bar] = "x" # --bar x
1368 argv = Array === args.first ? args.shift : default_argv
1369 single_options, *long_options = *args
1373 single_options.scan(/(.)(:)?/) do |opt, val|
1376 define("-#{opt} VAL")
1381 end if single_options
1383 long_options.each do |arg|
1384 opt, val = arg.split(':', 2)
1386 result[opt] = val.empty? ? nil : val
1387 define("--#{opt} VAL")
1394 parse_in_order(argv, result.method(:[]=))
1401 def self.getopts(*args)
1406 # Traverses @stack, sending each element method +id+ with +args+ and
1409 def visit(id, *args, &block)
1410 @stack.reverse_each do |el|
1411 el.send(id, *args, &block)
1418 # Searches +key+ in @stack for +id+ hash and returns or yields the result.
1421 block_given = block_given?
1422 visit(:search, id, key) do |k|
1423 return block_given ? yield(k) : k
1429 # Completes shortened long style option switch and returns pair of
1430 # canonical switch and switch descriptor OptionParser::Switch.
1432 # +id+:: Searching table.
1433 # +opt+:: Searching key.
1434 # +icase+:: Search case insensitive if true.
1435 # +pat+:: Optional pattern for completion.
1437 def complete(typ, opt, icase = false, *pat)
1439 search(typ, opt) {|sw| return [sw, opt]} # exact match or...
1441 raise AmbiguousOption, catch(:ambiguous) {
1442 visit(:complete, typ, opt, icase, *pat) {|o, *sw| return sw}
1443 raise InvalidOption, opt
1449 # Loads options from file names as +filename+. Does nothing when the file
1450 # is not present. Returns whether successfully loaded.
1452 # +filename+ defaults to basename of the program without suffix in a
1453 # directory ~/.options.
1455 def load(filename = nil)
1457 filename ||= File.expand_path(File.basename($0, '.*'), '~/.options')
1462 parse(*IO.readlines(filename).each {|s| s.chomp!})
1464 rescue Errno::ENOENT, Errno::ENOTDIR
1470 # Parses environment variable +env+ or its uppercase with splitting like a
1473 # +env+ defaults to the basename of the program.
1475 def environment(env = File.basename($0, '.*'))
1476 env = ENV[env] || ENV[env.upcase] or return
1477 require 'shellwords'
1478 parse(*Shellwords.shellwords(env))
1482 # Acceptable argument classes
1486 # Any string and no conversion. This is fall-back.
1488 accept(Object) {|s,|s or s.nil?}
1490 accept(NilClass) {|s,|s}
1493 # Any non-empty string, and no conversion.
1495 accept(String, /.+/nm) {|s,*|s}
1498 # Ruby/C-like integer, octal for 0-7 sequence, binary for 0b, hexadecimal
1499 # for 0x, and decimal for others; with optional sign prefix. Converts to
1502 decimal = '\d+(?:_\d+)*'
1503 binary = 'b[01]+(?:_[01]+)*'
1504 hex = 'x[\da-f]+(?:_[\da-f]+)*'
1505 octal = "0(?:[0-7]*(?:_[0-7]+)*|#{binary}|#{hex})"
1506 integer = "#{octal}|#{decimal}"
1507 accept(Integer, %r"\A[-+]?(?:#{integer})"io) {|s,| Integer(s) if s}
1510 # Float number format, and converts to Float.
1512 float = "(?:#{decimal}(?:\\.(?:#{decimal})?)?|\\.#{decimal})(?:E[-+]?#{decimal})?"
1513 floatpat = %r"\A[-+]?#{float}"io
1514 accept(Float, floatpat) {|s,| s.to_f if s}
1517 # Generic numeric format, converts to Integer for integer format, Float
1520 accept(Numeric, %r"\A[-+]?(?:#{octal}|#{float})"io) {|s,| eval(s) if s}
1523 # Decimal integer format, to be converted to Integer.
1525 DecimalInteger = /\A[-+]?#{decimal}/io
1526 accept(DecimalInteger) {|s,| s.to_i if s}
1529 # Ruby/C like octal/hexadecimal/binary integer format, to be converted to
1532 OctalInteger = /\A[-+]?(?:[0-7]+(?:_[0-7]+)*|0(?:#{binary}|#{hex}))/io
1533 accept(OctalInteger) {|s,| s.oct if s}
1536 # Decimal integer/float number format, to be converted to Integer for
1537 # integer format, Float for float format.
1539 DecimalNumeric = floatpat # decimal integer is allowed as float also.
1540 accept(DecimalNumeric) {|s,| eval(s) if s}
1543 # Boolean switch, which means whether it is present or not, whether it is
1544 # absent or not with prefix no-, or it takes an argument
1545 # yes/no/true/false/+/-.
1547 yesno = CompletingHash.new
1548 %w[- no false].each {|el| yesno[el] = false}
1549 %w[+ yes true].each {|el| yesno[el] = true}
1550 yesno['nil'] = false # shoud be nil?
1551 accept(TrueClass, yesno) {|arg, val| val == nil or val}
1553 # Similar to TrueClass, but defaults to false.
1555 accept(FalseClass, yesno) {|arg, val| val != nil and val}
1558 # List of strings separated by ",".
1560 accept(Array) do |s,|
1562 s = s.split(',').collect {|ss| ss unless ss.empty?}
1568 # Regular expression with options.
1570 accept(Regexp, %r"\A/((?:\\.|[^\\])*)/([[:alpha:]]+)?\z|.*") do |all, s, o|
1573 f |= Regexp::IGNORECASE if /i/ =~ o
1574 f |= Regexp::MULTILINE if /m/ =~ o
1575 f |= Regexp::EXTENDED if /x/ =~ o
1576 k = o.delete("^imx")
1578 Regexp.new(s || all, f, k)
1586 # Base class of exceptions from OptionParser.
1588 class ParseError < RuntimeError
1589 # Reason which caused the error.
1590 Reason = 'parse error'.freeze
1592 def initialize(*args)
1601 # Pushes back erred argument(s) to +argv+.
1608 def set_option(opt, eq)
1618 # Returns error reason. Override this for I18N.
1621 @reason || self.class::Reason
1625 "#<#{self.class.to_s}: #{args.join(' ')}>"
1629 # Default stringizing method to emit standard error message.
1632 reason + ': ' + args.join(' ')
1639 # Raises when ambiguously completable string is encountered.
1641 class AmbiguousOption < ParseError
1642 const_set(:Reason, 'ambiguous option'.freeze)
1646 # Raises when there is an argument for a switch which takes no argument.
1648 class NeedlessArgument < ParseError
1649 const_set(:Reason, 'needless argument'.freeze)
1653 # Raises when a switch with mandatory argument has no argument.
1655 class MissingArgument < ParseError
1656 const_set(:Reason, 'missing argument'.freeze)
1660 # Raises when switch is undefined.
1662 class InvalidOption < ParseError
1663 const_set(:Reason, 'invalid option'.freeze)
1667 # Raises when the given argument does not match required format.
1669 class InvalidArgument < ParseError
1670 const_set(:Reason, 'invalid argument'.freeze)
1674 # Raises when the given argument word can't be completed uniquely.
1676 class AmbiguousArgument < InvalidArgument
1677 const_set(:Reason, 'ambiguous argument'.freeze)
1685 # Extends command line arguments array (ARGV) to parse itself.
1690 # Sets OptionParser object, when +opt+ is +false+ or +nil+, methods
1691 # OptionParser::Arguable#options and OptionParser::Arguable#options= are
1692 # undefined. Thus, there is no ways to access the OptionParser object
1693 # via the receiver object.
1696 unless @optparse = opt
1698 undef_method(:options)
1699 undef_method(:options=)
1705 # Actual OptionParser object, automatically created if nonexistent.
1707 # If called with a block, yields the OptionParser object and returns the
1708 # result of the block. If an OptionParser::ParseError exception occurs
1709 # in the block, it is rescued, a error message printed to STDERR and
1713 @optparse ||= OptionParser.new
1714 @optparse.default_argv = self
1715 block_given? or return @optparse
1725 # Parses +self+ destructively in order and returns +self+ containing the
1726 # rest arguments left unparsed.
1728 def order!(&blk) options.order!(self, &blk) end
1731 # Parses +self+ destructively in permutation mode and returns +self+
1732 # containing the rest arguments left unparsed.
1734 def permute!() options.permute!(self) end
1737 # Parses +self+ destructively and returns +self+ containing the
1738 # rest arguments left unparsed.
1740 def parse!() options.parse!(self) end
1743 # Substitution of getopts is possible as follows. Also see
1744 # OptionParser#getopts.
1746 # def getopts(*args)
1747 # ($OPT = ARGV.getopts(*args)).each do |opt, val|
1748 # eval "$OPT_#{opt.gsub(/[^A-Za-z0-9_]/, '_')} = val"
1750 # rescue OptionParser::ParseError
1754 options.getopts(self, *args)
1758 # Initializes instance variable.
1760 def self.extend_object(obj)
1762 obj.instance_eval {@optparse = nil}
1764 def initialize(*args)
1771 # Acceptable argument classes. Now contains DecimalInteger, OctalInteger
1772 # and DecimalNumeric. See Acceptable argument classes (in source code).
1775 const_set(:DecimalInteger, OptionParser::DecimalInteger)
1776 const_set(:OctalInteger, OptionParser::OctalInteger)
1777 const_set(:DecimalNumeric, OptionParser::DecimalNumeric)
1781 # ARGV is arguable by OptionParser
1782 ARGV.extend(OptionParser::Arguable)
1785 Version = OptionParser::Version
1787 q.parse!.empty? or puts "what's #{ARGV.join(' ')}?"
1788 } or abort(ARGV.options.to_s)