Class: FileChecksum

Inherits:
Object
  • Object
show all
Defined in:
lib/vagrant/util/file_checksum.rb

Constant Summary collapse

BUFFER_SIZE =
1024 * 8
CHECKSUM_MAP =

Supported file checksum

{
  :md5 => Digest::MD5,
  :sha1 => Digest::SHA1,
  :sha256 => Digest::SHA256,
  :sha384 => Digest::SHA384,
  :sha512 => Digest::SHA512
}.freeze

Instance Method Summary collapse

Constructor Details

#initialize(path, digest_klass) ⇒ FileChecksum

Initializes an object to calculate the checksum of a file. The given digest_klass should implement the DigestClass interface. Note that the built-in Ruby digest classes duck type this properly: Digest::MD5, Digest::SHA1, etc.


29
30
31
32
33
34
35
36
37
# File 'lib/vagrant/util/file_checksum.rb', line 29

def initialize(path, digest_klass)
  if digest_klass.is_a?(Class)
    @digest_klass = digest_klass
  else
    @digest_klass = load_digest(digest_klass)
  end

  @path = path
end

Instance Method Details

#checksumString

This calculates the checksum of the file and returns it as a string.

Returns:

  • (String)

43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/vagrant/util/file_checksum.rb', line 43

def checksum
  digest = @digest_klass.new
  buf = ''

  File.open(@path, "rb") do |f|
    while !f.eof
      begin
        f.readpartial(BUFFER_SIZE, buf)
        digest.update(buf)
      rescue EOFError
        # Although we check for EOF earlier, this seems to happen
        # sometimes anyways [GH-2716].
        break
      end
    end
  end

  digest.hexdigest
end