optparse.rb

Path: lib/optparse.rb
Last Update: Tue Jan 17 18:02:18 +0000 2012

optparse.rb - command-line option analysis with the OptionParser class.

Author:Nobu Nakada
Documentation:Nobu Nakada and Gavin Sinclair.

See OptionParser for documentation.

Required files

shellwords  

Methods

abort   accept   accept   banner   base   complete   def_head_option   def_option   def_tail_option   define   define_head   define_tail   environment   getopts   getopts   help   inc   inc   load   make_switch   new   new   notwice   on   on_head   on_tail   order   order!   parse   parse!   permute   permute!   program_name   reject   reject   release   remove   search   separator   summarize   terminate   terminate   to_a   to_s   top   top   ver   version   visit   warn   with  

Constants

DecimalInteger = /\A[-+]?#{decimal}/io   Decimal integer format, to be converted to Integer.
OctalInteger = /\A[-+]?(?:[0-7]+(?:_[0-7]+)*|0(?:#{binary}|#{hex}))/io   Ruby/C like octal/hexadecimal/binary integer format, to be converted to Integer.
DecimalNumeric = floatpat # decimal integer is allowed as float also.   Decimal integer/float number format, to be converted to Integer for integer format, Float for float format.

External Aliases

banner= -> set_banner
  for experimental cascading :-)
program_name= -> set_program_name
summary_width= -> set_summary_width
summary_indent= -> set_summary_indent

Public Class methods

See accept.

[Source]

     # File lib/optparse.rb, line 828
828:   def self.accept(*args, &blk) top.accept(*args, &blk) end

See getopts.

[Source]

      # File lib/optparse.rb, line 1407
1407:   def self.getopts(*args)
1408:     new.getopts(*args)
1409:   end

Returns an incremented value of default according to arg.

[Source]

     # File lib/optparse.rb, line 764
764:   def self.inc(arg, default = nil)
765:     case arg
766:     when Integer
767:       arg.nonzero?
768:     when nil
769:       default.to_i + 1
770:     end
771:   end

Initializes the instance and yields itself if called with a block.

banner:Banner message.
width:Summary width.
indent:Summary indent.

[Source]

     # File lib/optparse.rb, line 783
783:   def initialize(banner = nil, width = 32, indent = ' ' * 4)
784:     @stack = [DefaultList, List.new, List.new]
785:     @program_name = nil
786:     @banner = banner
787:     @summary_width = width
788:     @summary_indent = indent
789:     @default_argv = ARGV
790:     add_officious
791:     yield self if block_given?
792:   end

See reject.

[Source]

     # File lib/optparse.rb, line 841
841:   def self.reject(*args, &blk) top.reject(*args, &blk) end

[Source]

     # File lib/optparse.rb, line 808
808:   def self.terminate(arg = nil)
809:     throw :terminate, arg
810:   end

[Source]

     # File lib/optparse.rb, line 813
813:   def self.top() DefaultList end

Initializes a new instance and evaluates the optional block in context of the instance. Arguments args are passed to new, see there for description of parameters.

This method is deprecated, its behavior corresponds to the older new method.

[Source]

     # File lib/optparse.rb, line 755
755:   def self.with(*args, &block)
756:     opts = new(*args)
757:     opts.instance_eval(&block)
758:     opts
759:   end

Public Instance methods

[Source]

     # File lib/optparse.rb, line 922
922:   def abort(mesg = $!)
923:     super("#{program_name}: #{mesg}")
924:   end

Directs to accept specified class t. The argument string is passed to the block in which it should be converted to the desired class.

t:Argument class specifier, any object including Class.
pat:Pattern for argument, defaults to t if it responds to match.
  accept(t, pat, &block)

[Source]

     # File lib/optparse.rb, line 824
824:   def accept(*args, &blk) top.accept(*args, &blk) end

Heading banner preceding summary.

[Source]

     # File lib/optparse.rb, line 866
866:   def banner
867:     unless @banner
868:       @banner = "Usage: #{program_name} [options]"
869:       visit(:add_banner, @banner)
870:     end
871:     @banner
872:   end

Subject of on_tail.

[Source]

     # File lib/optparse.rb, line 936
936:   def base
937:     @stack[1]
938:   end
def_head_option(*opts, &block)

Alias for define_head

def_option(*opts, &block)

Alias for define

def_tail_option(*opts, &block)

Alias for define_tail

[Source]

      # File lib/optparse.rb, line 1183
1183:   def define(*opts, &block)
1184:     top.append(*(sw = make_switch(opts, block)))
1185:     sw[0]
1186:   end

[Source]

      # File lib/optparse.rb, line 1198
1198:   def define_head(*opts, &block)
1199:     top.prepend(*(sw = make_switch(opts, block)))
1200:     sw[0]
1201:   end

[Source]

      # File lib/optparse.rb, line 1212
1212:   def define_tail(*opts, &block)
1213:     base.append(*(sw = make_switch(opts, block)))
1214:     sw[0]
1215:   end

Parses environment variable env or its uppercase with splitting like a shell.

env defaults to the basename of the program.

[Source]

      # File lib/optparse.rb, line 1482
1482:   def environment(env = File.basename($0, '.*'))
1483:     env = ENV[env] || ENV[env.upcase] or return
1484:     require 'shellwords'
1485:     parse(*Shellwords.shellwords(env))
1486:   end

Wrapper method for getopts.rb.

  params = ARGV.getopts("ab:", "foo", "bar:")
  # params[:a] = true   # -a
  # params[:b] = "1"    # -b1
  # params[:foo] = "1"  # --foo
  # params[:bar] = "x"  # --bar x

[Source]

      # File lib/optparse.rb, line 1373
1373:   def getopts(*args)
1374:     argv = Array === args.first ? args.shift : default_argv
1375:     single_options, *long_options = *args
1376: 
1377:     result = {}
1378: 
1379:     single_options.scan(/(.)(:)?/) do |opt, val|
1380:       if val
1381:         result[opt] = nil
1382:         define("-#{opt} VAL")
1383:       else
1384:         result[opt] = false
1385:         define("-#{opt}")
1386:       end
1387:     end if single_options
1388: 
1389:     long_options.each do |arg|
1390:       opt, val = arg.split(':', 2)
1391:       if val
1392:         result[opt] = val.empty? ? nil : val
1393:         define("--#{opt} VAL")
1394:       else
1395:         result[opt] = false
1396:         define("--#{opt}")
1397:       end
1398:     end
1399: 
1400:     parse_in_order(argv, result.method(:[]=))
1401:     result
1402:   end

Returns option summary string.

[Source]

     # File lib/optparse.rb, line 977
977:   def help; summarize(banner.to_s.sub(/\n?\z/, "\n")) end

[Source]

     # File lib/optparse.rb, line 772
772:   def inc(*args)
773:     self.class.inc(*args)
774:   end

Loads options from file names as filename. Does nothing when the file is not present. Returns whether successfully loaded.

filename defaults to basename of the program without suffix in a directory ~/.options.

[Source]

      # File lib/optparse.rb, line 1462
1462:   def load(filename = nil)
1463:     begin
1464:       filename ||= File.expand_path(File.basename($0, '.*'), '~/.options')
1465:     rescue
1466:       return false
1467:     end
1468:     begin
1469:       parse(*IO.readlines(filename).each {|s| s.chomp!})
1470:       true
1471:     rescue Errno::ENOENT, Errno::ENOTDIR
1472:       false
1473:     end
1474:   end

Creates an OptionParser::Switch from the parameters. The parsed argument value is passed to the given block, where it can be processed.

See at the beginning of OptionParser for some full examples.

opts can include the following elements:

Argument style:
One of the following:
  :NONE, :REQUIRED, :OPTIONAL
Argument pattern:
Acceptable option argument format, must be pre-defined with OptionParser.accept or OptionParser#accept, or Regexp. This can appear once or assigned as String if not present, otherwise causes an ArgumentError. Examples:
  Float, Time, Array
Possible argument values:
Hash or Array.
  [:text, :binary, :auto]
  %w[iso-2022-jp shift_jis euc-jp utf8 binary]
  { "jis" => "iso-2022-jp", "sjis" => "shift_jis" }
Long style switch:
Specifies a long style switch which takes a mandatory, optional or no argument. It‘s a string of the following form:
  "--switch=MANDATORY" or "--switch MANDATORY"
  "--switch[=OPTIONAL]"
  "--switch"
Short style switch:
Specifies short style switch which takes a mandatory, optional or no argument. It‘s a string of the following form:
  "-xMANDATORY"
  "-x[OPTIONAL]"
  "-x"

There is also a special form which matches character range (not full set of regular expression):

  "-[a-z]MANDATORY"
  "-[a-z][OPTIONAL]"
  "-[a-z]"
Argument style and description:
Instead of specifying mandatory or optional arguments directly in the switch parameter, this separate parameter can be used.
  "=MANDATORY"
  "=[OPTIONAL]"
Description:
Description string for the option.
  "Run verbosely"
Handler:
Handler for the parsed argument value. Either give a block or pass a Proc or Method as an argument.

[Source]

      # File lib/optparse.rb, line 1064
1064:   def make_switch(opts, block = nil)
1065:     short, long, nolong, style, pattern, conv, not_pattern, not_conv, not_style = [], [], []
1066:     ldesc, sdesc, desc, arg = [], [], []
1067:     default_style = Switch::NoArgument
1068:     default_pattern = nil
1069:     klass = nil
1070:     o = nil
1071:     n, q, a = nil
1072: 
1073:     opts.each do |o|
1074:       # argument class
1075:       next if search(:atype, o) do |pat, c|
1076:         klass = notwice(o, klass, 'type')
1077:         if not_style and not_style != Switch::NoArgument
1078:           not_pattern, not_conv = pat, c
1079:         else
1080:           default_pattern, conv = pat, c
1081:         end
1082:       end
1083: 
1084:       # directly specified pattern(any object possible to match)
1085:       if !(String === o) and o.respond_to?(:match)
1086:         pattern = notwice(o, pattern, 'pattern')
1087:         conv = pattern.method(:convert).to_proc if pattern.respond_to?(:convert)
1088:         next
1089:       end
1090: 
1091:       # anything others
1092:       case o
1093:       when Proc, Method
1094:         block = notwice(o, block, 'block')
1095:       when Array, Hash
1096:         case pattern
1097:         when CompletingHash
1098:         when nil
1099:           pattern = CompletingHash.new
1100:           conv = pattern.method(:convert).to_proc if pattern.respond_to?(:convert)
1101:         else
1102:           raise ArgumentError, "argument pattern given twice"
1103:         end
1104:         o.each {|(o, *v)| pattern[o] = v.fetch(0) {o}}
1105:       when Module
1106:         raise ArgumentError, "unsupported argument type: #{o}"
1107:       when *ArgumentStyle.keys
1108:         style = notwice(ArgumentStyle[o], style, 'style')
1109:       when /^--no-([^\[\]=\s]*)(.+)?/
1110:         q, a = $1, $2
1111:         o = notwice(a ? Object : TrueClass, klass, 'type')
1112:         not_pattern, not_conv = search(:atype, o) unless not_style
1113:         not_style = (not_style || default_style).guess(arg = a) if a
1114:         default_style = Switch::NoArgument
1115:         default_pattern, conv = search(:atype, FalseClass) unless default_pattern
1116:         ldesc << "--no-#{q}"
1117:         long << 'no-' + (q = q.downcase)
1118:         nolong << q
1119:       when /^--\[no-\]([^\[\]=\s]*)(.+)?/
1120:         q, a = $1, $2
1121:         o = notwice(a ? Object : TrueClass, klass, 'type')
1122:         if a
1123:           default_style = default_style.guess(arg = a)
1124:           default_pattern, conv = search(:atype, o) unless default_pattern
1125:         end
1126:         ldesc << "--[no-]#{q}"
1127:         long << (o = q.downcase)
1128:         not_pattern, not_conv = search(:atype, FalseClass) unless not_style
1129:         not_style = Switch::NoArgument
1130:         nolong << 'no-' + o
1131:       when /^--([^\[\]=\s]*)(.+)?/
1132:         q, a = $1, $2
1133:         if a
1134:           o = notwice(NilClass, klass, 'type')
1135:           default_style = default_style.guess(arg = a)
1136:           default_pattern, conv = search(:atype, o) unless default_pattern
1137:         end
1138:         ldesc << "--#{q}"
1139:         long << (o = q.downcase)
1140:       when /^-(\[\^?\]?(?:[^\\\]]|\\.)*\])(.+)?/
1141:         q, a = $1, $2
1142:         o = notwice(Object, klass, 'type')
1143:         if a
1144:           default_style = default_style.guess(arg = a)
1145:           default_pattern, conv = search(:atype, o) unless default_pattern
1146:         end
1147:         sdesc << "-#{q}"
1148:         short << Regexp.new(q)
1149:       when /^-(.)(.+)?/
1150:         q, a = $1, $2
1151:         if a
1152:           o = notwice(NilClass, klass, 'type')
1153:           default_style = default_style.guess(arg = a)
1154:           default_pattern, conv = search(:atype, o) unless default_pattern
1155:         end
1156:         sdesc << "-#{q}"
1157:         short << q
1158:       when /^=/
1159:         style = notwice(default_style.guess(arg = o), style, 'style')
1160:         default_pattern, conv = search(:atype, Object) unless default_pattern
1161:       else
1162:         desc.push(o)
1163:       end
1164:     end
1165: 
1166:     default_pattern, conv = search(:atype, default_style.pattern) unless default_pattern
1167:     if !(short.empty? and long.empty?)
1168:       s = (style || default_style).new(pattern || default_pattern,
1169:                                        conv, sdesc, ldesc, arg, desc, block)
1170:     elsif !block
1171:       raise ArgumentError, "no switch given" if style or pattern
1172:       s = desc
1173:     else
1174:       short << pattern
1175:       s = (style || default_style).new(pattern,
1176:                                        conv, nil, nil, arg, desc, block)
1177:     end
1178:     return s, short, long,
1179:       (not_style.new(not_pattern, not_conv, sdesc, ldesc, nil, desc, block) if not_style),
1180:       nolong
1181:   end

