Class: FileHashCache

Inherits:
Object
  • Object
show all
Defined in:
lib/wonko_the_sane/util/file_hash_cache.rb

Constant Summary collapse

@@defaultCache =
FileHashCache.new 'cache/filehashes', :sha256
@@md5Cache =
FileHashCache.new 'cache/filehashes.md5', :md5

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file, algorithm) ⇒ FileHashCache

Returns a new instance of FileHashCache.



2
3
4
5
6
7
# File 'lib/wonko_the_sane/util/file_hash_cache.rb', line 2

def initialize(file, algorithm)
  @file = file
  @algorithm = algorithm
  @data = JSON.parse File.read(@file), symbolize_names: true if File.exists? @file
  @data ||= {}
end

Class Method Details

.get(file) ⇒ Object



34
35
36
# File 'lib/wonko_the_sane/util/file_hash_cache.rb', line 34

def self.get(file)
  @@defaultCache.get file
end

.get_md5(file) ⇒ Object



39
40
41
# File 'lib/wonko_the_sane/util/file_hash_cache.rb', line 39

def self.get_md5(file)
  @@md5Cache.get file
end

Instance Method Details

#digest(data) ⇒ Object



25
26
27
28
29
30
31
# File 'lib/wonko_the_sane/util/file_hash_cache.rb', line 25

def digest(data)
  if @algorithm == :sha256
    Digest::SHA256.hexdigest data
  elsif @algorithm == :md5
    Digest::MD5.hexdigest data
  end
end

#get(file) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/wonko_the_sane/util/file_hash_cache.rb', line 9

def get(file)
  name = (file.is_a?(File) ? file.path : file).to_sym
  timestamp = (file.is_a?(File) ? file.mtime : File.mtime(file)).to_i
  size = file.is_a?(File) ? file.size : File.size(file)
  if not @data[name] or not @data[name][:timestamp] == timestamp or not @data[name][:size] == size
    hash = digest(file.is_a?(File) ? file.read : File.read(file))
    @data[name] = {
        timestamp: timestamp,
        size: size,
        hash: hash
    }
    File.write @file, JSON.pretty_generate(@data)
  end
  return @data[name][:hash]
end