optparse.rb

Path: lib/optparse.rb
Last Update: Fri Jul 03 13:24:47 +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 824
824:   def self.accept(*args, &blk) top.accept(*args, &blk) end

See getopts.

[Source]

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

Returns an incremented value of default according to arg.

[Source]

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

See reject.

[Source]

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

[Source]

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

[Source]

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

Public Instance methods

[Source]

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

Heading banner preceding summary.

[Source]

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

Subject of on_tail.

[Source]

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

[Source]

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

[Source]

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

Returns option summary string.

[Source]

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

[Source]

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

Pushes a new List.

[Source]

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

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

[Source]

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

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

[Source]

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

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

[Source]

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

Same as order, but removes switches destructively.

[Source]

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

Same as parse, but removes switches destructively.

[Source]

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

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

[Source]

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

Same as permute, but removes switches destructively.

[Source]

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

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

[Source]

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

Directs to reject specified class argument.

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

[Source]

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

Release code

[Source]

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

Removes the last List.

[Source]

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

Add separator in summary.

[Source]

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

Returns option summary list.

[Source]

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

Returns version string from program_name, version and release.

[Source]

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

Version

[Source]

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

[Source]

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

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

[Source]

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

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

[Source]

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

[Validate]