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.
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 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. |
# 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
# File lib/optparse.rb, line 804 804: def self.terminate(arg = nil) 805: throw :terminate, arg 806: 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 751 751: def self.with(*args, &block) 752: opts = new(*args) 753: opts.instance_eval(&block) 754: opts 755: end
# 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)
# File lib/optparse.rb, line 820 820: def accept(*args, &blk) top.accept(*args, &blk) end
# File lib/optparse.rb, line 1178 1178: def define(*opts, &block) 1179: top.append(*(sw = make_switch(opts, block))) 1180: sw[0] 1181: end
# 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
# 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.
# 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
# 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.
# File lib/optparse.rb, line 972 972: 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 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:
: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 regular expression):
"-[a-z]MANDATORY" "-[a-z][OPTIONAL]" "-[a-z]"
"=MANDATORY" "=[OPTIONAL]"
"Run verbosely"
# 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
Add option switch and handler. See make_switch for an explanation of parameters.
# File lib/optparse.rb, line 1187 1187: def on(*opts, &block) 1188: define(*opts, &block) 1189: self 1190: 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 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
Parses command line arguments argv in order when environment variable POSIXLY_CORRECT is set, and in permutation mode otherwise.
# 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
Parses command line arguments argv in permutation mode and returns list of non-option arguments.
# 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
Release code
# File lib/optparse.rb, line 899 899: def release 900: @release || (defined?(::Release) && ::Release) || (defined?(::RELEASE) && ::RELEASE) 901: 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 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.
# File lib/optparse.rb, line 801 801: def terminate(arg = nil) 802: self.class.terminate(arg) 803: end
Returns option summary list.
# File lib/optparse.rb, line 978 978: def to_a; summarize(banner.to_a.dup) end
Returns version string from program_name, version and release.
# 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
# File lib/optparse.rb, line 892 892: def version 893: @version || (defined?(::Version) && ::Version) 894: end
# File lib/optparse.rb, line 914 914: def warn(mesg = $!) 915: super("#{program_name}: #{mesg}") 916: 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 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. |
# 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.
# 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