summaryrefslogtreecommitdiffstats
path: root/lib/puppet/checksum.rb
blob: c607953c1d5371ce88fdb73f44cc932f2421b2c8 (plain)
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
61
62
63
64
#
#  Created by Luke Kanies on 2007-9-22.
#  Copyright (c) 2007. All rights reserved.

require 'puppet'
require 'puppet/indirector'

# A checksum class to model translating checksums to file paths.  This
# is the new filebucket.
class Puppet::Checksum
    extend Puppet::Indirector

    indirects :checksum

    attr_reader :algorithm, :content

    def algorithm=(value)
        unless respond_to?(value)
            raise ArgumentError, "Checksum algorithm %s is not supported" % value
        end
        value = value.intern if value.is_a?(String)
        @algorithm = value
        # Reset the checksum so it's forced to be recalculated.
        @checksum = nil
    end

    # Calculate (if necessary) and return the checksum
    def checksum
        unless @checksum
            @checksum = send(algorithm)
        end
        @checksum
    end

    def initialize(content, algorithm = nil)
        raise ArgumentError.new("You must specify the content") unless content

        @content = content
        self.algorithm = algorithm || "md5"

        # Init to avoid warnings.
        @checksum = nil
    end

    # This can't be private, else respond_to? returns false.
    def md5
        require 'digest/md5'
        Digest::MD5.hexdigest(content)
    end

    # This is here so the Indirector::File terminus works correctly.
    def name
        checksum
    end

    def sha1
        require 'digest/sha1'
        Digest::SHA1.hexdigest(content)
    end

    def to_s
        "Checksum<{%s}%s>" % [algorithm, checksum]
    end
end