Module: RSCM::CommandLine

Defined in:
lib/rscm/command_line.rb

Defined Under Namespace

Classes: ExecutionError, OptionError

Class Method Summary collapse

Class Method Details

.execute(cmd, options = {}, &proc) ⇒ Object

Executes cmd. If the :stdout and :stderr options are specified, a line consisting of a prompt (including cmd) will be appended to the respective output streams will be appended to those files, followed by the output itself. Example:

CommandLine.execute("echo hello world", {:stdout => "stdout.log", :stderr => "stderr.log"})

will result in the following being written to stdout.log:

/Users/aslakhellesoy/scm/buildpatterns/repos/damagecontrol/trunk aslakhellesoy$ echo hello world
hello world

-and to stderr.log:

/Users/aslakhellesoy/scm/buildpatterns/repos/damagecontrol/trunk aslakhellesoy$ echo hello world

If a block is passed, the stdout io will be yielded to it (as with IO.popen). In this case the output will not be written to the stdout file (even if it’s specified):

/Users/aslakhellesoy/scm/buildpatterns/repos/damagecontrol/trunk aslakhellesoy$ echo hello world
[output captured and therefore not logged]

If the exitstatus of the command is different from the value specified by the :exitstatus option (which defaults to 0) then an ExecutionError is raised, its message containing the last 400 bytes of stderr (provided :stderr was specified)

You can also specify the :dir option, which will cause the command to be executed in that directory (default is current directory).

You can also specify a hash of environment variables in :env, which will add additional environment variables to the default environment.

Finally, you can specify several commands within one by separating them with ‘&&’ (as you would in a shell). This will result in several lines to be appended to the log (as if you had executed the commands separately).

See the unit test for more examples.



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
# File 'lib/rscm/command_line.rb', line 52

def execute(cmd, options={}, &proc)
  raise "Can't have newline in cmd" if cmd =~ /\n/
  options = {
    :dir => Dir.pwd,
    :env => {},
    :exitstatus => 0
  }.merge(options)
  
  options[:stdout] = File.expand_path(options[:stdout]) if options[:stdout]
  options[:stderr] = File.expand_path(options[:stderr]) if options[:stderr]

  commands = cmd.split("&&").collect{|c| c.strip}
  Dir.chdir(options[:dir]) do
    stdout_opt = options[:stdout] ? ">> #{options[:stdout]}" : ""
    stderr_opt = options[:stderr] ? "2>> #{options[:stderr]}" : ""
    capture_info_command = block_given? ? "echo [output captured and therefore not logged] >> #{options[:stdout]} && " : ""

    full_cmd = commands.collect do |c|
      escaped_command = c.gsub(/"/, "\\\"").gsub(/</, "\\<")
      stdout_prompt_command = options[:stdout] ? "echo #{RSCM::Platform.prompt} #{escaped_command} >> #{options[:stdout]} && " : ""
      stderr_prompt_command = options[:stderr] ? "echo #{RSCM::Platform.prompt} #{escaped_command} >> #{options[:stderr]} && " : ""
      redirected_command = block_given? ? "#{c} #{stderr_opt}" : "#{c} #{stdout_opt} #{stderr_opt}"

      stdout_prompt_command + capture_info_command + stderr_prompt_command + redirected_command
    end.join(" && ")

    options[:env].each{|k,v| ENV[k]=v}
    begin
      IO.popen(full_cmd) do |io|
        if(block_given?)
          return(proc.call(io))
        else
          io.read
        end
      end
    rescue Errno::ENOENT => e
      File.open(options[:stderr], "a") {|io| io.write(e.message)}
      raise ExecutionError.new(cmd, options[:dir], nil, e.message)
    ensure
      if($?.exitstatus != options[:exitstatus])
        error_message = "#{options[:stderr]} doesn't exist"
        if options[:stderr] && File.exist?(options[:stderr])
          File.open(options[:stderr]) do |errio|
            begin
              errio.seek(-800, IO::SEEK_END)
            rescue Errno::EINVAL
              # ignore - it just means we didn't have 400 bytes.
            end
            error_message = errio.read
          end
        end
        raise ExecutionError.new(cmd, options[:dir], $?.exitstatus, error_message)
      end
    end
  end
  $?.exitstatus
end