Class: Metanorma::Utils::Log

Inherits:
Object
  • Object
show all
Defined in:
lib/utils/log.rb

Instance Method Summary collapse

Constructor Details

#initializeLog

Returns a new instance of Log.



4
5
6
# File 'lib/utils/log.rb', line 4

def initialize
  @log = {}
end

Instance Method Details

#add(category, loc, msg) ⇒ Object



8
9
10
11
12
13
14
15
16
# File 'lib/utils/log.rb', line 8

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

#context(node) ⇒ Object



39
40
41
42
43
44
45
# File 'lib/utils/log.rb', line 39

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

#current_location(node) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/utils/log.rb', line 18

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

#write(file) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
# File 'lib/utils/log.rb', line 47

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|
        write1(f, n)
      end
    end
  end
end

#write1(file, entry) ⇒ Object



59
60
61
62
63
64
65
66
# File 'lib/utils/log.rb', line 59

def write1(file, entry)
  loc = entry[:location] ? "(#{entry[:location]}): " : ""
  file.puts "#{loc}#{entry[:message]}"
    .encode("UTF-8", invalid: :replace, undef: :replace)
  entry[:context]&.split(/\n/)&.first(5)&.each do |l|
    file.puts "\t#{l}"
  end
end