Pushes a new List.

[Source]

     # File lib/optparse.rb, line 943
943:   def new
944:     @stack.push(List.new)
945:     if block_given?
946:       yield self
947:     else
948:       self
949:     end
950:   end

Add option switch and handler. See make_switch for an explanation of parameters.

[Source]

      # File lib/optparse.rb, line 1192
1192:   def on(*opts, &block)
1193:     define(*opts, &block)
1194:     self
1195:   end

Add option switch like with on, but at head of summary.

[Source]

      # File lib/optparse.rb, line 1206
1206:   def on_head(*opts, &block)
1207:     define_head(*opts, &block)
1208:     self
1209:   end

Add option switch like with on, but at tail of summary.

[Source]

      # File lib/optparse.rb, line 1220
1220:   def on_tail(*opts, &block)
1221:     define_tail(*opts, &block)
1222:     self
1223:   end

Parses command line arguments argv in order. When a block is given, each non-option argument is yielded.

Returns the rest of argv left unparsed.

[Source]

      # File lib/optparse.rb, line 1239
1239:   def order(*argv, &block)
1240:     argv = argv[0].dup if argv.size == 1 and Array === argv[0]
1241:     order!(argv, &block)
1242:   end

Same as order, but removes switches destructively.

[Source]

      # File lib/optparse.rb, line 1247
