Sha256: 1c1fb7a8a88eb01df0f510b0579d86edb7c503eb95bb7a72f055c9664aa3a7b5

Contents?: true

Size: 1.9 KB

Versions: 5

Compression:

Stored size: 1.9 KB

Contents

module Metanorma
  module Utils
    class Log
      def initialize
        @log = {}
      end

      def add(category, loc, msg)
        return if @novalid

        @log[category] = [] unless @log[category]
        @log[category] << { location: current_location(loc), message: msg,
                            context: context(loc) }
        loc = loc.nil? ? "" : "(#{current_location(loc)}): "
        warn "#{category}: #{loc}#{msg}"
      end

      def current_location(node)
        if node.nil? then ""
        elsif node.is_a? String then node
        elsif node.respond_to?(:lineno) && !node.lineno.nil? &&
            !node.lineno.empty?
          "Asciidoctor Line #{'%06d' % node.lineno}"
        elsif node.respond_to?(:line) && !node.line.nil?
          "XML Line #{'%06d' % node.line}"
        elsif node.respond_to?(:id) && !node.id.nil? then "ID #{node.id}"
        else
          while !node.nil? &&
              (!node.respond_to?(:level) || node.level.positive?) &&
              (!node.respond_to?(:context) || node.context != :section)
            node = node.parent
            return "Section: #{node.title}" if node&.respond_to?(:context) &&
              node&.context == :section
          end
          "??"
        end
      end

      def context(node)
        return nil if node.is_a? String

        node.respond_to?(:to_xml) and return node.to_xml
        node.respond_to?(:to_s) and return node.to_s
        nil
      end

      def write(file)
        File.open(file, "w:UTF-8") do |f|
          f.puts "#{file} errors"
          @log.each_key do |key|
            f.puts "\n\n== #{key}\n\n"
            @log[key].sort_by { |a| a[:location] }.each do |n|
              loc = n[:location] ? "(#{n[:location]}): " : ""
              f.puts "#{loc}#{n[:message]}"
              n[:context]&.split(/\n/)&.first(5)&.each { |l| f.puts "\t#{l}" }
            end
          end
        end
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
metanorma-utils-1.2.7 lib/utils/log.rb
metanorma-utils-1.2.6 lib/utils/log.rb
metanorma-utils-1.2.5 lib/utils/log.rb
metanorma-utils-1.2.4 lib/utils/log.rb
metanorma-utils-1.2.3 lib/utils/log.rb