class Patir::ShellCommand

This class wraps the Command interface around github.com/ahoward/systemu

It allows for execution of any shell command on any platform.

Accepted keys are

:cmd - the shell command to execute (required - ParameterException will be raised).
:working_directory - specify the working directory (default is '.')
:name - assign a name to the command (default is "").
:timeout - if the command runs longer than timeout, it will be interrupted and an error will be set.

The timeout is set in seconds

Public Class Methods

new(params) click to toggle source

The constructor will throw CommandError if :cmd is missing.

CommandError will also be thrown if :working_directory does not exist.

# File lib/patir/command.rb, line 110
def initialize params
  @name=params[:name]
  @working_directory=params[:working_directory] || "."
  #we need a command line :)
  raise ParameterException,"No :command defined" unless params[:cmd]
  @command=params[:cmd]
  @status=:not_executed
  @timeout=params[:timeout]
  @error=""
  @output=""
end

Public Instance Methods

run(context=nil) click to toggle source

Executes the shell command and returns the status

# File lib/patir/command.rb, line 123
def run context=nil
  start_time=Time.now
  begin
    #create the working directory if it does not exist
    FileUtils::mkdir_p(@working_directory,:verbose=>false)
    #create the actual command, run it, grab stderr and stdout and set output,error, status and execution time
    if @timeout 
      exited=nil
      exitstatus=0
      status, @output, err = systemu(@command,:cwd=>@working_directory) do |cid|
          sleep @timeout
          @error<<"Command timed out after #{@timeout}s"
          exited=true
          exitstatus=23
          Process.kill 9,cid
      end
      @error<<"\n#{err}" unless err.empty?
    else
      status, @output, @error = systemu(@command,:cwd=>@working_directory) 
      exitstatus = status.exitstatus
    end
    begin
      exited||= status.exited?
    rescue NotImplementedError
      #oh look, it's jruby
      exited=true
    end
    #lets get the status how we want it
    if exited
      if exitstatus ==0
        @status=:success
      else
        @status=:error
      end
    else
      @status=:warning
    end
  rescue
    #if it blows in systemu it will be nil
    @error<<"\n#{$!.message}"
    @error<<"\n#{$!.backtrace}" if $DEBUG
    @status=:error
  end
  #set the time it took us
  @exec_time=Time.now-start_time
  return @status
end
to_s() click to toggle source
# File lib/patir/command.rb, line 171
def to_s
  return "#{@name}: #{@command} in #{@working_directory}"
end