Sha256: 436d9dd2b1db9be5cf0b021b0c03dd1f9785cb5de220ffed838bcd25e52bf3e6

Contents?: true

Size: 1.14 KB

Versions: 4

Compression:

Stored size: 1.14 KB

Contents

# encoding: utf-8

require 'open3'

module Nanoc::Extra
  # @api private
  class Piper
    class Error < ::Nanoc::Int::Errors::Generic
      def initialize(command, exit_code)
        @command   = command
        @exit_code = exit_code
      end

      def message
        "command exited with a nonzero status code #{@exit_code} (command: #{@command.join(' ')})"
      end
    end

    # @option [IO] :stdout ($stdout)
    # @option [IO] :stderr ($stderr)
    def initialize(params = {})
      @stdout = params.fetch(:stdout, $stdout)
      @stderr = params.fetch(:stderr, $stderr)
    end

    # @param [Array<String>] cmd
    #
    # @param [String, nil] input
    def run(cmd, input)
      Open3.popen3(*cmd) do |stdin, stdout, stderr, wait_thr|
        stdout_thread = Thread.new { @stdout << stdout.read }
        stderr_thread = Thread.new { @stderr << stderr.read }

        if input
          stdin << input
        end
        stdin.close

        stdout_thread.join
        stderr_thread.join

        exit_status = wait_thr.value
        unless exit_status.success?
          raise Error.new(cmd, exit_status.to_i)
        end
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
nanoc-4.0.0b2 lib/nanoc/extra/piper.rb
nanoc-4.0.0b1 lib/nanoc/extra/piper.rb
nanoc-4.0.0a2 lib/nanoc/extra/piper.rb
nanoc-4.0.0a1 lib/nanoc/extra/piper.rb