Class: URI::SFTP

Inherits:
Generic show all
Defined in:
lib/buildr/core/transports.rb

Overview

:nodoc:

Constant Summary collapse

DEFAULT_PORT =
22
COMPONENT =
[ :scheme, :userinfo, :host, :port, :path ].freeze

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Generic

#download, #upload, #write

Constructor Details

#initialize(*arg) ⇒ SFTP

Returns a new instance of SFTP.



389
390
391
# File 'lib/buildr/core/transports.rb', line 389

def initialize(*arg)
  super
end

Class Method Details

.passwordsObject

Caching of passwords, so we only need to ask once.



384
385
386
# File 'lib/buildr/core/transports.rb', line 384

def passwords
  @passwords ||= {}
end

Instance Method Details

#read(options = {}, &block) ⇒ Object



393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
# File 'lib/buildr/core/transports.rb', line 393

def read(options = {}, &block)
  # SSH options are based on the username/password from the URI.
  ssh_options = { :port=>port, :password=>password }.merge(options[:ssh_options] || {})
  ssh_options[:password] ||= SFTP.passwords[host]
  begin
    trace "Connecting to #{host}"
    result = nil
    Net::SFTP.start(host, user, ssh_options) do |sftp|
      SFTP.passwords[host] = ssh_options[:password]
      trace 'connected'

      with_progress_bar options[:progress] && options[:size], path.split('/'), options[:size] || 0 do |progress|
        trace "Downloading to #{path}"
        sftp.file.open(path, 'r') do |file|
          if block
            while chunk = file.read(RW_CHUNK_SIZE)
              block.call chunk
              progress << chunk
            end
          else
            result = ''
            while chunk = file.read(RW_CHUNK_SIZE)
              result << chunk
              progress << chunk
            end
          end
        end
      end
    end
    return result
  rescue Net::SSH::AuthenticationFailed=>ex
    # Only if running with console, prompt for password.
    if !ssh_options[:password] && $stdout.isatty
      password = ask("Password for #{host}:") { |q| q.echo = '*' }
      ssh_options[:password] = password
      retry
    end
    raise
  end
end