Skip to content

Commit

Permalink
Change execute to throw on non zero exit code by default and close #7
Browse files Browse the repository at this point in the history
  • Loading branch information
piotrmurach committed May 10, 2016
1 parent 98d530c commit 0d36eea
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 17 deletions.
41 changes: 26 additions & 15 deletions lib/tty/command.rb
Expand Up @@ -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)
Expand All @@ -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
Expand Down
4 changes: 2 additions & 2 deletions spec/unit/execute_spec.rb
Expand Up @@ -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
Expand All @@ -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",
Expand Down

0 comments on commit 0d36eea

Please sign in to comment.