# Copyright (c) 2020 Jerome Arbez-Gindre # frozen_string_literal: true require 'digest' # Contains the content of a Defmastership definition module Defmastership BUILD_FROM_MATCH = { type: ->(match) { match[:type] }, reference: ->(match) { match[:reference] }, lines: ->(_) { [] }, labels: lambda do |match| labels = Set.new labels.merge(match[:labels].split(/\s*,\s*/).to_set) if match[:labels] labels end, eref: ->(_) { Hash.new([]) }, iref: ->(_) { [] }, attributes: ->(_) { {} }, explicit_checksum: ->(match) { match[:explicit_checksum] }, explicit_version: ->(match) { match[:explicit_version] } }.freeze private_constant :BUILD_FROM_MATCH # Class to host data of Definition class DefinitionData = Struct.new( :type, :reference, :lines, :labels, :eref, :iref, :attributes, :explicit_checksum, :explicit_version ) private_constant :DefinitionData # Defmastership definition: contains all data of a definition class Definition extend Forwardable def_delegators :@data, :type, :reference, :lines, :labels, :eref, :iref, :attributes, :explicit_checksum, :explicit_version # @param match [MatchData] the definition data from regepx match def initialize(match) @data = DefinitionData.new( *BUILD_FROM_MATCH.transform_values { |lamb| lamb.call(match) } .fetch_values(*DefinitionData.members) ) end # Add a line to the definition's value # # @param new_line [String] the new line # @return [Definition] the definition itself def <<(new_line) lines << new_line self end # Add a line to the definition's value # # @return [String] the complete value of the definition def value lines.join("\n") end # @return [String] short representation (8 last characters) of the sha256 of the definition's value def sha256_short "~#{Digest::SHA2.hexdigest(value).chars.last(8).join}" end # @return [String] the explicit checsum if wrong or nil def wrong_explicit_checksum explicit_checksum unless explicit_checksum.eql?(sha256_short) end # Set an external ref list for a given reference type # # @param ref [String] the type of cross reference # @param extrefs [String] the comma separated external references def add_eref(ref, extrefs) eref[ref] = extrefs.strip.split(/\s*,\s*/) end # Set an internal ref # # @param ref [String] the internal reference def add_iref(ref) iref << ref end # Set an attribute for a given key # # @param key [String] the attribute's key # @param value [String] the attribute's value def set_attribute(key, value) attributes[key] = value end end end