class OptionParser
RCSID = %w$Id: optparse.rb 22469 2009-02-20 11:43:35Z shyouhei $[1..-1].each {|s| s.freeze}.freeze
Version = (RCSID[1].split('.').collect {|s| s.to_i}.extend(Comparable).freeze if RCSID[1])
LastModified = (Time.gm(*RCSID[2, 2].join('-').scan(/\d+/).collect {|s| s.to_i}) if RCSID[2])
Release = RCSID[2]
NoArgument = [NO_ARGUMENT = :NONE, nil].freeze
RequiredArgument = [REQUIRED_ARGUMENT = :REQUIRED, true].freeze
OptionalArgument = [OPTIONAL_ARGUMENT = :OPTIONAL, false].freeze
module Completion
def complete(key, icase = false, pat = nil)
pat ||= Regexp.new('\A' + Regexp.quote(key).gsub(/\w+\b/, '\&\w*'),
icase)
canon, sw, k, v, cn = nil
candidates = []
each do |k, *v|
(if Regexp === k
kn = nil
k === key
else
kn = defined?(k.id2name) ? k.id2name : k
pat === kn
end) or next
v << k if v.empty?
candidates << [k, v, kn]
end
candidates = candidates.sort_by {|k, v, kn| kn.size}
if candidates.size == 1
canon, sw, * = candidates[0]
elsif candidates.size > 1
canon, sw, cn = candidates.shift
candidates.each do |k, v, kn|
next if sw == v
if String === cn and String === kn
if cn.rindex(kn, 0)
canon, sw, cn = k, v, kn
next
elsif kn.rindex(cn, 0)
next
end
end
throw :ambiguous, key
end
end
if canon
block_given? or return key, *sw
yield(key, *sw)
end
end
def convert(opt = nil, val = nil, *)
val
end
end
class OptionMap < Hash
include Completion
end
class Switch
attr_reader :pattern, :conv, :short, :long, :arg, :desc, :block
def self.guess(arg)
case arg
when ""
t = self
when /\A=?\[/
t = Switch::OptionalArgument
when /\A\s+\[/
t = Switch::PlacedArgument
else
t = Switch::RequiredArgument
end
self >= t or incompatible_argument_styles(arg, t)
t
end
def self.incompatible_argument_styles(arg, t)
raise ArgumentError, "#{arg}: incompatible argument styles\n #{self}, #{t}"
end
def self.pattern
NilClass
end
def initialize(pattern = nil, conv = nil,
short = nil, long = nil, arg = nil,
desc = ([] if short or long), block = Proc.new)
raise if Array === pattern
@pattern, @conv, @short, @long, @arg, @desc, @block =
pattern, conv, short, long, arg, desc, block
end
def parse_arg(arg)
pattern or return nil, arg
unless m = pattern.match(arg)
yield(InvalidArgument, arg)
return arg, nil
end
if String === m
m = [s = m]
else
m = m.to_a
s = m[0]
return nil, m unless String === s
end
raise InvalidArgument, arg unless arg.rindex(s, 0)
return nil, m if s.length == arg.length
yield(InvalidArgument, arg) return arg[s.length..-1], m
end
private :parse_arg
def conv_arg(arg, val = nil)
if conv
val = conv.call(*val)
else
val = proc {|val| val}.call(*val)
end
return arg, block, val
end
private :conv_arg
def summarize(sdone = [], ldone = [], width = 1, max = width - 1, indent = "")
sopts, lopts, s = [], [], nil
@short.each {|s| sdone.fetch(s) {sopts << s}; sdone[s] = true} if @short
@long.each {|s| ldone.fetch(s) {lopts << s}; ldone[s] = true} if @long
return if sopts.empty? and lopts.empty?
left = [sopts.join(', ')]
right = desc.dup
while s = lopts.shift
l = left[-1].length + s.length
l += arg.length if left.size == 1 && arg
l < max or sopts.empty? or left << ''
left[-1] << if left[-1].empty? then ' ' * 4 else ', ' end << s
end
left[0] << arg if arg
mlen = left.collect {|s| s.length}.max.to_i
while mlen > width and l = left.shift
mlen = left.collect {|s| s.length}.max.to_i if l.length == mlen
yield(indent + l)
end
while begin l = left.shift; r = right.shift; l or r end
l = l.to_s.ljust(width) + ' ' + r if r and !r.empty?
yield(indent + l)
end
self
end
def add_banner(to) unless @short or @long
s = desc.join
to << " [" + s + "]..." unless s.empty?
end
to
end
def match_nonswitch?(str) @pattern =~ str unless @short or @long
end
def switch_name
(long.first || short.first).sub(/\A-+(?:\[no-\])?/, '')
end
class NoArgument < self
def parse(arg, argv)
yield(NeedlessArgument, arg) if arg
conv_arg(arg)
end
def self.incompatible_argument_styles(*)
end
def self.pattern
Object
end
end
class RequiredArgument < self
def parse(arg, argv)
unless arg
raise MissingArgument if argv.empty?
arg = argv.shift
end
conv_arg(*parse_arg(arg) {|*exc| raise(*exc)})
end
end
class OptionalArgument < self
def parse(arg, argv, &error)
if arg
conv_arg(*parse_arg(arg, &error))
else
conv_arg(arg)
end
end
end
class PlacedArgument < self
def parse(arg, argv, &error)
if !(val = arg) and (argv.empty? or /\A-/ =~ (val = argv[0]))
return nil, block, nil
end
opt = (val = parse_arg(val, &error))[1]
val = conv_arg(*val)
if opt and !arg
argv.shift
else
val[0] = nil
end
val
end
end
end
class List
attr_reader :atype
attr_reader :short
attr_reader :long
attr_reader :list
def initialize
@atype = {}
@short = OptionMap.new
@long = OptionMap.new
@list = []
end
def accept(t, pat = /.*/nm, &block)
if pat
pat.respond_to?(:match) or raise TypeError, "has no `match'"
else
pat = t if t.respond_to?(:match)
end
unless block
block = pat.method(:convert).to_proc if pat.respond_to?(:convert)
end
@atype[t] = [pat, block]
end
def reject(t)
@atype.delete(t)
end
def update(sw, sopts, lopts, nsw = nil, nlopts = nil)
o = nil
sopts.each {|o| @short[o] = sw} if sopts
lopts.each {|o| @long[o] = sw} if lopts
nlopts.each {|o| @long[o] = nsw} if nsw and nlopts
used = @short.invert.update(@long.invert)
@list.delete_if {|o| Switch === o and !used[o]}
end
private :update
def prepend(*args)
update(*args)
@list.unshift(args[0])
end
def append(*args)
update(*args)
@list.push(args[0])
end
def search(id, key)
if list = __send__(id)
val = list.fetch(key) {return nil}
block_given? ? yield(val) : val
end
end
def complete(id, opt, icase = false, *pat, &block)
__send__(id).complete(opt, icase, *pat, &block)
end
def each_option(&block)
list.each(&block)
end
def summarize(*args, &block)
sum = []
list.reverse_each do |opt|
if opt.respond_to?(:summarize) s = []
opt.summarize(*args) {|l| s << l}
sum.concat(s.reverse)
elsif !opt or opt.empty?
sum << ""
elsif opt.respond_to?(:each_line)
sum.concat([*opt.each_line].reverse)
else
sum.concat([*opt.each].reverse)
end
end
sum.reverse_each(&block)
end
def add_banner(to) list.each do |opt|
if opt.respond_to?(:add_banner)
opt.add_banner(to)
end
end
to
end
end
class CompletingHash < Hash
include Completion
def match(key)
return key, *fetch(key) {
raise AmbiguousArgument, catch(:ambiguous) {return complete(key)}
}
end
end
ArgumentStyle = {}
NoArgument.each {|el| ArgumentStyle[el] = Switch::NoArgument}
RequiredArgument.each {|el| ArgumentStyle[el] = Switch::RequiredArgument}
OptionalArgument.each {|el| ArgumentStyle[el] = Switch::OptionalArgument}
ArgumentStyle.freeze
DefaultList = List.new
DefaultList.short['-'] = Switch::NoArgument.new {}
DefaultList.long[''] = Switch::NoArgument.new {throw :terminate}
Officious = {}
Officious['help'] = proc do |parser|
Switch::NoArgument.new do
puts parser.help
exit
end
end
Officious['version'] = proc do |parser|
Switch::OptionalArgument.new do |pkg|
if pkg
begin
require 'optparse/version'
rescue LoadError
else
show_version(*pkg.split(/,/)) or
abort("#{parser.program_name}: no version found in package #{pkg}")
exit
end
end
v = parser.ver or abort("#{parser.program_name}: version unknown")
puts v
exit
end
end
def self.with(*args, &block)
opts = new(*args)
opts.instance_eval(&block)
opts
end
def self.inc(arg, default = nil)
case arg
when Integer
arg.nonzero?
when nil
default.to_i + 1
end
end
def inc(*args)
self.class.inc(*args)
end
def initialize(banner = nil, width = 32, indent = ' ' * 4)
@stack = [DefaultList, List.new, List.new]
@program_name = nil
@banner = banner
@summary_width = width
@summary_indent = indent
@default_argv = ARGV
add_officious
yield self if block_given?
end
def add_officious # :nodoc:
list = base()
Officious.each do |opt, block|
list.long[opt] ||= block.call(self)
end
end
def terminate(arg = nil)
self.class.terminate(arg)
end
def self.terminate(arg = nil)
throw :terminate, arg
end
@stack = [DefaultList]
def self.top() DefaultList end
def accept(*args, &blk) top.accept(*args, &blk) end
def self.accept(*args, &blk) top.accept(*args, &blk) end
def reject(*args, &blk) top.reject(*args, &blk) end
def self.reject(*args, &blk) top.reject(*args, &blk) end
attr_writer :banner
attr_writer :program_name
attr_accessor :summary_width
attr_accessor :summary_indent
attr_accessor :default_argv
def banner
unless @banner
@banner = "Usage: #{program_name} [options]"
visit(:add_banner, @banner)
end
@banner
end
def program_name
@program_name || File.basename($0, '.*')
end
alias set_banner banner=
alias set_program_name program_name=
alias set_summary_width summary_width=
alias set_summary_indent summary_indent=
attr_writer :version
attr_writer :release
def version
@version || (defined?(::Version) && ::Version)
end
def release
@release || (defined?(::Release) && ::Release) || (defined?(::RELEASE) && ::RELEASE)
end
def ver
if v = version
str = "#{program_name} #{[v].join('.')}"
str << " (#{v})" if v = release
str
end
end
def warn(mesg = $!)
super("#{program_name}: #{mesg}")
end
def abort(mesg = $!)
super("#{program_name}: #{mesg}")
end
def top
@stack[-1]
end
def base
@stack[1]
end
def new
@stack.push(List.new)
if block_given?
yield self
else
self
end
end
def remove
@stack.pop
end
def summarize(to = [], width = @summary_width, max = width - 1, indent = @summary_indent, &blk)
blk ||= proc {|l| to << (l.index($/, -1) ? l : l + $/)}
visit(:summarize, {}, {}, width, max, indent, &blk)
to
end
def help; summarize(banner.to_s.sub(/\n?\z/, "\n")) end
alias to_s help
def to_a; summarize(banner.to_a.dup) end
def notwice(obj, prv, msg)
unless !prv or prv == obj
begin
raise ArgumentError, "argument #{msg} given twice: #{obj}"
rescue
$@[0, 2] = nil
raise
end
end
obj
end
private :notwice
def make_switch(opts, block = nil)
short, long, nolong, style, pattern, conv, not_pattern, not_conv, not_style = [], [], []
ldesc, sdesc, desc, arg = [], [], []
default_style = Switch::NoArgument
default_pattern = nil
klass = nil
o = nil
n, q, a = nil
opts.each do |o|
next if search(:atype, o) do |pat, c|
klass = notwice(o, klass, 'type')
if not_style and not_style != Switch::NoArgument
not_pattern, not_conv = pat, c
else
default_pattern, conv = pat, c
end
end
if !(String === o) and o.respond_to?(:match)
pattern = notwice(o, pattern, 'pattern')
conv = pattern.method(:convert).to_proc if pattern.respond_to?(:convert)
next
end
case o
when Proc, Method
block = notwice(o, block, 'block')
when Array, Hash
case pattern
when CompletingHash
when nil
pattern = CompletingHash.new
conv = pattern.method(:convert).to_proc if pattern.respond_to?(:convert)
else
raise ArgumentError, "argument pattern given twice"
end
o.each {|(o, *v)| pattern[o] = v.fetch(0) {o}}
when Module
raise ArgumentError, "unsupported argument type: #{o}"
when *ArgumentStyle.keys
style = notwice(ArgumentStyle[o], style, 'style')
when /^--no-([^\[\]=\s]*)(.+)?/
q, a = $1, $2
o = notwice(a ? Object : TrueClass, klass, 'type')
not_pattern, not_conv = search(:atype, o) unless not_style
not_style = (not_style || default_style).guess(arg = a) if a
default_style = Switch::NoArgument
default_pattern, conv = search(:atype, FalseClass) unless default_pattern
ldesc << "--no-#{q}"
long << 'no-' + (q = q.downcase)
nolong << q
when /^--\[no-\]([^\[\]=\s]*)(.+)?/
q, a = $1, $2
o = notwice(a ? Object : TrueClass, klass, 'type')
if a
default_style = default_style.guess(arg = a)
default_pattern, conv = search(:atype, o) unless default_pattern
end
ldesc << "--[no-]#{q}"
long << (o = q.downcase)
not_pattern, not_conv = search(:atype, FalseClass) unless not_style
not_style = Switch::NoArgument
nolong << 'no-' + o
when /^--([^\[\]=\s]*)(.+)?/
q, a = $1, $2
if a
o = notwice(NilClass, klass, 'type')
default_style = default_style.guess(arg = a)
default_pattern, conv = search(:atype, o) unless default_pattern
end
ldesc << "--#{q}"
long << (o = q.downcase)
when /^-(\[\^?\]?(?:[^\\\]]|\\.)*\])(.+)?/
q, a = $1, $2
o = notwice(Object, klass, 'type')
if a
default_style = default_style.guess(arg = a)
default_pattern, conv = search(:atype, o) unless default_pattern
end
sdesc << "-#{q}"
short << Regexp.new(q)
when /^-(.)(.+)?/
q, a = $1, $2
if a
o = notwice(NilClass, klass, 'type')
default_style = default_style.guess(arg = a)
default_pattern, conv = search(:atype, o) unless default_pattern
end
sdesc << "-#{q}"
short << q
when /^=/
style = notwice(default_style.guess(arg = o), style, 'style')
default_pattern, conv = search(:atype, Object) unless default_pattern
else
desc.push(o)
end
end
default_pattern, conv = search(:atype, default_style.pattern) unless default_pattern
if !(short.empty? and long.empty?)
s = (style || default_style).new(pattern || default_pattern,
conv, sdesc, ldesc, arg, desc, block)
elsif !block
raise ArgumentError, "no switch given" if style or pattern
s = desc
else
short << pattern
s = (style || default_style).new(pattern,
conv, nil, nil, arg, desc, block)
end
return s, short, long,
(not_style.new(not_pattern, not_conv, sdesc, ldesc, nil, desc, block) if not_style),
nolong
end
def define(*opts, &block)
top.append(*(sw = make_switch(opts, block)))
sw[0]
end
def on(*opts, &block)
define(*opts, &block)
self
end
alias def_option define
def define_head(*opts, &block)
top.prepend(*(sw = make_switch(opts, block)))
sw[0]
end
def on_head(*opts, &block)
define_head(*opts, &block)
self
end
alias def_head_option define_head
def define_tail(*opts, &block)
base.append(*(sw = make_switch(opts, block)))
sw[0]
end
def on_tail(*opts, &block)
define_tail(*opts, &block)
self
end
alias def_tail_option define_tail
def separator(string)
top.append(string, nil, nil)
end
def order(*argv, &block)
argv = argv[0].dup if argv.size == 1 and Array === argv[0]
order!(argv, &block)
end
def order!(argv = default_argv, &nonopt)
parse_in_order(argv, &nonopt)
end
def parse_in_order(argv = default_argv, setter = nil, &nonopt) opt, arg, sw, val, rest = nil
nonopt ||= proc {|arg| throw :terminate, arg}
argv.unshift(arg) if arg = catch(:terminate) {
while arg = argv.shift
case arg
when /\A--([^=]*)(?:=(.*))?/nm
opt, rest = $1, $2
begin
sw, = complete(:long, opt, true)
rescue ParseError
raise $!.set_option(arg, true)
end
begin
opt, cb, val = sw.parse(rest, argv) {|*exc| raise(*exc)}
val = cb.call(val) if cb
setter.call(sw.switch_name, val) if setter
rescue ParseError
raise $!.set_option(arg, rest)
end
when /\A-(.)((=).*|.+)?/nm
opt, has_arg, eq, val, rest = $1, $3, $3, $2, $2
begin
sw, = search(:short, opt)
unless sw
begin
sw, = complete(:short, opt)
val = arg.sub(/\A-/, '')
has_arg = true
rescue InvalidOption
sw, = complete(:long, opt)
eq ||= !rest
end
end
rescue ParseError
raise $!.set_option(arg, true)
end
begin
opt, cb, val = sw.parse(val, argv) {|*exc| raise(*exc) if eq}
raise InvalidOption, arg if has_arg and !eq and arg == "-#{opt}"
argv.unshift(opt) if opt and (opt = opt.sub(/\A-*/, '-')) != '-'
val = cb.call(val) if cb
setter.call(sw.switch_name, val) if setter
rescue ParseError
raise $!.set_option(arg, arg.length > 2)
end
else
catch(:prune) do
visit(:each_option) do |sw|
sw.block.call(arg) if Switch === sw and sw.match_nonswitch?(arg)
end
nonopt.call(arg)
end
end
end
nil
}
visit(:search, :short, nil) {|sw| sw.block.call(*argv) if !sw.pattern}
argv
end
private :parse_in_order
def permute(*argv)
argv = argv[0].dup if argv.size == 1 and Array === argv[0]
permute!(argv)
end
def permute!(argv = default_argv)
nonopts = []
arg = nil
order!(argv) {|arg| nonopts << arg}
argv[0, 0] = nonopts
argv
end
def parse(*argv)
argv = argv[0].dup if argv.size == 1 and Array === argv[0]
parse!(argv)
end
def parse!(argv = default_argv)
if ENV.include?('POSIXLY_CORRECT')
order!(argv)
else
permute!(argv)
end
end
def getopts(*args)
argv = Array === args.first ? args.shift : default_argv
single_options, *long_options = *args
result = {}
single_options.scan(/(.)(:)?/) do |opt, val|
if val
result[opt] = nil
define("-#{opt} VAL")
else
result[opt] = false
define("-#{opt}")
end
end if single_options
long_options.each do |arg|
opt, val = arg.split(':', 2)
if val
result[opt] = val.empty? ? nil : val
define("--#{opt} VAL")
else
result[opt] = false
define("--#{opt}")
end
end
parse_in_order(argv, result.method(:[]=))
result
end
def self.getopts(*args)
new.getopts(*args)
end
def visit(id, *args, &block)
el = nil
@stack.reverse_each do |el|
el.send(id, *args, &block)
end
nil
end
private :visit
def search(id, key)
block_given = block_given?
visit(:search, id, key) do |k|
return block_given ? yield(k) : k
end
end
private :search
def complete(typ, opt, icase = false, *pat)
if pat.empty?
search(typ, opt) {|sw| return [sw, opt]} end
raise AmbiguousOption, catch(:ambiguous) {
visit(:complete, typ, opt, icase, *pat) {|opt, *sw| return sw}
raise InvalidOption, opt
}
end
private :complete
def load(filename = nil)
begin
filename ||= File.expand_path(File.basename($0, '.*'), '~/.options')
rescue
return false
end
begin
parse(*IO.readlines(filename).each {|s| s.chomp!})
true
rescue Errno::ENOENT, Errno::ENOTDIR
false
end
end
def environment(env = File.basename($0, '.*'))
env = ENV[env] || ENV[env.upcase] or return
require 'shellwords'
parse(*Shellwords.shellwords(env))
end
accept(Object) {|s,|s or s.nil?}
accept(NilClass) {|s,|s}
accept(String, /.+/nm) {|s,*|s}
decimal = '\d+(?:_\d+)*'
binary = 'b[01]+(?:_[01]+)*'
hex = 'x[\da-f]+(?:_[\da-f]+)*'
octal = "0(?:[0-7]*(?:_[0-7]+)*|#{binary}|#{hex})"
integer = "#{octal}|#{decimal}"
accept(Integer, %r"\A[-+]?(?:#{integer})"io) {|s,| Integer(s) if s}
float = "(?:#{decimal}(?:\\.(?:#{decimal})?)?|\\.#{decimal})(?:E[-+]?#{decimal})?"
floatpat = %r"\A[-+]?#{float}"io
accept(Float, floatpat) {|s,| s.to_f if s}
accept(Numeric, %r"\A[-+]?(?:#{octal}|#{float})"io) {|s,| eval(s) if s}
DecimalInteger = /\A[-+]?#{decimal}/io
accept(DecimalInteger) {|s,| s.to_i if s}
OctalInteger = /\A[-+]?(?:[0-7]+(?:_[0-7]+)*|0(?:#{binary}|#{hex}))/io
accept(OctalInteger) {|s,| s.oct if s}
DecimalNumeric = floatpat accept(DecimalNumeric) {|s,| eval(s) if s}
yesno = CompletingHash.new
%w[- no false].each {|el| yesno[el] = false}
%w[+ yes true].each {|el| yesno[el] = true}
yesno['nil'] = false accept(TrueClass, yesno) {|arg, val| val == nil or val}
accept(FalseClass, yesno) {|arg, val| val != nil and val}
accept(Array) do |s,|
if s
s = s.split(',').collect {|s| s unless s.empty?}
end
s
end
accept(Regexp, %r"\A/((?:\\.|[^\\])*)/([[:alpha:]]+)?\z|.*") do |all, s, o|
f = 0
if o
f |= Regexp::IGNORECASE if /i/ =~ o
f |= Regexp::MULTILINE if /m/ =~ o
f |= Regexp::EXTENDED if /x/ =~ o
k = o.delete("^imx")
end
Regexp.new(s || all, f, k)
end
class ParseError < RuntimeError
Reason = 'parse error'.freeze
def initialize(*args)
@args = args
@reason = nil
end
attr_reader :args
attr_writer :reason
def recover(argv)
argv[0, 0] = @args
argv
end
def set_option(opt, eq)
if eq
@args[0] = opt
else
@args.unshift(opt)
end
self
end
def reason
@reason || self.class::Reason
end
def inspect
"#<#{self.class.to_s}: #{args.join(' ')}>"
end
def message
reason + ': ' + args.join(' ')
end
alias to_s message
end
class AmbiguousOption < ParseError
const_set(:Reason, 'ambiguous option'.freeze)
end
class NeedlessArgument < ParseError
const_set(:Reason, 'needless argument'.freeze)
end
class MissingArgument < ParseError
const_set(:Reason, 'missing argument'.freeze)
end
class InvalidOption < ParseError
const_set(:Reason, 'invalid option'.freeze)
end
class InvalidArgument < ParseError
const_set(:Reason, 'invalid argument'.freeze)
end
class AmbiguousArgument < InvalidArgument
const_set(:Reason, 'ambiguous argument'.freeze)
end
module Arguable
def options=(opt)
unless @optparse = opt
class << self
undef_method(:options)
undef_method(:options=)
end
end
end
def options
@optparse ||= OptionParser.new
@optparse.default_argv = self
block_given? or return @optparse
begin
yield @optparse
rescue ParseError
@optparse.warn $!
nil
end
end
def order!(&blk) options.order!(self, &blk) end
def permute!() options.permute!(self) end
def parse!() options.parse!(self) end
def getopts(*args)
options.getopts(self, *args)
end
def self.extend_object(obj)
super
obj.instance_eval {@optparse = nil}
end
def initialize(*args)
super
@optparse = nil
end
end
module Acceptables
const_set(:DecimalInteger, OptionParser::DecimalInteger)
const_set(:OctalInteger, OptionParser::OctalInteger)
const_set(:DecimalNumeric, OptionParser::DecimalNumeric)
end
end
ARGV.extend(OptionParser::Arguable)
if $0 == __FILE__
Version = OptionParser::Version
ARGV.options {|q|
q.parse!.empty? or puts "what's #{ARGV.join(' ')}?"
} or abort(ARGV.options.to_s)
end