Class: Contrast::Utils::Sha256Builder

Inherits:
Object
  • Object
show all
Includes:
Singleton
Defined in:
lib/contrast/utils/sha256_builder.rb

Overview

Utility methods for building and caching hashes from strings

Constant Summary collapse

PATHS =

Return a list of “source” files. Ignore metadata files as well as files in the spec, test or exe directories. Could potentially miss important files but good enough for the time being.

'{lib,bin,ext}/**/*.{rb,c,h,c++,cpp,java,rs}'

Instance Method Summary collapse

Constructor Details

#initializeSha256Builder

Returns a new instance of Sha256Builder.



17
18
19
20
# File 'lib/contrast/utils/sha256_builder.rb', line 17

def initialize
  @sha256_cache = {}
  @gem_hash_cache = {}
end

Instance Method Details

#build_from_spec(spec) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
# File 'lib/contrast/utils/sha256_builder.rb', line 38

def build_from_spec spec
  name = spec.file_name.to_s
  cached = @gem_hash_cache[name]
  return cached if cached

  gem_path = File.join(cache_dir(spec), name)
  hash = sha256(gem_path)

  @gem_hash_cache[name] = hash
  hash
end

#cache_dir(spec) ⇒ Object



50
51
52
53
54
# File 'lib/contrast/utils/sha256_builder.rb', line 50

def cache_dir spec
  gems_dir = spec.gems_dir
  parent_dir = File.dirname(gems_dir)
  File.join(parent_dir, Contrast::Utils::ObjectShare::CACHE)
end

#files(path) ⇒ Object



22
23
24
25
26
27
28
# File 'lib/contrast/utils/sha256_builder.rb', line 22

def files path
  if Dir.exist?(path)
    Dir.glob(File.join(path, PATHS))
  else
    []
  end
end

#sha256(path) ⇒ Object

Generate a SHA256 hash of the combined source code of this Gem



31
32
33
34
35
36
# File 'lib/contrast/utils/sha256_builder.rb', line 31

def sha256 path
  return unless path
  return unless File.exist?(path) && !File.directory?(path)

  @sha256_cache[path] ||= Digest::SHA256.file(path).to_s
end