Method: FileDependencies::File.download

Defined in:
lib/file-dependencies/file.rb

.download(url, target) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/file-dependencies/file.rb', line 47

def download(url, target)
  uri = URI(url)
  output = ::File.join(target, ::File.basename(uri.path))
  tmp = "#{output}.tmp"
  Net::HTTP.start(uri.host, uri.port, :use_ssl => (uri.scheme == "https")) do |http|
    request = Net::HTTP::Get.new(uri.path)
    http.request(request) do |response|
      raise("HTTP fetch failed for #{url}. #{response}") unless [200, 301].include?(response.code.to_i)
      size = (response["content-length"].to_i || -1).to_f
      count = 0
      ::File.open(tmp, "w") do |fd|
        response.read_body do |chunk|
          fd.write(chunk)
          if size > 0 && $stdout.tty?
            count += chunk.bytesize
            $stdout.write(sprintf("\r%0.2f%%", count / size * 100))
          end
        end
      end
      $stdout.write("\r      \r") if $stdout.tty?
    end
  end

  ::File.rename(tmp, output)

  return output
rescue SocketError => e
  puts "Failure while downloading #{url}: #{e}"
  raise
ensure
  ::File.unlink(tmp) if ::File.exist?(tmp)
end