Class: TravisCustomDeploy::Transfer::Sftp

Inherits:
Base
  • Object
show all
Defined in:
lib/travis-custom-deploy/transfer/sftp.rb

Overview

The class which transfers files via the SSH File Transfer Protocol (SFTP).

Instance Attribute Summary

Attributes inherited from Base

#files, #options

Instance Method Summary collapse

Constructor Details

#initialize(options, files) ⇒ Sftp

Returns a new instance of Sftp.



11
12
13
14
# File 'lib/travis-custom-deploy/transfer/sftp.rb', line 11

def initialize(options, files)
  super(options, files)
  prepare_remotedir
end

Instance Method Details

#check_options(options) ⇒ Object

Check if the passed arguments are sufficient

Raises:

  • (ArgumentError)


29
30
31
32
33
# File 'lib/travis-custom-deploy/transfer/sftp.rb', line 29

def check_options(options)
  raise ArgumentError, 'host name must not be nil' if options['host'].nil?
  raise ArgumentError, 'userna)e must not be nil' if options['username'].nil?
  raise ArgumentError, 'password must not be nil' if options['password'].nil?
end

#prepare_remotedirObject

Prepares the remote directory (remote trailing slash)



59
60
61
62
63
# File 'lib/travis-custom-deploy/transfer/sftp.rb', line 59

def prepare_remotedir
  @remotedir = @options['remotedir']
  @remotedir = "" if @remotedir.nil?
  @remotedir = @remotedir[0..-2] if @remotedir[-1] == "/"
end

#send_dir(sftp, dir, remote) ⇒ Object

Sends a directory to the remote server with the given parameters

sftp - the SFTP connection dir - the local dir to transfer the remote folder where to place the files



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/travis-custom-deploy/transfer/sftp.rb', line 40

def send_dir(sftp, dir, remote)
  Dir.foreach(dir) do |file_name|
    next if file_name =~ /^(\.|\.\.)$/

    localfile = File.join(dir, file_name)
    if File.directory?(localfile)
      begin 
        sftp.mkdir!(remote + "/" + file_name)
      rescue Net::SFTP::StatusException
        # the directory probably already exists
      end
      send_dir(sftp, File.join(dir, file_name), File.join(remote, file_name))
    else
      sftp.upload!(File.join(dir, file_name), File.join(remote, file_name))
    end
  end
end

#transferObject



16
17
18
19
20
21
22
23
24
25
26
# File 'lib/travis-custom-deploy/transfer/sftp.rb', line 16

def transfer
  Net::SFTP.start(@options['host'], @options['username'], :password => @options['password']) do |sftp|
    for e in @files
      if File.directory?(e)
        send_dir(sftp, e, @remotedir)
      else
        sftp.upload!(e, @remotedir + "/" + File.basename(e))
      end
    end
  end
end