Path: | lib/optparse.rb |
Last Update: | Fri Dec 30 14:55:12 +0000 2011 |
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 764 764: def self.inc(arg, default = nil) 765: case arg 766: when Integer 767: arg.nonzero? 768: when nil 769: default.to_i + 1 770: end 771: 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 783 783: def initialize(banner = nil, width = 32, indent = ' ' * 4) 784: @stack = [DefaultList, List.new, List.new] 785: @program_name = nil 786: @banner = banner 787: @summary_width = width 788: @summary_indent = indent 789: @default_argv = ARGV 790: add_officious 791: yield self if block_given? 792: end
# File lib/optparse.rb, line 808 808: def self.terminate(arg = nil) 809: throw :terminate, arg 810: 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 755 755: def self.with(*args, &block) 756: opts = new(*args) 757: opts.instance_eval(&block) 758: opts 759: end
# File lib/optparse.rb, line 922 922: def abort(mesg = $!) 923: super("#{program_name}: #{mesg}") 924: 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 824 824: def accept(*args, &blk) top.accept(*args, &blk) end
# File lib/optparse.rb, line 1183 1183: def define(*opts, &block) 1184: top.append(*(sw = make_switch(opts, block))) 1185: sw[0] 1186: end
# File lib/optparse.rb, line 1198 1198: def define_head(*opts, &block) 1199: top.prepend(*(sw = make_switch(opts, block))) 1200: sw[0] 1201: end
# File lib/optparse.rb, line 1212 1212: def define_tail(*opts, &block) 1213: base.append(*(sw = make_switch(opts, block))) 1214: sw[0] 1215: 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 1482 1482: def environment(env = File.basename($0, '.*')) 1483: env = ENV[env] || ENV[env.upcase] or return 1484: require 'shellwords' 1485: parse(*Shellwords.shellwords(env)) 1486: 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 1373 1373: def getopts(*args) 1374: argv = Array === args.first ? args.shift : default_argv 1375: single_options, *long_options = *args 1376: 1377: result = {} 1378: 1379: single_options.scan(/(.)(:)?/) do |opt, val| 1380: if val 1381: result[opt] = nil 1382: define("-#{opt} VAL") 1383: else 1384: result[opt] = false 1385: define("-#{opt}") 1386: end 1387: end if single_options 1388: 1389: long_options.each do |arg| 1390: opt, val = arg.split(':', 2) 1391: if val 1392: result[opt] = val.empty? ? nil : val 1393: define("--#{opt} VAL") 1394: else 1395: result[opt] = false 1396: define("--#{opt}") 1397: end 1398: end 1399: 1400: parse_in_order(argv, result.method(:[]=)) 1401: result 1402: end
Returns option summary string.
# File lib/optparse.rb, line 977 977: 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 1462 1462: def load(filename = nil) 1463: begin 1464: filename ||= File.expand_path(File.basename($0, '.*'), '~/.options') 1465: rescue 1466: return false 1467: end 1468: begin 1469: parse(*IO.readlines(filename).each {|s| s.chomp!}) 1470: true 1471: rescue Errno::ENOENT, Errno::ENOTDIR 1472: false 1473: end 1474: 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 1064 1064: def make_switch(opts, block = nil) 1065: short, long, nolong, style, pattern, conv, not_pattern, not_conv, not_style = [], [], [] 1066: ldesc, sdesc, desc, arg = [], [], [] 1067: default_style = Switch::NoArgument 1068: default_pattern = nil 1069: klass = nil 1070: o = nil 1071: n, q, a = nil 1072: 1073: opts.each do |o| 1074: # argument class 1075: next if search(:atype, o) do |pat, c| 1076: klass = notwice(o, klass, 'type') 1077: if not_style and not_style != Switch::NoArgument 1078: not_pattern, not_conv = pat, c 1079: else 1080: default_pattern, conv = pat, c 1081: end 1082: end 1083: 1084: # directly specified pattern(any object possible to match) 1085: if !(String === o) and o.respond_to?(:match) 1086: pattern = notwice(o, pattern, 'pattern') 1087: conv = pattern.method(:convert).to_proc if pattern.respond_to?(:convert) 1088: next 1089: end 1090: 1091: # anything others 1092: case o 1093: when Proc, Method 1094: block = notwice(o, block, 'block') 1095: when Array, Hash 1096: case pattern 1097: when CompletingHash 1098: when nil 1099: pattern = CompletingHash.new 1100: conv = pattern.method(:convert).to_proc if pattern.respond_to?(:convert) 1101: else 1102: raise ArgumentError, "argument pattern given twice" 1103: end 1104: o.each {|(o, *v)| pattern[o] = v.fetch(0) {o}} 1105: when Module 1106: raise ArgumentError, "unsupported argument type: #{o}" 1107: when *ArgumentStyle.keys 1108: style = notwice(ArgumentStyle[o], style, 'style') 1109: when /^--no-([^\[\]=\s]*)(.+)?/ 1110: q, a = $1, $2 1111: o = notwice(a ? Object : TrueClass, klass, 'type') 1112: not_pattern, not_conv = search(:atype, o) unless not_style 1113: not_style = (not_style || default_style).guess(arg = a) if a 1114: default_style = Switch::NoArgument 1115: default_pattern, conv = search(:atype, FalseClass) unless default_pattern 1116: ldesc << "--no-#{q}" 1117: long << 'no-' + (q = q.downcase) 1118: nolong << q 1119: when /^--\[no-\]([^\[\]=\s]*)(.+)?/ 1120: q, a = $1, $2 1121: o = notwice(a ? Object : TrueClass, klass, 'type') 1122: if a 1123: default_style = default_style.guess(arg = a) 1124: default_pattern, conv = search(:atype, o) unless default_pattern 1125: end 1126: ldesc << "--[no-]#{q}" 1127: long << (o = q.downcase) 1128: not_pattern, not_conv = search(:atype, FalseClass) unless not_style 1129: not_style = Switch::NoArgument 1130: nolong << 'no-' + o 1131: when /^--([^\[\]=\s]*)(.+)?/ 1132: q, a = $1, $2 1133: if a 1134: o = notwice(NilClass, klass, 'type') 1135: default_style = default_style.guess(arg = a) 1136: default_pattern, conv = search(:atype, o) unless default_pattern 1137: end 1138: ldesc << "--#{q}" 1139: long << (o = q.downcase) 1140: when /^-(\[\^?\]?(?:[^\\\]]|\\.)*\])(.+)?/ 1141: q, a = $1, $2 1142: o = notwice(Object, klass, 'type') 1143: if a 1144: default_style = default_style.guess(arg = a) 1145: default_pattern, conv = search(:atype, o) unless default_pattern 1146: end 1147: sdesc << "-#{q}" 1148: short << Regexp.new(q) 1149: when /^-(.)(.+)?/ 1150: q, a = $1, $2 1151: if a 1152: o = notwice(NilClass, klass, 'type') 1153: default_style = default_style.guess(arg = a) 1154: default_pattern, conv = search(:atype, o) unless default_pattern 1155: end 1156: sdesc << "-#{q}" 1157: short << q 1158: when /^=/ 1159: style = notwice(default_style.guess(arg = o), style, 'style') 1160: default_pattern, conv = search(:atype, Object) unless default_pattern 1161: else 1162: desc.push(o) 1163: end 1164: end 1165: 1166: default_pattern, conv = search(:atype, default_style.pattern) unless default_pattern 1167: if !(short.empty? and long.empty?) 1168: s = (style || default_style).new(pattern || default_pattern, 1169: conv, sdesc, ldesc, arg, desc, block) 1170: elsif !block 1171: raise ArgumentError, "no switch given" if style or pattern 1172: s = desc 1173: else 1174: short << pattern 1175: s = (style || default_style).new(pattern, 1176: conv, nil, nil, arg, desc, block) 1177: end 1178: return s, short, long, 1179: (not_style.new(not_pattern, not_conv, sdesc, ldesc, nil, desc, block) if not_style), 1180: nolong 1181: end
Add option switch and handler. See make_switch for an explanation of parameters.
# File lib/optparse.rb, line 1192 1192: def on(*opts, &block) 1193: define(*opts, &block) 1194: self 1195: 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 1239 1239: def order(*argv, &block) 1240: argv = argv[0].dup if argv.size == 1 and Array === argv[0] 1241: order!(argv, &block) 1242: 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 1348 1348: def parse(*argv) 1349: argv = argv[0].dup if argv.size == 1 and Array === argv[0] 1350: parse!(argv) 1351: end
Parses command line arguments argv in permutation mode and returns list of non-option arguments.
# File lib/optparse.rb, line 1328 1328: def permute(*argv) 1329: argv = argv[0].dup if argv.size == 1 and Array === argv[0] 1330: permute!(argv) 1331: end
Release code
# File lib/optparse.rb, line 903 903: def release 904: @release || (defined?(::Release) && ::Release) || (defined?(::RELEASE) && ::RELEASE) 905: 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 968 968: def summarize(to = [], width = @summary_width, max = width - 1, indent = @summary_indent, &blk) 969: blk ||= proc {|l| to << (l.index($/, -1) ? l : l + $/)} 970: visit(:summarize, {}, {}, width, max, indent, &blk) 971: to 972: end
Terminates option parsing. Optional parameter arg is a string pushed back to be the first non-option argument.
# File lib/optparse.rb, line 805 805: def terminate(arg = nil) 806: self.class.terminate(arg) 807: end
Returns option summary list.
# File lib/optparse.rb, line 983 983: def to_a; summarize(banner.to_a.dup) end
Returns version string from program_name, version and release.
# File lib/optparse.rb, line 910 910: def ver 911: if v = version 912: str = "#{program_name} #{[v].join('.')}" 913: str << " (#{v})" if v = release 914: str 915: end 916: end
Version
# File lib/optparse.rb, line 896 896: def version 897: @version || (defined?(::Version) && ::Version) 898: end
# File lib/optparse.rb, line 918 918: def warn(mesg = $!) 919: super("#{program_name}: #{mesg}") 920: 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 1444 1444: def complete(typ, opt, icase = false, *pat) 1445: if pat.empty? 1446: search(typ, opt) {|sw| return [sw, opt]} # exact match or... 1447: end 1448: raise AmbiguousOption, catch(:ambiguous) { 1449: visit(:complete, typ, opt, icase, *pat) {|opt, *sw| return sw} 1450: raise InvalidOption, opt 1451: } 1452: 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 993 993: def notwice(obj, prv, msg) 994: unless !prv or prv == obj 995: begin 996: raise ArgumentError, "argument #{msg} given twice: #{obj}" 997: rescue 998: $@[0, 2] = nil 999: raise 1000: end 1001: end 1002: obj 1003: end
Searches key in @stack for id hash and returns or yields the result.
# File lib/optparse.rb, line 1427 1427: def search(id, key) 1428: block_given = block_given? 1429: visit(:search, id, key) do |k| 1430: return block_given ? yield(k) : k 1431: end 1432: end