1247:   def order!(argv = default_argv, &nonopt)
1248:     parse_in_order(argv, &nonopt)
1249:   end

Parses command line arguments argv in order when environment variable POSIXLY_CORRECT is set, and in permutation mode otherwise.

[Source]

      # File lib/optparse.rb, line 1348
1348:   def parse(*argv)
1349:     argv = argv[0].dup if argv.size == 1 and Array === argv[0]
1350:     parse!(argv)
1351:   end

Same as parse, but removes switches destructively.

[Source]

      # File lib/optparse.rb, line 1356
1356:   def parse!(argv = default_argv)
1357:     if ENV.include?('POSIXLY_CORRECT')
1358:       order!(argv)
1359:     else
1360:       permute!(argv)
1361:     end
1362:   end

Parses command line arguments argv in permutation mode and returns list of non-option arguments.

[Source]

      # File lib/optparse.rb, line 1328
1328:   def permute(*argv)
1329:     argv = argv[0].dup if argv.size == 1 and Array === argv[0]
1330:     permute!(argv)
1331:   end

Same as permute, but removes switches destructively.

[Source]

      # File lib/optparse.rb, line 1336
1336:   def permute!(argv = default_argv)
1337:     nonopts = []
1338:     arg = nil
1339:     order!(argv) {|arg| nonopts << arg}
1340:     argv[0, 0] = nonopts
1341:     argv
1342:   end

