lib/tty/command/process_runner.rb in tty-command-0.9.0 vs lib/tty/command/process_runner.rb in tty-command-0.10.0

- old
+ new

@@ -1,12 +1,12 @@ # frozen_string_literal: true -require 'thread' +require "thread" -require_relative 'child_process' -require_relative 'result' -require_relative 'truncator' +require_relative "child_process" +require_relative "result" +require_relative "truncator" module TTY class Command class ProcessRunner # the command to be spawned @@ -126,24 +126,24 @@ # @api private def read_streams(stdout, stderr) stdout_data = [] stderr_data = Truncator.new - out_buffer = ->(line) { - stdout_data << line - @printer.print_command_out_data(cmd, line) - @block.(line, nil) if @block + out_handler = ->(data) { + stdout_data << data + @printer.print_command_out_data(cmd, data) + @block.(data, nil) if @block } - err_buffer = ->(line) { - stderr_data << line - @printer.print_command_err_data(cmd, line) - @block.(nil, line) if @block + err_handler = ->(data) { + stderr_data << data + @printer.print_command_err_data(cmd, data) + @block.(nil, data) if @block } - stdout_thread = read_stream(stdout, out_buffer) - stderr_thread = read_stream(stderr, err_buffer) + stdout_thread = read_stream(stdout, out_handler) + stderr_thread = read_stream(stderr, err_handler) stdout_thread.join stderr_thread.join encoding = @binmode ? Encoding::BINARY : Encoding::UTF_8 @@ -152,11 +152,19 @@ stdout_data.join.force_encoding(encoding), stderr_data.read.dup.force_encoding(encoding) ] end - def read_stream(stream, buffer) + # Read stream and invoke handler when data becomes available + # + # @param [IO] stream + # the stream to read data from + # @param [Proc] handler + # the handler to call when data becomes available + # + # @api private + def read_stream(stream, handler) Thread.new do if Thread.current.respond_to?(:report_on_exception) Thread.current.report_on_exception = false end Thread.current[:cmd_start] = Time.now @@ -166,11 +174,11 @@ ready = IO.select(readers, nil, readers, @timeout) raise TimeoutExceeded if ready.nil? ready[0].each do |reader| begin - line = reader.readpartial(BUFSIZE) - buffer.(line) + chunk = reader.readpartial(BUFSIZE) + handler.(chunk) # control total time spent reading runtime = Time.now - Thread.current[:cmd_start] handle_timeout(runtime) rescue Errno::EAGAIN, Errno::EINTR