Class: ChefCore::FileFetcher

Inherits:
Object
  • Object
show all
Defined in:
lib/chef_core/file_fetcher.rb

Class Method Summary collapse

Class Method Details

.download_file(url, local_path) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/chef_core/file_fetcher.rb', line 39

def download_file(url, local_path)
  temp_path = "#{local_path}.downloading"
  file = open(temp_path, "wb")
  ChefCore::Log.debug "Downloading: #{temp_path}"
  Net::HTTP.start(url.host) do |http|
    begin
      http.request_get(url.path) do |resp|
        resp.read_body do |segment|
          file.write(segment)
        end
      end
    rescue e
      @error = true
      raise
    ensure
      file.close
      # If any failures occurred, don't risk keeping
      # an incomplete download that we'll see as 'cached'
      if @error
        FileUtils.rm_f(temp_path)
      else
        FileUtils.mv(temp_path, local_path)
      end
    end
  end
end

.fetch(cache_path, path) ⇒ Object

Simple fetcher of an http(s) url. Returns the local path of the downloaded file.



26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/chef_core/file_fetcher.rb', line 26

def fetch(cache_path, path)
  FileUtils.mkdir_p(cache_path)
  url = URI.parse(path)
  name = File.basename(url.path)
  local_path = File.join(cache_path, name)

  # TODO header check for size or checksum?
  return local_path if File.exist?(local_path)

  download_file(url, local_path)
  local_path
end