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.



399
400
401
# File 'lib/buildr/core/transports.rb', line 399

def initialize(*arg)
  super
end

Class Method Details

.passwordsObject

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



394
395
396
# File 'lib/buildr/core/transports.rb', line 394

def passwords
  @passwords ||= {}
end

Instance Method Details

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



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
433
434
435
436
437
438
439
440
# File 'lib/buildr/core/transports.rb', line 403

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}"
    if block
      result = nil
    else
      result = ''
      block = lambda { |chunk| result << chunk }
    end
    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('/').last, options[:size] || 0 do |progress|
        trace "Downloading from #{path}"
        sftp.file.open(path, 'r') do |file|
          while chunk = file.read(RW_CHUNK_SIZE)
            block.call chunk
            progress << chunk
            break if chunk.size < RW_CHUNK_SIZE
          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