| 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.
| 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 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. |
# 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
# File lib/optparse.rb, line 806
806: def self.terminate(arg = nil)
807: throw :terminate, arg
808: 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 753
753: def self.with(*args, &block)
754: opts = new(*args)
755: opts.instance_eval(&block)
756: opts
757: end
# 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)
# File lib/optparse.rb, line 822
822: def accept(*args, &blk) top.accept(*args, &blk) end
# File lib/optparse.rb, line 1181
1181: def define(*opts, &block)
1182: top.append(*(sw = make_switch(opts, block)))
1183: sw[0]
1184: end
# 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
# 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.
# 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
# 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.
# File lib/optparse.rb, line 975
975: 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 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:
: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 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
Add option switch and handler. See make_switch for an explanation of parameters.
# File lib/optparse.rb, line 1190
1190: def on(*opts, &block)
1191: define(*opts, &block)
1192: self
1193: 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 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
Parses command line arguments argv in order when environment variable POSIXLY_CORRECT is set, and in permutation mode otherwise.
# 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
Parses command line arguments argv in permutation mode and returns list of non-option arguments.
# 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
Release code
# File lib/optparse.rb, line 901
901: def release
902: @release || (defined?(::Release) && ::Release) || (defined?(::RELEASE) && ::RELEASE)
903: 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 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.
# File lib/optparse.rb, line 803
803: def terminate(arg = nil)
804: self.class.terminate(arg)
805: end
Returns option summary list.
# File lib/optparse.rb, line 981
981: def to_a; summarize(banner.to_a.dup) end
Returns version string from program_name, version and release.
# 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
# File lib/optparse.rb, line 894
894: def version
895: @version || (defined?(::Version) && ::Version)
896: end
# File lib/optparse.rb, line 916
916: def warn(mesg = $!)
917: super("#{program_name}: #{mesg}")
918: 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 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. |
# 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.
# 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