class FileChecksum

Constants

BUFFER_SIZE

Public Class Methods

new(path, digest_klass) click to toggle source

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.

# File lib/vagrant/util/file_checksum.rb, line 17
def initialize(path, digest_klass)
  @digest_klass = digest_klass
  @path         = path
end

Public Instance Methods

checksum() click to toggle source

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

@return [String]

# File lib/vagrant/util/file_checksum.rb, line 26
def checksum
  digest = @digest_klass.new

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

  return digest.hexdigest
end