commit 12940cd52172cf70c49a2e924f47c7f5d13e7243 Author: Denis Knauf Date: Wed Feb 6 11:53:08 2013 +0100 truckle in cave diff --git a/truckle b/truckle new file mode 100755 index 0000000..2bf7952 --- /dev/null +++ b/truckle @@ -0,0 +1,234 @@ +#!/usr/bin/env ruby +# -*- encoding : utf-8 -*- + +require 'irb-pager' +require 'shellwords' + +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, :default_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 on *names, &run + if names.empty? + @default_cmd = run + else + names.each {|name| self[name.to_s.to_sym] = 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] || @default_cmd).call c, *argv + rescue CommandError + STDERR.puts $!.message + exit 1 + end + alias call run + + def to_proc + method(:call).to_proc + end +end + +class RunCave + class CommandExpected