Program name to be emitted in error message and default banner, defaults to $0.

[Source]

     # File lib/optparse.rb, line 878
878:   def program_name
879:     @program_name || File.basename($0, '.*')
880:   end

Directs to reject specified class argument.

t:Argument class specifier, any object including Class.
  reject(t)

[Source]

     # File lib/optparse.rb, line 837
837:   def reject(*args, &blk) top.reject(*args, &blk) end

Release code

[Source]

     # File lib/optparse.rb, line 903
903:   def release
904:     @release || (defined?(::Release) && ::Release) || (defined?(::RELEASE) && ::RELEASE)
905:   end

Removes the last List.

[Source]

     # File lib/optparse.rb, line 955
955:   def remove
956:     @stack.pop
957:   end

Add separator in summary.

[Source]

      # File lib/optparse.rb, line 1229
1229:   def separator(string)
1230:     top.append(string, nil, nil)
1231:   end

Puts option summary into to and returns to. Yields each line if a block is given.

to:Output destination, which must have method <<. Defaults to [].
width:Width of left side, defaults to @summary_width.
max:Maximum length allowed for left side, defaults to width - 1.
indent:Indentation, defaults to @summary_indent.

[Source]

     # File lib/optparse.rb, line 968
968:   def summarize(to = [], width = @summary_width, max = width - 1, indent = @summary_indent, &blk)
969:     blk ||= proc {|l| to << (l.index($/, -1) ? l : l + $/)}
970:     visit(:summarize, {}, {}, width, max, indent, &blk)
971:     to
972:   end

