Sha256: 2bea4be17f103f227148b09869224de5c33fe5ad73ee6edee6ebf018f4a77e48

Contents?: true

Size: 1.12 KB

Versions: 8

Compression:

Stored size: 1.12 KB

Contents

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

8 entries across 8 versions & 1 rubygems

Version Path
nanoc-4.0.2 lib/nanoc/extra/piper.rb
nanoc-4.0.1 lib/nanoc/extra/piper.rb
nanoc-4.0.0 lib/nanoc/extra/piper.rb
nanoc-4.0.0rc3 lib/nanoc/extra/piper.rb
nanoc-4.0.0rc2 lib/nanoc/extra/piper.rb
nanoc-4.0.0rc1 lib/nanoc/extra/piper.rb
nanoc-4.0.0b4 lib/nanoc/extra/piper.rb
nanoc-4.0.0b3 lib/nanoc/extra/piper.rb