Sha256: a2cbb0c512e405045efb59c7be74fd099d88e7c9775d5669e60fc559ecd8ab24

Contents?: true

Size: 1.39 KB

Versions: 2

Compression:

Stored size: 1.39 KB

Contents

module Datacenter
  module Shell

    class Local
      def run(command)
        Datacenter.logger.debug(self.class) { command }
        if RUBY_ENGINE == 'jruby'
          run_system command
        else
          run_open3 command
        end
      end

      private

      def run_open3(command)
        i,o,e,t = Open3.popen3 command
        (o.readlines.join + e.readlines.join).strip
      end

      def run_system(command)
        $stdout = StringIO.new
        $stderr = StringIO.new

        system command

        [$stdout, $stderr].map do |io| 
          io.rewind
          io.readlines.join.force_encoding('UTF-8')
        end.join.strip

      ensure
        $stdout = STDOUT
        $stderr = STDERR
      end
    end

    class Remote
      attr_reader :options

      def initialize(*args)
        @options = args
      end

      def run(command)
        Datacenter.logger.debug(self.class) { command }
        if @session
          @session.exec!(command).strip
        else
          Net::SSH.start(*options) { |ssh| ssh.exec! command }.to_s.strip
        end
      end

      def open
        @session ||= Net::SSH.start *options
      end

      def close
        if @session
          @session.close
          @session = nil
        end
      end

      def self.open(*args, &block)
        shell = new *args
        shell.open
        block.call shell
        shell.close
      end
    end

  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
datacenter-0.2.2 lib/datacenter/shell.rb
datacenter-0.2.1 lib/datacenter/shell.rb