Class: Hercules::CommandRunner

Inherits:
Object
  • Object
show all
Defined in:
lib/command_runner.rb

Overview

Class to run the shell commands and store their output. Yes, this class was kindly provided by Integrity. A very nice CI solution built with ruby: github.com/integrity/integrity I’ve made some modifications to store all the commands ran in an output log.

Defined Under Namespace

Classes: Error, Result

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(logger) ⇒ CommandRunner

We need to inform the logger object to initialize a CommandRunner



15
16
17
18
# File 'lib/command_runner.rb', line 15

def initialize(logger)
  @logger = logger
  @output = ""
end

Instance Attribute Details

#outputObject (readonly)

Returns the value of attribute output.



7
8
9
# File 'lib/command_runner.rb', line 7

def output
  @output
end

Instance Method Details

#cd(dir) ⇒ Object

Change the working directory.

  • dir is the new working directory.



29
30
31
32
# File 'lib/command_runner.rb', line 29

def cd(dir)
  @dir = dir
  self
end

#normalize(cmd) ⇒ Object

We change the working directory befor executing anything.

  • cmd is the command to be executed.



65
66
67
68
69
70
71
# File 'lib/command_runner.rb', line 65

def normalize(cmd)
  if @dir
    "(cd #{@dir} && #{cmd} 2>&1)"
  else
    "(#{cmd} 2>&1)"
  end
end

#run(command) ⇒ Object

Run a command using IO.popen, append output to @output

  • command is the string containing the shell command that will be run.



36
37
38
39
40
41
42
43
44
45
46
# File 'lib/command_runner.rb', line 36

def run(command)
  cmd = normalize(command)

  @logger.debug(cmd)

  output = ""
  IO.popen(cmd, "r") { |io| output = io.read }

  @output += output
  Result.new($?.success?, output.chomp)
end

#run!(command) ⇒ Object

Run a command using IO.popen, append output to @output But we raise an error in case the command is not successful.

  • command is the string containing the shell command that will be run.



51
52
53
54
55
56
57
58
59
60
61
# File 'lib/command_runner.rb', line 51

def run!(command)
  result = run(command)

  unless result.success
    @logger.error(result.output.inspect)
    raise Error, "Failed to run '#{command}'"
  end
  @logger.debug(result.output.inspect)

  result
end

#store_output(path) ⇒ Object

This method will store the output of every command ran by this instance on a file.

  • path is the file path where we want to store the log.



23
24
25
# File 'lib/command_runner.rb', line 23

def store_output path
  File.open(path, 'a+'){|f| f.write @output }
end