optparse.rb

Path: lib/optparse.rb
Last Update: Sat Sep 22 12:31:32 +0000 2007

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

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

See OptionParser for documentation.

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

See getopts.

[Source]

      # File lib/optparse.rb, line 1400
1400:   def self.getopts(*args)
1401:     new.getopts(*args)
1402:   end

Returns an incremented value of default according to arg.

[Source]

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

See reject.

[Source]

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

[Source]

     # File lib/optparse.rb, line 802
802:   def self.terminate(arg = nil)
803:     throw :terminate, arg
804:   end

[Source]

     # File lib/optparse.rb, line 807
807:   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 749
749:   def self.with(*args, &block)
750:     opts = new(*args)
751:     opts.instance_eval(&block)
752:     opts
753:   end

Public Instance methods

[Source]

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

Heading banner preceding summary.

[Source]

     # File lib/optparse.rb, line 860
860:   def banner
861:     unless @banner
862:       @banner = "Usage: #{program_name} [options]"
863:       visit(:add_banner, @banner)
864:     end
865:     @banner
866:   end

Subject of on_tail.

[Source]

     # File lib/optparse.rb, line 930
930:   def base
931:     @stack[1]
932:   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 1176
1176:   def define(*opts, &block)
1177:     top.append(*(sw = make_switch(opts, block)))
1178:     sw[0]
1179:   end

[Source]

      # File lib/optparse.rb, line 1191
1191:   def define_head(*opts, &block)
1192:     top.prepend(*(sw = make_switch(opts, block)))
1193:     sw[0]
1194:   end

[Source]

      # File lib/optparse.rb, line 1205
1205:   def define_tail(*opts, &block)
1206:     base.append(*(sw = make_switch(opts, block)))
1207:     sw[0]
1208:   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 1475
1475:   def environment(env = File.basename($0, '.*'))
1476:     env = ENV[env] || ENV[env.upcase] or return
1477:     parse(*Shellwords.shellwords(env))
1478:   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 1366
1366:   def getopts(*args)
1367:     argv = Array === args.first ? args.shift : default_argv
1368:     single_options, *long_options = *args
1369: 
1370:     result = {}
1371: 
1372:     single_options.scan(/(.)(:)?/) do |opt, val|
1373:       if val
1374:         result[opt] = nil
1375:         define("-#{opt} VAL")
1376:       else
1377:         result[opt] = false
1378:         define("-#{opt}")
1379:       end
1380:     end if single_options
1381: 
1382:     long_options.each do |arg|
1383:       opt, val = arg.split(':', 2)
1384:       if val
1385:         result[opt] = val.empty? ? nil : val
1386:         define("--#{opt} VAL")
1387:       else
1388:         result[opt] = false
1389:         define("--#{opt}")
1390:       end
1391:     end
1392: 
1393:     parse_in_order(argv, result.method(:[]=))
1394:     result
1395:   end

Returns option summary string.

[Source]

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

[Source]

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

Pushes a new List.

[Source]

     # File lib/optparse.rb, line 937
937:   def new
938:     @stack.push(List.new)
939:     if block_given?
940:       yield self
941:     else
942:       self
943:     end
944:   end

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

[Source]

      # File lib/optparse.rb, line 1185
1185:   def on(*opts, &block)
1186:     define(*opts, &block)
1187:     self
1188:   end

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

[Source]

      # File lib/optparse.rb, line 1199
1199:   def on_head(*opts, &block)
1200:     define_head(*opts, &block)
1201:     self
1202:   end

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

[Source]

      # File lib/optparse.rb, line 1213
1213:   def on_tail(*opts, &block)
1214:     define_tail(*opts, &block)
1215:     self
1216:   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 1232
1232:   def order(*argv, &block)
1233:     argv = argv[0].dup if argv.size == 1 and Array === argv[0]
1234:     order!(argv, &block)
1235:   end

Same as order, but removes switches destructively.

[Source]

      # File lib/optparse.rb, line 1240
