require 'optparse'
require 'optparse/time'
require 'pp'
CODES = %w[iso-2022-jp shift_jis euc-jp utf8 binary]
CODE_ALIASES = {"jis" => "iso-2022-jp", "sjis" => "shift_jis"}
POSSIBLE_CODES = "(#{(CODES+CODE_ALIASES.keys).join(',')})"
ARGV.options do
|opts|
opts.banner << " argv..."
opts.on_tail
opts.on_tail("common options:")
opts.on_tail("--help", "show this message") {puts opts; exit}
opts.on("-r", "--require=LIBRARY", String,
"require the LIBRARY, before",
"executing your script") {|@library|}
opts.on("-i", "--inplace=[EXTENSION]",
"edit ARGV files in place", "(make backup if EXTENSION supplied)") {|@inplace| @inplace ||= ''}
opts.on("-N=[NUM]", Integer) {|@number|}
opts.on("-t", "--[no-]time[=TIME]", Time, "it's the time") {|@time|}
opts.on("-[0-7]", "-F", "--irs=[OCTAL]", OptionParser::OctalInteger,
"specify record separator", "(\\0, if no argument)") {|@irs|}
@exec = true
opts.on("-n", "--no-exec[=FLAG]", TrueClass, "not really execute") {|@exec|}
opts.on("-a", "--list[=LIST,LIST]", Array, "list") {|@list|}
opts.on("--pair[=car,cdr]", Array, "pair") {|@x, @y|}
opts.on("--code=CODE", CODES, CODE_ALIASES, "select coding system",
"("+CODES.join(",")+",", " "+CODE_ALIASES.keys.join(",")+")") {|@code|}
opts.on("--type[=TYPE]", [:text, :binary], "select type(text, binary)") {|@type|}
opts.on("-v", "--[no-]verbose=[FLAG]", "run verbosely") {|@verbose|}
opts.on("-q", "--quit", "quit when ARGV is empty") {|@quit|}
opts.on("--add=SWITCH=[ARG]", "add option on the fly", /\A(\w+)(?:=.+)?\Z/) do
|opt, var|
opts.on("--#{opt}", "added in runtime", &eval("proc {|@#{var}|}"))
end
opts.on_head("specific options:")
opts.on_tail("--version", "show version") do
puts OptionParser::Version.join('.')
exit
end
opts.parse!
end
pp self
(print ARGV.options; exit) if @quit
ARGV.options = nil puts "ARGV = #{ARGV.join(' ')}" if !ARGV.empty?