Module: Edoxen::SchemaValidator::LineMap

Defined in:
lib/edoxen/schema_validator.rb

Overview

Builds a => line_no map for a YAML source. The path is the JSON-Schema-style pointer: "/metadata", "/resolutions/0/title", etc. This is a tag-class is allocated freely — no instance_variable_set ever crosses another object's boundary.

Class Method Summary collapse

Class Method Details

.build(content) ⇒ Hash{String => Integer}

Returns:

  • (Hash{String => Integer})


136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
# File 'lib/edoxen/schema_validator.rb', line 136

def build(content)
  map = {}
  stack = []
  array_counter = Hash.new(-1)
  array_path_for = {}

  content.each_line.with_index(1) do |raw, line_no|
    line = raw.chomp
    stripped = line.strip
    next if stripped.empty? || stripped.start_with?("#") || stripped == "---"

    indent = line.index(/\S/) || 0
    level = indent / 2
    stack = stack.first(level)

    if stripped.start_with?("- ")
      parent = stack.empty? ? "" : "/#{stack.join("/")}"
      parent_key = parent.empty? ? parent : parent.dup
      array_counter[parent_key] = -1 unless array_counter.key?(parent_key)
      array_counter[parent_key] += 1
      array_index = array_counter[parent_key]
      array_path = "#{parent}/#{array_index}"
      map[array_path] = line_no

      remainder = stripped[2..].to_s.strip
      if remainder.match(/\A(.+?):(\s|$)/)
        key = Regexp.last_match(1).strip.gsub(/["']/, "")
        map["#{array_path}/#{key}"] = line_no
        stack = stack.first(level) + [array_index.to_s, key]
      else
        stack = stack.first(level) + [array_index.to_s]
      end
    elsif (md = stripped.match(/\A(.+?):(\s|$)/))
      key = md[1].strip.gsub(/["']/, "")
      stack = stack.first(level) + [key]
      full = "/#{stack.join("/")}"
      map[full] = line_no
      array_counter.delete_if { |p, _| p.start_with?(full) }
    end
  end
  map
end

.locate(pointer, line_map) ⇒ Array(Integer, Integer)

Returns [line, column] for the given JSON-Schema data pointer. Picks the longest prefix in the line map — pure longest-match, no knowledge of specific path shapes.

Returns:

  • (Array(Integer, Integer))

    [line, column] for the given JSON-Schema data pointer. Picks the longest prefix in the line map — pure longest-match, no knowledge of specific path shapes.



182
183
184
185
186
187
188
189
190
191
# File 'lib/edoxen/schema_validator.rb', line 182

def locate(pointer, line_map)
  pointer = pointer.to_s
  return [1, 1] if pointer.empty?

  match_key = line_map.keys
                      .select { |path| pointer.start_with?(path) || path.start_with?(pointer) }
                      .max_by(&:length)

  match_key ? [line_map[match_key], 1] : [1, 1]
end