class WinRM::FS::Core::FileUploader

Uploads the given source file to a temp file in 8k chunks

Public Class Methods

new(command_executor) click to toggle source
# File lib/winrm-fs/core/file_uploader.rb, line 23
def initialize(command_executor)
  @command_executor = command_executor
end

Public Instance Methods

upload(local_file, remote_file, &block) click to toggle source

Uploads the given file to the specified temp file as base64 encoded.

@param [String] Path to the local source file on this machine @param [String] Path to the file on the target machine @return [Integer] Count of bytes uploaded

# File lib/winrm-fs/core/file_uploader.rb, line 32
def upload(local_file, remote_file, &block)
  @command_executor.run_powershell(prepare_script(remote_file))
  do_upload(local_file, dos_path(remote_file), &block)
end

Private Instance Methods

base64_content(local_file) click to toggle source
# File lib/winrm-fs/core/file_uploader.rb, line 50
def base64_content(local_file)
  base64_host_file = Base64.encode64(IO.binread(local_file)).gsub("\n", '')
  base64_host_file.chars.to_a
end
do_upload(local_file, remote_file) { |bytes_copied, count| ... } click to toggle source
# File lib/winrm-fs/core/file_uploader.rb, line 39
def do_upload(local_file, remote_file)
  bytes_copied = 0
  base64_array = base64_content(local_file)
  base64_array.each_slice(8000 - remote_file.size) do |chunk|
    @command_executor.run_cmd("echo #{chunk.join} >> \"#{remote_file}\"")
    bytes_copied += chunk.count
    yield bytes_copied, base64_array.count if block_given?
  end
  base64_array.length
end
dos_path(path) click to toggle source
# File lib/winrm-fs/core/file_uploader.rb, line 55
def dos_path(path)
  # TODO: convert all env vars
  path = path.gsub(/\$env:TEMP/, '%TEMP%')
  path.gsub(/\/, '/')
end
prepare_script(remote_file) click to toggle source

rubocop:disable Metrics/MethodLength

# File lib/winrm-fs/core/file_uploader.rb, line 62
def prepare_script(remote_file)
  <<-EOH
    $p = $ExecutionContext.SessionState.Path
    $path = $p.GetUnresolvedProviderPathFromPSPath("#{remote_file}")

    # if the file exists, truncate it
    if (Test-Path $path -PathType Leaf) {
      '' | Set-Content $path
    }

    # ensure the target directory exists
    $dir = [System.IO.Path]::GetDirectoryName($path)
    if (!(Test-Path $dir -PathType Container)) {
      mkdir $dir -ErrorAction SilentlyContinue | Out-Null
    }
  EOH
end