Sha256: a4596ba22819f5cbf0563f8ef7c6bb9754b5d66d5c32cb582e2fbc65b12e7259

Contents?: true

Size: 1.71 KB

Versions: 2

Compression:

Stored size: 1.71 KB

Contents

require "net/ssh"
require "shellwords"
require "etc"

module Masterbaker
  class RemoteError < RuntimeError; end

  class Remote
    attr_reader :user, :host, :key, :timeout, :stdout, :stderr, :exitstatus
    attr_writer :connection

    def self.from_uri(uri, key = "~/.ssh/id_rsa")
      parsed = URI.parse("ssh://#{uri}")
      new(parsed.user || Etc.getlogin, parsed.host, key)
    end

    def initialize(user, host, key, options = {})
      @user = user
      @host = host
      @key = File.expand_path(key)
      @timeout = options[:timeout] || 10000
    end

    def backtick(command)
      @stdout = ""
      @stderr = ""
      exec(command)
      @stdout
    end

    def system(command)
      @stdout = STDOUT
      @stderr = STDERR
      exec(command)
      exitstatus
    end

    def system!(*command)
      system(*command).tap do |status|
        raise RemoteError.new("#{command.join(" ")} exited #{status}") unless status == 0
      end
    end

    def upload(from, to, opts = "--exclude .git")
      Kernel.system("rsync -e 'ssh -i #{key}' -avz --delete #{from} #{user}@#{host}:#{to} #{opts}")
    end

    private
    def connection
      @connection ||= Net::SSH.start(host, user, :keys => [key], :timeout => timeout)
    end

    def exec(*command)
      connection.open_channel do |channel|
        channel.exec(*command) do |stream, success|
          raise RemoteError.new("Could not run #{command.join(" ")}") unless success
          stream.on_data { |_, data| stdout << data }
          stream.on_extended_data { |_, type, data| stderr << data }
          stream.on_request("exit-status") { |_, data| @exitstatus = data.read_long }
        end
      end
      connection.loop
      @exitstatus ||= 0
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
masterbaker-0.9.0 lib/masterbaker/remote.rb
masterbaker-0.7.8 lib/masterbaker/remote.rb