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: optparse.rb 11798 2007-02-20 06:53:16Z knu $[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*'),
224 canon, sw, k, v, cn = nil
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 = nil)
350 val = conv.call(*val)
352 val = proc {|val| val}.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, s = [], [], 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 left << ''
383 left[-1] << if left[-1].empty? then ' ' * 4 else ', ' end << s
386 left[0] << arg if arg
387 mlen = left.collect {|s| s.length}.max.to_i
388 while mlen > width and l = left.shift
389 mlen = left.collect {|s| s.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(arg, t) # HACK was (*)
443 # Switch that takes an argument.
445 class RequiredArgument < self
448 # Raises an exception if argument is not present.
452 raise MissingArgument if argv.empty?
455 conv_arg(*parse_arg(arg) {|*exc| raise(*exc)})
460 # Switch that can omit argument.
462 class OptionalArgument < self
465 # Parses argument if given, or uses default value.
467 def parse(arg, argv, &error)
469 conv_arg(*parse_arg(arg, &error))
477 # Switch that takes an argument, which does not begin with '-'.
479 class PlacedArgument < self
482 # Returns nil if argument is not present or begins with '-'.
484 def parse(arg, argv, &error)
485 if !(val = arg) and (argv.empty? or /\A-/ =~ (val = argv[0]))
486 return nil, block, nil
488 opt = (val = parse_arg(val, &error))[1]
501 # Simple option list providing mapping from short and/or long option
502 # string to OptionParser::Switch and mapping from acceptable argument to
503 # matching pattern and converter pair. Also provides summary feature.
506 # Map from acceptable argument types to pattern and converter pairs.
509 # Map from short style option switches to actual switch objects.
512 # Map from long style option switches to actual switch objects.
515 # List of all switches and summary string.
519 # Just initializes all instance variables.
523 @short = OptionMap.new
524 @long = OptionMap.new
529 # See OptionParser.accept.
531 def accept(t, pat = /.*/nm, &block)
533 pat.respond_to?(:match) or raise TypeError, "has no `match'"
535 pat = t if t.respond_to?(:match)
538 block = pat.method(:convert).to_proc if pat.respond_to?(:convert)
540 @atype[t] = [pat, block]
544 # See OptionParser.reject.
551 # Adds +sw+ according to +sopts+, +lopts+ and +nlopts+.
553 # +sw+:: OptionParser::Switch instance to be added.
554 # +sopts+:: Short style option list.
555 # +lopts+:: Long style option list.
556 # +nlopts+:: Negated long style options list.
558 def update(sw, sopts, lopts, nsw = nil, nlopts = nil)
560 sopts.each {|o| @short[o] = sw} if sopts
561 lopts.each {|o| @long[o] = sw} if lopts
562 nlopts.each {|o| @long[o] = nsw} if nsw and nlopts
563 used = @short.invert.update(@long.invert)
564 @list.delete_if {|o| Switch === o and !used[o]}
569 # Inserts +switch+ at the head of the list, and associates short, long
570 # and negated long options. Arguments are:
572 # +switch+:: OptionParser::Switch instance to be inserted.
573 # +short_opts+:: List of short style options.
574 # +long_opts+:: List of long style options.
575 # +nolong_opts+:: List of long style options with "no-" prefix.
577 # prepend(switch, short_opts, long_opts, nolong_opts)
581 @list.unshift(args[0])
585 # Appends +switch+ at the tail of the list, and associates short, long
586 # and negated long options. Arguments are:
588 # +switch+:: OptionParser::Switch instance to be inserted.
589 # +short_opts+:: List of short style options.
590 # +long_opts+:: List of long style options.
591 # +nolong_opts+:: List of long style options with "no-" prefix.
593 # append(switch, short_opts, long_opts, nolong_opts)
601 # Searches +key+ in +id+ list. The result is returned or yielded if a
602 # block is given. If it isn't found, nil is returned.
605 if list = __send__(id)
606 val = list.fetch(key) {return nil}
607 block_given? ? yield(val) : val
612 # Searches list +id+ for +opt+ and the optional patterns for completion
613 # +pat+. If +icase+ is true, the search is case insensitive. The result
614 # is returned or yielded if a block is given. If it isn't found, nil is
617 def complete(id, opt, icase = false, *pat, &block)
618 __send__(id).complete(opt, icase, *pat, &block)
622 # Iterates over each option, passing the option to the +block+.
624 def each_option(&block)
629 # Creates the summary table, passing each line to the +block+ (without
630 # newline). The arguments +args+ are passed along to the summarize
631 # method which is called on every option.
633 def summarize(*args, &block)
635 if opt.respond_to?(:summarize) # perhaps OptionParser::Switch
636 opt.summarize(*args, &block)
637 elsif !opt or opt.empty?
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 return key, *fetch(key) {
666 raise AmbiguousArgument, catch(:ambiguous) {return complete(key)}
674 # Enumeration of acceptable argument styles. Possible values are:
676 # NO_ARGUMENT:: The switch takes no arguments. (:NONE)
677 # REQUIRED_ARGUMENT:: The switch requires an argument. (:REQUIRED)
678 # OPTIONAL_ARGUMENT:: The switch requires an optional argument. (:OPTIONAL)
680 # Use like --switch=argument (long style) or -Xargument (short style). For
681 # short style, only portion matched to argument pattern is dealed as
685 NoArgument.each {|el| ArgumentStyle[el] = Switch::NoArgument}
686 RequiredArgument.each {|el| ArgumentStyle[el] = Switch::RequiredArgument}
687 OptionalArgument.each {|el| ArgumentStyle[el] = Switch::OptionalArgument}
691 # Switches common used such as '--', and also provides default
694 DefaultList = List.new
695 DefaultList.short['-'] = Switch::NoArgument.new {}
696 DefaultList.long[''] = Switch::NoArgument.new {throw :terminate}
699 # Default options for ARGV, which never appear in option summary.
705 # Shows option summary.
707 Officious['help'] = proc do |parser|
708 Switch::NoArgument.new do
716 # Shows version string if Version is defined.
718 Officious['version'] = proc do |parser|
719 Switch::OptionalArgument.new do |pkg|
722 require 'optparse/version'
725 show_version(*pkg.split(/,/)) or
726 abort("#{parser.program_name}: no version found in package #{pkg}")
730 v = parser.ver or abort("#{parser.program_name}: version unknown")
743 # Initializes a new instance and evaluates the optional block in context
744 # of the instance. Arguments +args+ are passed to #new, see there for
745 # description of parameters.
747 # This method is *deprecated*, its behavior corresponds to the older #new
750 def self.with(*args, &block)
752 opts.instance_eval(&block)
757 # Returns an incremented value of +default+ according to +arg+.
759 def self.inc(arg, default = nil)
768 self.class.inc(*args)
772 # Initializes the instance and yields itself if called with a block.
774 # +banner+:: Banner message.
775 # +width+:: Summary width.
776 # +indent+:: Summary indent.
778 def initialize(banner = nil, width = 32, indent = ' ' * 4)
779 @stack = [DefaultList, List.new, List.new]
782 @summary_width = width
783 @summary_indent = indent
786 yield self if block_given?
789 def add_officious # :nodoc:
791 Officious.each do |opt, block|
792 list.long[opt] ||= block.call(self)
797 # Terminates option parsing. Optional parameter +arg+ is a string pushed
798 # back to be the first non-option argument.
800 def terminate(arg = nil)
801 self.class.terminate(arg)
803 def self.terminate(arg = nil)
804 throw :terminate, arg
807 @stack = [DefaultList]
808 def self.top() DefaultList end
811 # Directs to accept specified class +t+. The argument string is passed to
812 # the block in which it should be converted to the desired class.
814 # +t+:: Argument class specifier, any object including Class.
815 # +pat+:: Pattern for argument, defaults to +t+ if it responds to match.
817 # accept(t, pat, &block)
819 def accept(*args, &blk) top.accept(*args, &blk) end
823 def self.accept(*args, &blk) top.accept(*args, &blk) end
826 # Directs to reject specified class argument.
828 # +t+:: Argument class speficier, any object including Class.
832 def reject(*args, &blk) top.reject(*args, &blk) end
836 def self.reject(*args, &blk) top.reject(*args, &blk) end
842 # Heading banner preceding summary.
845 # Program name to be emitted in error message and default banner,
847 attr_writer :program_name
849 # Width for option list portion of summary. Must be Numeric.
850 attr_accessor :summary_width
852 # Indentation for summary. Must be String (or have + String method).
853 attr_accessor :summary_indent
855 # Strings to be parsed in default.
856 attr_accessor :default_argv
859 # Heading banner preceding summary.
863 @banner = "Usage: #{program_name} [options]"
864 visit(:add_banner, @banner)
870 # Program name to be emitted in error message and default banner, defaults
874 @program_name || File.basename($0, '.*')
877 # for experimental cascading :-)
878 alias set_banner banner=
879 alias set_program_name program_name=
880 alias set_summary_width summary_width=
881 alias set_summary_indent summary_indent=
892 @version || (defined?(::Version) && ::Version)
899 @release || (defined?(::Release) && ::Release) || (defined?(::RELEASE) && ::RELEASE)
903 # Returns version string from program_name, version and release.
907 str = "#{program_name} #{[v].join('.')}"
908 str << " (#{v})" if v = release
914 super("#{program_name}: #{mesg}")
918 super("#{program_name}: #{mesg}")
922 # Subject of #on / #on_head, #accept / #reject
929 # Subject of #on_tail.
939 @stack.push(List.new)
948 # Removes the last List.
955 # Puts option summary into +to+ and returns +to+. Yields each line if
958 # +to+:: Output destination, which must have method <<. Defaults to [].
959 # +width+:: Width of left side, defaults to @summary_width.
960 # +max+:: Maximum length allowed for left side, defaults to +width+ - 1.
961 # +indent+:: Indentation, defaults to @summary_indent.
963 def summarize(to = [], width = @summary_width, max = width - 1, indent = @summary_indent, &blk)
964 visit(:summarize, {}, {}, width, max, indent, &(blk || proc {|l| to << l + $/}))
969 # Returns option summary string.
971 def help; summarize(banner.to_s.sub(/\n?\z/, "\n")) end
975 # Returns option summary list.
977 def to_a; summarize(banner.to_a.dup) end
980 # Checks if an argument is given twice, in which case an ArgumentError is
981 # raised. Called from OptionParser#switch only.
983 # +obj+:: New argument.
984 # +prv+:: Previously specified argument.
985 # +msg+:: Exception message.
987 def notwice(obj, prv, msg)
988 unless !prv or prv == obj
990 raise ArgumentError, "argument #{msg} given twice: #{obj}"
1001 # Creates an OptionParser::Switch from the parameters. The parsed argument
1002 # value is passed to the given block, where it can be processed.
1004 # See at the beginning of OptionParser for some full examples.
1006 # +opts+ can include the following elements:
1009 # One of the following:
1010 # :NONE, :REQUIRED, :OPTIONAL
1012 # [Argument pattern:]
1013 # Acceptable option argument format, must be pre-defined with
1014 # OptionParser.accept or OptionParser#accept, or Regexp. This can appear
1015 # once or assigned as String if not present, otherwise causes an
1016 # ArgumentError. Examples:
1017 # Float, Time, Array
1019 # [Possible argument values:]
1021 # [:text, :binary, :auto]
1022 # %w[iso-2022-jp shift_jis euc-jp utf8 binary]
1023 # { "jis" => "iso-2022-jp", "sjis" => "shift_jis" }
1025 # [Long style switch:]
1026 # Specifies a long style switch which takes a mandatory, optional or no
1027 # argument. It's a string of the following form:
1028 # "--switch=MANDATORY" or "--switch MANDATORY"
1029 # "--switch[=OPTIONAL]"
1032 # [Short style switch:]
1033 # Specifies short style switch which takes a mandatory, optional or no
1034 # argument. It's a string of the following form:
1038 # There is also a special form which matches character range (not full
1039 # set of regural expression):
1041 # "-[a-z][OPTIONAL]"
1044 # [Argument style and description:]
1045 # Instead of specifying mandatory or optional orguments directly in the
1046 # switch parameter, this separate parameter can be used.
1051 # Description string for the option.
1055 # Handler for the parsed argument value. Either give a block or pass a
1056 # Proc or Method as an argument.
1058 def make_switch(opts, block = nil)
1059 short, long, nolong, style, pattern, conv, not_pattern, not_conv, not_style = [], [], []
1060 ldesc, sdesc, desc, arg = [], [], []
1061 default_style = Switch::NoArgument
1062 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 {|(o, *v)| pattern[o] = v.fetch(0) {o}}
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, sw, val, rest = nil
1247 nonopt ||= proc {|arg| throw :terminate, arg}
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 |sw|
1302 sw.block.call(arg) if Switch === sw and sw.match_nonswitch?(arg)
1312 visit(:search, :short, nil) {|sw| sw.block.call(*argv) if !sw.pattern}
1316 private :parse_in_order
1319 # Parses command line arguments +argv+ in permutation mode and returns
1320 # list of non-option arguments.
1323 argv = argv[0].dup if argv.size == 1 and Array === argv[0]
1328 # Same as #permute, but removes switches destructively.
1330 def permute!(argv = default_argv)
1333 order!(argv) {|arg| nonopts << arg}
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)
1411 @stack.reverse_each do |el|
1412 el.send(id, *args, &block)
1419 # Searches +key+ in @stack for +id+ hash and returns or yields the result.
1422 block_given = block_given?
1423 visit(:search, id, key) do |k|
1424 return block_given ? yield(k) : k
1430 # Completes shortened long style option switch and returns pair of
1431 # canonical switch and switch descriptor OptionParser::Switch.
1433 # +id+:: Searching table.
1434 # +opt+:: Searching key.
1435 # +icase+:: Search case insensitive if true.
1436 # +pat+:: Optional pattern for completion.
1438 def complete(typ, opt, icase = false, *pat)
1440 search(typ, opt) {|sw| return [sw, opt]} # exact match or...
1442 raise AmbiguousOption, catch(:ambiguous) {
1443 visit(:complete, typ, opt, icase, *pat) {|opt, *sw| return sw}
1444 raise InvalidOption, opt
1450 # Loads options from file names as +filename+. Does nothing when the file
1451 # is not present. Returns whether successfully loaded.
1453 # +filename+ defaults to basename of the program without suffix in a
1454 # directory ~/.options.
1456 def load(filename = nil)
1458 filename ||= File.expand_path(File.basename($0, '.*'), '~/.options')
1463 parse(*IO.readlines(filename).each {|s| s.chomp!})
1465 rescue Errno::ENOENT, Errno::ENOTDIR
1471 # Parses environment variable +env+ or its uppercase with splitting like a
1474 # +env+ defaults to the basename of the program.
1476 def environment(env = File.basename($0, '.*'))
1477 env = ENV[env] || ENV[env.upcase] or return
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 {|s| s unless s.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)