optparse.rb

Path: lib/optparse.rb
Last Update: Fri Jul 03 17:13:02 +0000 2009

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 826
826:   def self.accept(*args, &blk) top.accept(*args, &blk) end

See getopts.

[Source]

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

Returns an incremented value of default according to arg.

[Source]

     # File lib/optparse.rb, line 762
762:   def self.inc(arg, default = nil)
763:     case arg
764:     when Integer
765:       arg.nonzero?
766:     when nil
767:       default.to_i + 1
768:     end
769:   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 781
781:   def initialize(banner = nil, width = 32, indent = ' ' * 4)
782:     @stack = [DefaultList, List.new, List.new]
783:     @program_name = nil
784:     @banner = banner
785:     @summary_width = width
786:     @summary_indent = indent
787:     @default_argv = ARGV
788:     add_officious
789:     yield self if block_given?
790:   end

See reject.

[Source]

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

[Source]

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

[Source]

     # File lib/optparse.rb, line 811
811:   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 753
753:   def self.with(*args, &block)
754:     opts = new(*args)
755:     opts.instance_eval(&block)
756:     opts
757:   end

Public Instance methods

[Source]

     # File lib/optparse.rb, line 920
920:   def abort(mesg = $!)
921:     super("#{program_name}: #{mesg}")
922:   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 822
822:   def accept(*args, &blk) top.accept(*args, &blk) end

Heading banner preceding summary.

[Source]

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

Subject of on_tail.

[Source]

     # File lib/optparse.rb, line 934
934:   def base
935:     @stack[1]
936:   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 1181
1181:   def define(*opts, &block)
1182:     top.append(*(sw = make_switch(opts, block)))
1183:     sw[0]
1184:   end

[Source]

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

[Source]

      # File lib/optparse.rb, line 1210
1210:   def define_tail(*opts, &block)
1211:     base.append(*(sw = make_switch(opts, block)))
1212:     sw[0]
1213:   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 1480
1480:   def environment(env = File.basename($0, '.*'))
1481:     env = ENV[env] || ENV[env.upcase] or return
1482:     require 'shellwords'
1483:     parse(*Shellwords.shellwords(env))
1484:   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 1371
1371:   def getopts(*args)
1372:     argv = Array === args.first ? args.shift : default_argv
1373:     single_options, *long_options = *args
1374: 
1375:     result = {}
1376: 
1377:     single_options.scan(/(.)(:)?/) do |opt, val|
1378:       if val
1379:         result[opt] = nil
1380:         define("-#{opt} VAL")
1381:       else
1382:         result[opt] = false
1383:         define("-#{opt}")
1384:       end
1385:     end if single_options
1386: 
1387:     long_options.each do |arg|
1388:       opt, val = arg.split(':', 2)
1389:       if val
1390:         result[opt] = val.empty? ? nil : val
1391:         define("--#{opt} VAL")
1392:       else
1393:         result[opt] = false
1394:         define("--#{opt}")
1395:       end
1396:     end
1397: 
1398:     parse_in_order(argv, result.method(:[]=))
1399:     result
1400:   end

Returns option summary string.

[Source]

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

[Source]

     # File lib/optparse.rb, line 770
770:   def inc(*args)
771:     self.class.inc(*args)
772:   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 1460
1460:   def load(filename = nil)
1461:     begin
1462:       filename ||= File.expand_path(File.basename($0, '.*'), '~/.options')
1463:     rescue
1464:       return false
1465:     end
1466:     begin
1467:       parse(*IO.readlines(filename).each {|s| s.chomp!})
1468:       true
1469:     rescue Errno::ENOENT, Errno::ENOTDIR
1470:       false
1471:     end
1472:   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 regural expression):

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

Pushes a new List.

[Source]

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

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

[Source]

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

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

[Source]

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

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

[Source]

      # File lib/optparse.rb, line 1218
1218:   def on_tail(*opts, &block)
1219:     define_tail(*opts, &block)
1220:     self
1221:   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 1237
1237:   def order(*argv, &block)
1238:     argv = argv[0].dup if argv.size == 1 and Array === argv[0]
1239:     order!(argv, &block)
1240:   end

Same as order, but removes switches destructively.

[Source]

      # File lib/optparse.rb, line 1245
1245:   def order!(argv = default_argv, &nonopt)
1246:     parse_in_order(argv, &nonopt)
1247:   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 1346
1346:   def parse(*argv)
1347:     argv = argv[0].dup if argv.size == 1 and Array === argv[0]
1348:     parse!(argv)
1349:   end

Same as parse, but removes switches destructively.

[Source]

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

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

[Source]

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

Same as permute, but removes switches destructively.

[Source]

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

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

[Source]

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

Directs to reject specified class argument.

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

[Source]

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

Release code

[Source]

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

Removes the last List.

[Source]

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

Add separator in summary.

[Source]

      # File lib/optparse.rb, line 1227
1227:   def separator(string)
1228:     top.append(string, nil, nil)
1229:   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 966
966:   def summarize(to = [], width = @summary_width, max = width - 1, indent = @summary_indent, &blk)
967:     blk ||= proc {|l| to << (l.index($/, -1) ? l : l + $/)}
968:     visit(:summarize, {}, {}, width, max, indent, &blk)
969:     to
970:   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 803
803:   def terminate(arg = nil)
804:     self.class.terminate(arg)
805:   end

Returns option summary list.

[Source]

     # File lib/optparse.rb, line 981
981:   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 927
927:   def top
928:     @stack[-1]
929:   end

Returns version string from program_name, version and release.

[Source]

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

Version

[Source]

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

[Source]

     # File lib/optparse.rb, line 916
916:   def warn(mesg = $!)
917:     super("#{program_name}: #{mesg}")
918:   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 1442
1442:   def complete(typ, opt, icase = false, *pat)
1443:     if pat.empty?
1444:       search(typ, opt) {|sw| return [sw, opt]} # exact match or...
1445:     end
1446:     raise AmbiguousOption, catch(:ambiguous) {
1447:       visit(:complete, typ, opt, icase, *pat) {|opt, *sw| return sw}
1448:       raise InvalidOption, opt
1449:     }
1450:   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 991
 991:   def notwice(obj, prv, msg)
 992:     unless !prv or prv == obj
 993:       begin
 994:         raise ArgumentError, "argument #{msg} given twice: #{obj}"
 995:       rescue
 996:         $@[0, 2] = nil
 997:         raise
 998:       end
 999:     end
1000:     obj
1001:   end

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

[Source]

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

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

[Source]

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

[Validate]