1240:   def order!(argv = default_argv, &nonopt)
1241:     parse_in_order(argv, &nonopt)
1242:   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 1341
1341:   def parse(*argv)
1342:     argv = argv[0].dup if argv.size == 1 and Array === argv[0]
1343:     parse!(argv)
1344:   end

Same as parse, but removes switches destructively.

[Source]

      # File lib/optparse.rb, line 1349
1349:   def parse!(argv = default_argv)
1350:     if ENV.include?('POSIXLY_CORRECT')
1351:       order!(argv)
1352:     else
1353:       permute!(argv)
1354:     end
1355:   end

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

[Source]

      # File lib/optparse.rb, line 1321
1321:   def permute(*argv)
1322:     argv = argv[0].dup if argv.size == 1 and Array === argv[0]
1323:     permute!(argv)
1324:   end

Same as permute, but removes switches destructively.

[Source]

      # File lib/optparse.rb, line 1329
1329:   def permute!(argv = default_argv)
1330:     nonopts = []
1331:     arg = nil
1332:     order!(argv) {|arg| nonopts << arg}
1333:     argv[0, 0] = nonopts
1334:     argv
1335:   end

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

[Source]

     # File lib/optparse.rb, line 872
872:   def program_name
873:     @program_name || File.basename($0, '.*')
874:   end

Directs to reject specified class argument.

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

[Source]

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

Release code

[Source]

     # File lib/optparse.rb, line 897
897:   def release
898:     @release || (defined?(::Release) && ::Release) || (defined?(::RELEASE) && ::RELEASE)
899:   end

Removes the last List.

[Source]

     # File lib/optparse.rb, line 949
949:   def remove
950:     @stack.pop
951:   end

Add separator in summary.

[Source]

      # File lib/optparse.rb, line 1222
1222:   def separator(string)
1223:     top.append(string, nil, nil)
1224:   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 962
962:   def summarize(to = [], width = @summary_width, max = width - 1, indent = @summary_indent, &blk)
963:     visit(:summarize, {}, {}, width, max, indent, &(blk || proc {|l| to << l + $/}))
964:     to
965:   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 799
799:   def terminate(arg = nil)
800:     self.class.terminate(arg)
801:   end

Returns option summary list.

[Source]

     # File lib/optparse.rb, line 976
976:   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 923
923:   def top
924:     @stack[-1]
925:   end

Returns version string from program_name, version and release.

[Source]

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

Version

[Source]

     # File lib/optparse.rb, line 890
890:   def version
891:     @version || (defined?(::Version) && ::Version)
892:   end

[Source]

     # File lib/optparse.rb, line 912
912:   def warn(mesg = $!)
913:     super("#{program_name}: #{mesg}")
914:   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 1437
1437:   def complete(typ, opt, icase = false, *pat)
1438:     if pat.empty?
1439:       search(typ, opt) {|sw| return [sw, opt]} # exact match or...
1440:     end
1441:     raise AmbiguousOption, catch(:ambiguous) {
1442:       visit(:complete, typ, opt, icase, *pat) {|opt, *sw| return sw}
1443:       raise InvalidOption, opt
1444:     }
1445:   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 986
986:   def notwice(obj, prv, msg)
987:     unless !prv or prv == obj
988:       begin
989:         raise ArgumentError, "argument #{msg} given twice: #{obj}"
990:       rescue
991:         $@[0, 2] = nil
992:         raise
993:       end
994:     end
995:     obj
996:   end

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

[Source]

      # File lib/optparse.rb, line 1420
1420:   def search(id, key)
1421:     block_given = block_given?
1422:     visit(:search, id, key) do |k|
1423:       return block_given ? yield(k) : k
1424:     end
1425:   end

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

[Source]

      # File lib/optparse.rb, line 1408
1408:   def visit(id, *args, &block)
1409:     el = nil
1410:     @stack.reverse_each do |el|
1411:       el.send(id, *args, &block)
1412:     end
1413:     nil
1414:   end

[Validate]