| 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.
| 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. |
| banner= | -> | set_banner |
| for experimental cascading :-) | ||
| program_name= | -> | set_program_name |
| summary_width= | -> | set_summary_width |
| summary_indent= | -> | set_summary_indent |
Returns an incremented value of default according to arg.
# 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. |
# 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
# File lib/optparse.rb, line 802
802: def self.terminate(arg = nil)
803: throw :terminate, arg
804: 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.
# 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
# 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)
# File lib/optparse.rb, line 818
818: def accept(*args, &blk) top.accept(*args, &blk) end
# File lib/optparse.rb, line 1176
1176: def define(*opts, &block)
1177: top.append(*(sw = make_switch(opts, block)))
1178: sw[0]
1179: end
# 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
# 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.
# 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
# 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.
# File lib/optparse.rb, line 970
970: def help; summarize(banner.to_s.sub(/\n?\z/, "\n")) 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.
# 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:
:NONE, :REQUIRED, :OPTIONAL
Float, Time, Array
[:text, :binary, :auto]
%w[iso-2022-jp shift_jis euc-jp utf8 binary]
{ "jis" => "iso-2022-jp", "sjis" => "shift_jis" }
"--switch=MANDATORY" or "--switch MANDATORY" "--switch[=OPTIONAL]" "--switch"
"-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]"
"=MANDATORY" "=[OPTIONAL]"
"Run verbosely"
# 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
Add option switch and handler. See make_switch for an explanation of parameters.
# File lib/optparse.rb, line 1185
1185: def on(*opts, &block)
1186: define(*opts, &block)
1187: self
1188: 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.
# 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
Parses command line arguments argv in order when environment variable POSIXLY_CORRECT is set, and in permutation mode otherwise.
# 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
Parses command line arguments argv in permutation mode and returns list of non-option arguments.
# 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
Release code
# File lib/optparse.rb, line 897
897: def release
898: @release || (defined?(::Release) && ::Release) || (defined?(::RELEASE) && ::RELEASE)
899: 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. |
# 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.
# File lib/optparse.rb, line 799
799: def terminate(arg = nil)
800: self.class.terminate(arg)
801: end
Returns option summary list.
# File lib/optparse.rb, line 976
976: def to_a; summarize(banner.to_a.dup) end
Returns version string from program_name, version and release.
# 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
# File lib/optparse.rb, line 890
890: def version
891: @version || (defined?(::Version) && ::Version)
892: end
# File lib/optparse.rb, line 912
912: def warn(mesg = $!)
913: super("#{program_name}: #{mesg}")
914: end
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. |
# 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. |
# 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.
# 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