From 0d36eead55b7be63574ab140e0d0e247c7270e90 Mon Sep 17 00:00:00 2001 From: Piotr Murach Date: Tue, 10 May 2016 22:06:45 +0100 Subject: [PATCH] Change execute to throw on non zero exit code by default and close #7 --- lib/tty/command.rb | 41 +++++++++++++++++++++++++-------------- spec/unit/execute_spec.rb | 4 ++-- 2 files changed, 28 insertions(+), 17 deletions(-) diff --git a/lib/tty/command.rb b/lib/tty/command.rb index 005719c..72912a2 100644 --- a/lib/tty/command.rb +++ b/lib/tty/command.rb @@ -51,40 +51,51 @@ def initialize(options = {}) # # @option options [String] :chdir # The current directory. + # # @option options [Integer] :timeout # Maximum number of seconds to allow the process # to execute before aborting with a TimeoutExceeded # exception. # + # @raise [ExitError] + # raised when command exits with non-zero code + # # @api public def execute(*args) - cmd = Cmd.new(*args) + cmd = command(*args) yield(cmd) if block_given? - mutex = Mutex.new - mutex.synchronize { @runner.run(cmd) } + result = execute_command(cmd) + if result && result.failure? + raise ExitError.new(cmd.to_command, result) + end + result end - # Throw exception when failed + # Start external executable without raising ExitError # # @example # cmd.execute!(command, [argv1, ..., argvN], [options]) # - # @raise [ExitError] - # raised when command exits with non-zero code - # # @api public def execute!(*args) - cmd_name = nil - result = execute(*args) do |cmd| - cmd_name = cmd.to_command - end - if result && result.failure? - raise ExitError.new(cmd_name, result) - end + cmd = command(*args) + yield(cmd) if block_given? + execute_command(cmd) end private + # @api private + def command(*args) + Cmd.new(*args) + end + + # @api private + def execute_command(cmd) + mutex = Mutex.new + mutex.synchronize { @runner.run(cmd) } + end + # @api private def use_printer(class_or_name, options) if class_or_name.is_a?(TTY::Command::Printers::Abstract) @@ -106,7 +117,7 @@ def use_printer(class_or_name, options) def find_printer_class(name) const_name = name.to_s.capitalize.to_sym unless TTY::Command::Printers.const_defined?(const_name) - fail ArgumentError, %Q{Unknown printer type "#{name}"} + fail ArgumentError, %(Unknown printer type "#{name}") end TTY::Command::Printers.const_get(const_name) end diff --git a/spec/unit/execute_spec.rb b/spec/unit/execute_spec.rb index 36be0e6..f6507e5 100644 --- a/spec/unit/execute_spec.rb +++ b/spec/unit/execute_spec.rb @@ -80,7 +80,7 @@ uuid = nil command = TTY::Command.new(output: output) - command.execute("echo 'nooo'; exit 1") do |cmd| + command.execute!("echo 'nooo'; exit 1") do |cmd| uuid = cmd.uuid end output.rewind @@ -99,7 +99,7 @@ command = TTY::Command.new(output: output) expect { - command.execute!("echo 'nooo'; exit 1") + command.execute("echo 'nooo'; exit 1") }.to raise_error(TTY::Command::ExitError, ["Executing `echo 'nooo'; exit 1` failed with", " exit status: 1",