Class: CmdRunner::Command
- Inherits:
-
Object
- Object
- CmdRunner::Command
- Defined in:
- lib/cmd_runner.rb
Overview
Class: Command
Runs a command and grabs STDOUT, STDERR. Checks exit status to raise an exception in case of non-zero.
Example:
runner = CmdRunner::Command.new
runner.work_dir = '/tmp' # to change dir before every command
runner.logger = Logger.new # to log command results
runner.execute!('ls') #=> [0, '.\n..\n', '']
Instance Attribute Summary collapse
- #cmd ⇒ Object
-
#logger ⇒ Object
writeonly
Logger to output command results.
-
#work_dir ⇒ Object
Change directory before each command.
Instance Method Summary collapse
-
#execute! ⇒ Object
Executes command.
Instance Attribute Details
#cmd ⇒ Object
26 27 28 29 30 31 32 |
# File 'lib/cmd_runner.rb', line 26 def cmd if self.work_dir.to_s.empty? @cmd else "cd #{self.work_dir} && " + @cmd end end |
#logger=(value) ⇒ Object
Logger to output command results
22 23 24 |
# File 'lib/cmd_runner.rb', line 22 def logger=(value) @logger = value end |
#work_dir ⇒ Object
Change directory before each command
20 21 22 |
# File 'lib/cmd_runner.rb', line 20 def work_dir @work_dir end |
Instance Method Details
#execute! ⇒ Object
Executes command.
Raises:
- {RuntimeError} if command returned non-zero status
Returns Array with exit status, stdout, stderr
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
# File 'lib/cmd_runner.rb', line 40 def execute! result = '' error = '' stdin, stdout, stderr, wait_thr = Open3.popen3(self.cmd) exit_status = wait_thr.value.exitstatus result << stdout.read error << stderr.read raise "Command exited with non zero status: #{self.cmd}" unless exit_status.zero? [exit_status, result, error] ensure logger.info '-'*25 logger.info "Command: #{self.cmd}" logger.info result logger.error error logger.info '-'*25 end |