Skip to content

Commit

Permalink
Implement SFTP transfer strategy
Browse files Browse the repository at this point in the history
  • Loading branch information
mattbrictson committed Dec 22, 2023
1 parent 0d65d88 commit 984b374
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 2 deletions.
11 changes: 9 additions & 2 deletions lib/sshkit/backends/netssh.rb
Original file line number Diff line number Diff line change
Expand Up @@ -200,10 +200,17 @@ def with_ssh(&block)
end

def with_transfer(summarizer)
require_relative "netssh/scp_transfer"
transfer_method = host.transfer_method || self.class.config.transfer_method
transfer_class = if transfer_method == :sftp
require_relative "netssh/sftp_transfer"
SftpTransfer
else
require_relative "netssh/scp_transfer"
ScpTransfer
end

with_ssh do |ssh|
yield(ScpTransfer.new(ssh, summarizer))
yield(transfer_class.new(ssh, summarizer))
end
end
end
Expand Down
46 changes: 46 additions & 0 deletions lib/sshkit/backends/netssh/sftp_transfer.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
require "net/sftp"

module SSHKit
module Backend
class Netssh < Abstract
class SftpTransfer
def initialize(ssh, summarizer)
@ssh = ssh
@summarizer = summarizer
end

def upload!(local, remote, options)
options = { progress: self }.merge(options || {})
ssh.sftp.connect!
ssh.sftp.upload!(local, remote, options)
ensure
ssh.sftp.close_channel
end

def download!(remote, local, options)
options = { progress: self }.merge(options || {})
destination = local ? local : StringIO.new.tap { |io| io.set_encoding('BINARY') }

ssh.sftp.connect!
ssh.sftp.download!(remote, destination, options)
local ? true : destination.string
ensure
ssh.sftp.close_channel
end

def on_get(download, entry, offset, data)
entry.size ||= download.sftp.file.open(entry.remote, &:size)
summarizer.call(nil, entry.remote, offset + data.bytesize, entry.size)
end

def on_put(_upload, file, offset, data)
summarizer.call(nil, file.local, offset + data.bytesize, file.size)
end

private

attr_reader :ssh, :summarizer
end
end
end
end

0 comments on commit 984b374

Please sign in to comment.