#!/usr/bin/env ruby # -*- encoding : utf-8 -*- require 'irb-pager' require 'shellwords' require 'getoptlong' class GetoptLong def argv=( v) @argv = v end def argv() @argv end def ARGV=( v) @argv = v end def ARGV() @argv end end class Commands < Hash class CommandError < Exception end class ExpectingCommandError < CommandError def initialize *args args = ['Command expected'] if args.empty? super *args end end class UnknownCommandError < CommandError def initialize *args args = ['This Command i do not know'] if args.empty? super *args end end attr_accessor :exe, :prefix, :fallback_cmd def self.arg_unshift arg, args arg = arg.is_a?(Array) ? arg : [arg] i = 1+args.index {|x|/^[^-]/=~x} args[0...i] + arg + args[i..-1] end def self.new prefix, exe r = super() r.exe = exe r.prefix = prefix r.on {|cmd, *argv| raise UnknownCommandError, 'Unknown Command: %s' % cmd } r end def sym_name name name.to_s.to_sym end def on *names, &run options = names.last.is_a?(Hash) ? names.pop.dup : {} if names.empty? @fallback_cmd = run else names.each {|name| self[sym_name name] = run } end end def cmd argv if @prefix == @exe raise ExpectingCommandError if argv.empty? [argv[0].to_sym, *argv[1..-1]] else @exe =~ /^(?:#{Regexp.escape @prefix}-)?(.*)$/ [$1.to_sym, *argv] end end def each all=nil, &block if not block_given? Enumerator.new self, :each, all elsif all super(&block) else super() {|k,v| yield k,v unless /^-/ =~ k.to_s } end end def run *argv c, *argv = self.cmd( argv) (self[c] || @fallback_cmd).call c, *argv rescue CommandError STDERR.puts $!.message, $!.backtrace exit 1 end alias call run def to_proc method(:call).to_proc end end # RunCave # ======= # # Prepare cave-commands. class RunCave class CommandExpected