Terminates option parsing. Optional parameter arg is a string pushed back to be the first non-option argument.

[Source]

     # File lib/optparse.rb, line 805
805:   def terminate(arg = nil)
806:     self.class.terminate(arg)
807:   end

Returns option summary list.

[Source]

     # File lib/optparse.rb, line 983
983:   def to_a; summarize(banner.to_a.dup) end
to_s()

Alias for help

Subject of on / on_head, accept / reject

[Source]

     # File lib/optparse.rb, line 929
929:   def top
930:     @stack[-1]
931:   end

Returns version string from program_name, version and release.

[Source]

     # File lib/optparse.rb, line 910
910:   def ver
911:     if v = version
912:       str = "#{program_name} #{[v].join('.')}"
913:       str << " (#{v})" if v = release
914:       str
915:     end
916:   end

Version

[Source]

     # File lib/optparse.rb, line 896
896:   def version
897:     @version || (defined?(::Version) && ::Version)
898:   end

[Source]

     # File lib/optparse.rb, line 918
918:   def warn(mesg = $!)
919:     super("#{program_name}: #{mesg}")
920:   end

Private Instance methods

Completes shortened long style option switch and returns pair of canonical switch and switch descriptor OptionParser::Switch.

id:Searching table.
opt:Searching key.
icase:Search case insensitive if true.
pat:Optional pattern for completion.

[Source]

      # File lib/optparse.rb, line 1444
1444:   def complete(typ, opt, icase = false, *pat)
1445:     if pat.empty?
1446:       search(typ, opt) {|sw| return [sw, opt]} # exact match or...
1447:     end
1448:     raise AmbiguousOption, catch(:ambiguous) {
1449:       visit(:complete, typ, opt, icase, *pat) {|opt, *sw| return sw}
1450:       raise InvalidOption, opt
1451:     }
1452:   end

Checks if an argument is given twice, in which case an ArgumentError is raised. Called from OptionParser#switch only.

obj:New argument.
prv:Previously specified argument.
msg:Exception message.

[Source]

      # File lib/optparse.rb, line 993
 993:   def notwice(obj, prv, msg)
 994:     unless !prv or prv == obj
 995:       begin
 996:         raise ArgumentError, "argument #{msg} given twice: #{obj}"
 997:       rescue
 998:         $@[0, 2] = nil
 999:         raise
1000:       end
1001:     end
1002:     obj
1003:   end

Searches key in @stack for id hash and returns or yields the result.

[Source]

      # File lib/optparse.rb, line 1427
1427:   def search(id, key)
1428:     block_given = block_given?
1429:     visit(:search, id, key) do |k|
1430:       return block_given ? yield(k) : k
1431:     end
1432:   end

Traverses @stack, sending each element method id with args and block.

[Source]

      # File lib/optparse.rb, line 1415
1415:   def visit(id, *args, &block)
1416:     el = nil
1417:     @stack.reverse_each do |el|
1418:       el.send(id, *args, &block)
1419:     end
1420:     nil
1421:   end

[Validate]