class FileChecksum

Constants

BUFFER_SIZE
CHECKSUM_MAP

Supported file checksum

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 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

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 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

Private Instance Methods

load_digest(type) click to toggle source
# File lib/vagrant/util/file_checksum.rb, line 65
def load_digest(type)
  digest = CHECKSUM_MAP[type.to_s.to_sym]
  if digest.nil?
    raise Vagrant::Errors::BoxChecksumInvalidType,
      type: type.to_s,
      types: CHECKSUM_MAP.keys.join(', ')
  end
  digest
end