Skip to content

Commit

Permalink
moar WIP
Browse files Browse the repository at this point in the history
  • Loading branch information
atz committed Apr 6, 2018
1 parent 78c54eb commit 3b77eac
Showing 1 changed file with 9 additions and 14 deletions.
23 changes: 9 additions & 14 deletions lib/moab/file_signature.rb
Expand Up @@ -65,33 +65,28 @@ def initialize(opts = {})
# @return [String] The SHA256 checksum value of the file
attribute :sha256, String, :on_save => Proc.new { |n| n.nil? ? "" : n.to_s }

ALL_CHECKSUM_ALGOS = {
KNOWN_ALGOS = {
md5: proc { Digest::MD5.new },
sha1: proc { Digest::SHA1.new },
sha256: proc { Digest::SHA2.new(256) }
}.freeze

def self.from_file(pathname, algos_to_use = nil)
algos_to_use ||= ALL_CHECKSUM_ALGOS.keys
if algos_to_use
raise 'Unrecognized algorithm requested' unless algos_to_use.all? { |a| KNOWN_ALGOS.include?(a) }
else
algos_to_use = KNOWN_ALGOS.keys
end

computed_signatures = algos_to_use.map do |algo_name|
[algo_name, ALL_CHECKSUM_ALGOS[algo_name].call]
end.to_h
signatures = algos_to_use.map { |k| [k, KNOWN_ALGOS[k].call] }.to_h

pathname.open("r") do |stream|
while (buffer = stream.read(8192))
computed_signatures.each_value do |digest|
digest.update(buffer)
end
signatures.each_value { |digest| digest.update(buffer) }
end
end

file_signature = new(size: pathname.size)
computed_signatures.each do |algo_name, digest|
file_signature.instance_variable_set("@#{algo_name}", digest.hexdigest)
end

file_signature
new(signatures.map { |k, digest| [k, digest.hexdigest] }.to_h.merge(size: pathname.size) )
end

# @param type [Symbol,String] The type of checksum
Expand Down

0 comments on commit 3b77eac

Please sign in to comment.