File: cache.rb

package info (click to toggle)
puppet 5.5.22-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 21,316 kB
  • sloc: ruby: 254,925; sh: 1,608; xml: 219; makefile: 153; sql: 103
file content (60 lines) | stat: -rw-r--r-- 1,692 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
require 'uri'

require 'puppet/forge'

class Puppet::Forge
  # = Cache
  #
  # Provides methods for reading files from local cache, filesystem or network.
  class Cache

    # Instantiate new cache for the +repository+ instance.
    def initialize(repository, options = {})
      @repository = repository
      @options = options
    end

    # Return filename retrieved from +uri+ instance. Will download this file and
    # cache it if needed.
    #
    # TODO: Add checksum support.
    # TODO: Add error checking.
    def retrieve(url)
      (path + File.basename(url.to_s)).tap do |cached_file|
        uri = url.is_a?(::URI) ? url : ::URI.parse(url)
        unless cached_file.file?
          if uri.scheme == 'file'
            # CGI.unescape butchers Uris that are escaped properly
            FileUtils.cp(Puppet::Util.uri_unescape(uri.path), cached_file)
          else
            # TODO: Handle HTTPS; probably should use repository.contact
            data = read_retrieve(uri)
            cached_file.open('wb') { |f| f.write data }
          end
        end
      end
    end

    # Return contents of file at the given URI's +uri+.
    def read_retrieve(uri)
      return uri.read
    end

    # Return Pathname for repository's cache directory, create it if needed.
    def path
      (self.class.base_path + @repository.cache_key).tap{ |o| o.mkpath }
    end

    # Return the base Pathname for all the caches.
    def self.base_path
      (Pathname(Puppet.settings[:module_working_dir]) + 'cache').tap do |o|
        o.mkpath unless o.exist?
      end
    end

    # Clean out all the caches.
    def self.clean
      base_path.rmtree if base_path.exist?
    end
  end
end