Sha256: 668a4b1a314381390d62d3b1b0402c2a9714e7dae5962bc8e2e0ae9edae3bc1d

Contents?: true

Size: 1.8 KB

Versions: 14

Compression:

Stored size: 1.8 KB

Contents

# Copyright (c) 2020 Contrast Security, Inc. See https://www.contrastsecurity.com/enduser-terms-0317a for more details.
# frozen_string_literal: true

cs__scoped_require 'singleton'
cs__scoped_require 'contrast/utils/object_share'

module Contrast
  module Utils
    # Utility methods for building and caching hashes from strings
    class Sha256Builder
      include Singleton

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

      # 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.
      PATHS = '{lib,bin,ext}/**/*.{rb,c,h,c++,cpp,java,rs}'
      def files path
        if Dir.exist?(path)
          Dir.glob(File.join(path, PATHS))
        else
          []
        end
      end

      # Generate a SHA256 hash of the combined source code of this Gem
      def sha256 path
        return nil unless path
        return nil unless File.exist?(path) && !File.directory?(path)

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

      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

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

      def self.files path
        instance.files(path)
      end

      def self.sha256 path
        instance.sha256(path)
      end

      def self.build_from_spec spec
        instance.build_from_spec(spec)
      end
    end
  end
end

Version data entries

14 entries across 14 versions & 1 rubygems

Version Path
contrast-agent-3.13.2 lib/contrast/utils/sha256_builder.rb
contrast-agent-3.13.1 lib/contrast/utils/sha256_builder.rb
contrast-agent-3.13.0 lib/contrast/utils/sha256_builder.rb
contrast-agent-3.12.2 lib/contrast/utils/sha256_builder.rb
contrast-agent-3.12.1 lib/contrast/utils/sha256_builder.rb
contrast-agent-3.12.0 lib/contrast/utils/sha256_builder.rb
contrast-agent-3.11.0 lib/contrast/utils/sha256_builder.rb
contrast-agent-3.10.2 lib/contrast/utils/sha256_builder.rb
contrast-agent-3.10.1 lib/contrast/utils/sha256_builder.rb
contrast-agent-3.10.0 lib/contrast/utils/sha256_builder.rb
contrast-agent-3.9.1 lib/contrast/utils/sha256_builder.rb
contrast-agent-3.9.0 lib/contrast/utils/sha256_builder.rb
contrast-agent-3.8.5 lib/contrast/utils/sha256_builder.rb
contrast-agent-3.8.4 lib/contrast/utils/sha256_builder.rb