require 'open3' require_relative('./array.rb') require_relative('./hash.rb') require_relative('./timer.rb') class Command < Hash def initialize command if(command.kind_of?(String)) self[:input] = command self[:timeout] = 0 self[:directory] = '' self[:exit_code] = 0 self[:output] = '' self[:error] = '' self[:machine] = '' self[:user] = '' self[:start_time] = nil self[:end_time] = nil end if(command.kind_of?(Hash)) command.each{|k,v| self[k.to_sym]=v } end end def execute puts "#{self[:input]}" pwd=Dir.pwd Dir.chdir(self[:directory]) if(self.has_key?(:directory) && File.exists?(self[:directory])) self[:directory] = pwd if(self[:directory].length==0) self[:machine] = Command.machine self[:user] = Command.user self[:start_time]=Time.now timer=Timer.new if self[:input].include?('<%') && self[:input].include?('%>') ruby = self[:input].gsub("<%","").gsub("%>","") begin #puts "eval(#{ruby})" self[:output]=eval(ruby) rescue #puts "unable to eval(#{ruby})" #raise "unable to eval(#{ruby})" self[:error]="unable to eval(#{ruby})" end self[:elapsed] = timer.elapsed_str self[:end_time] = Time.now else begin self[:output],self[:error],self[:exit_code]= Open3.capture3(self[:input]) #self[:output] = `#{self[:input]}` self[:elapsed] = timer.elapsed_str self[:end_time] = Time.now #self[:exit_code]=$?.to_i rescue Exception => e self[:elapsed] = timer.elapsed_str self[:end_time] = Time.now self[:error] = "Exception: " + e.to_s self[:exit_code]=1 end end Dir.chdir(pwd) if pwd != Dir.pwd end def self.machine if !ENV['COMPUTERNAME'].nil? return ENV['COMPUTERNAME'] end machine = `hostname` machine = machine.split('.')[0] if machine.include?('.') return machine.strip end def self.user ENV['USER'].nil? ? ENV['USERNAME'] : ENV['USER'] end def to_html if self[:exit_code] == 0 [ '
',
      	self[:input],
      	'
' ].join else [ '
',
      	self[:input],
        '
', map { |k, v| ["", v.respond_to?(:to_html) ? v.to_html : ""] }, '
#{k}
#{v}
', '
' ].join end end end