Module: MarkdownComposer::Where

Defined in:
lib/markdown_composer/where.rb

Constant Summary collapse

GROUP_KEYS =
%w[all any none not xor].freeze
FIELD_TAKE_FIELDS =
%w[title text source_text].freeze

Class Method Summary collapse

Class Method Details

.apply_field_take(actual, take) ⇒ Object



245
246
247
# File 'lib/markdown_composer/where.rb', line 245

def apply_field_take(actual, take)
  Take.apply(field_tokens(actual), take).join(" ")
end

.cast(value) ⇒ Object



305
306
307
308
309
310
311
# File 'lib/markdown_composer/where.rb', line 305

def cast(value)
  return true if value == "true"
  return false if value == "false"
  return Take.integer(value) if value.to_s.match?(/\A-?\d+\z|last/)

  value
end

.compare(actual, operator, value, condition, options:) ⇒ Object



196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
# File 'lib/markdown_composer/where.rb', line 196

def compare(actual, operator, value, condition, options:)
  case operator
  when "contains"
    actual.to_s.include?(value.to_s)
  when "starts_with"
    actual.to_s.start_with?(value.to_s)
  when "ends_with"
    actual.to_s.end_with?(value.to_s)
  when "equals"
    actual.to_s.downcase == value.to_s.downcase
  when "range"
    from = condition["from"].to_i
    to = condition["to"].to_i
    actual.to_i >= from && actual.to_i <= (to.negative? ? Float::INFINITY : to)
  when "exists"
    actual.respond_to?(:any?) ? actual.any? : !!actual
  when "min"
    actual.to_i >= value.to_i
  when "max"
    actual.to_i <= value.to_i
  when "matches"
    Regexp.new(value.to_s).match?(actual.to_s)
  else
    false
  end
rescue RegexpError
  false
end

.field_tokens(actual) ⇒ Object



249
250
251
# File 'lib/markdown_composer/where.rb', line 249

def field_tokens(actual)
  actual.to_s.scan(/\S+/)
end

.field_value(unit, field, position:, total:) ⇒ Object



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
178
179
180
181
182
183
184
185
186
187
188
# File 'lib/markdown_composer/where.rb', line 153

def field_value(unit, field, position:, total:)
  case field
  when "title"
    unit.respond_to?(:title_text) ? unit.title_text : unit.text
  when "text"
    unit.respond_to?(:text) ? unit.text : unit.title_text
  when "source_text"
    unit.respond_to?(:raw) ? unit.raw : field_value(unit, "text", position: position, total: total)
  when "position"
    position
  when "language"
    unit.respond_to?(:attributes) ? unit.attributes["language"] : nil
  when "diagram_type"
    unit.respond_to?(:attributes) ? unit.attributes["diagram_type"] : nil
  when "format"
    unit.respond_to?(:attributes) ? unit.attributes["format"] : nil
  when "location"
    unit.respond_to?(:attributes) ? unit.attributes["location"] : nil
  when "links"
    nested_nodes(unit).any? { |node| node.type == "link" }
  when "images"
    nested_nodes(unit).any? { |node| node.type == "image" }
  when "code"
    nested_nodes(unit).any? { |node| node.type == "code_block" }
  when "numbers"
    (unit.respond_to?(:text) ? unit.text : unit.title_text).to_s.match?(/\d/)
  when "empty"
    (unit.respond_to?(:text) ? unit.text : unit.title_text).to_s.strip.empty?
  when "length"
    (unit.respond_to?(:text) ? unit.text : unit.title_text).to_s.length
  when "word_count"
    (unit.respond_to?(:text) ? unit.text : unit.title_text).to_s.scan(/\w+/).length
  when "child"
    unit.respond_to?(:child_sections) ? unit.child_sections : []
  end
end

.match?(unit, condition, position:, total:, options: {}) ⇒ Boolean

Returns:

  • (Boolean)


100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/markdown_composer/where.rb', line 100

def match?(unit, condition, position:, total:, options: {})
  return true if condition.nil? || condition == {}

  condition = normalize(condition)
  if condition.is_a?(Hash)
    group_key = GROUP_KEYS.find { |key| condition.key?(key) }
    return match_group?(group_key, condition[group_key], unit, position: position, total: total, options: options) if group_key
  end

  field = condition["field"].to_s
  operator = condition["operator"].to_s
  value = condition["value"]
  actual = field_value(unit, field, position: position, total: total)
  actual = apply_field_take(actual, condition["field_take"]) if condition["field_take"]
  compare(actual, operator, value, condition, options: options)
end

.match_group?(group_key, children, unit, position:, total:, options:) ⇒ Boolean

Returns:

  • (Boolean)


225
226
227
228
229
230
231
232
233
234
235
236
# File 'lib/markdown_composer/where.rb', line 225

def match_group?(group_key, children, unit, position:, total:, options:)
  children = group_key == "not" ? [ children ] : Array(children)
  results = children.map { |child| match?(unit, child, position: position, total: total, options: options) }
  case group_key
  when "all" then results.all?
  when "any" then results.any?
  when "none" then results.none?
  when "not" then !results.first
  when "xor" then results.count(true) == 1
  else false
  end
end

.nested_nodes(unit) ⇒ Object



238
239
240
241
242
243
# File 'lib/markdown_composer/where.rb', line 238

def nested_nodes(unit)
  return [ unit, *unit.children ].compact if unit.respond_to?(:children)
  return [ unit ] unless unit.respond_to?(:all_nodes)

  [ unit.heading_node, *unit.body_nodes, *unit.all_nodes ].compact
end

.normalize(value) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/markdown_composer/where.rb', line 10

def normalize(value)
  return parse(value) if value.is_a?(String)
  return nil if value.nil?

  case value
  when Hash
    hash = value.transform_keys(&:to_s)
    group_key = GROUP_KEYS.find { |key| hash.key?(key) }
    if group_key
      children = hash[group_key]
      return { group_key => Array(children).map { |child| normalize(child) } } unless group_key == "not"

      return { "not" => normalize(children) }
    end
    hash
  else
    value
  end
end

.parse(text) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# File 'lib/markdown_composer/where.rb', line 30

def parse(text)
  text = text.to_s.strip
  group = GROUP_KEYS.find { |key| text.start_with?("#{key}(") && text.end_with?(")") }
  if group
    inner = text[(group.length + 1)..-2]
    children = split_top_level(inner, ";").map { |part| parse(part) }
    return group == "not" ? { "not" => children.first } : { group => children }
  end

  field_expression, rest = split_field_and_rest(text)
  if field_expression && (predicate_match = rest&.match(/\A([a-z_]+)\((.*)\)\z/))
    field, field_take = parse_field_expression(field_expression)
    condition = {
      "field" => field,
      "operator" => predicate_match[1].strip,
      "value" => unquote(predicate_match[2].strip)
    }
    condition["field_take"] = field_take if field_take
    return condition
  end

  if field_expression && rest
    field, field_take = parse_field_expression(field_expression)
    if rest.match?(/\A[a-z_]+\(/)
      condition = {
        "field" => field,
        "operator" => "__malformed_predicate__",
        "value" => rest.strip
      }
      condition["field_take"] = field_take if field_take
      return condition
    end

    value = unquote(rest.strip)
    if field == "position" && value.include?("..")
      from, to = value.split("..", 2)
      condition = { "field" => field, "operator" => "range", "from" => Take.integer(from), "to" => Take.integer(to) }
      condition["field_take"] = field_take if field_take
      return condition
    end

    operator = %w[exists true false].include?(value) ? value : "equals"
    condition = { "field" => field, "operator" => operator == "exists" ? "exists" : "equals", "value" => cast(value) }
    condition["field_take"] = field_take if field_take
    return condition
  end

  if text =~ /\A([^:]+):([a-z_]+)\((.*)\)\z/
    return {
      "field" => Regexp.last_match(1).strip,
      "operator" => Regexp.last_match(2).strip,
      "value" => unquote(Regexp.last_match(3).strip)
    }
  end

  if text =~ /\A([^:]+):(.+)\z/
    field = Regexp.last_match(1).strip
    value = unquote(Regexp.last_match(2).strip)
    if field == "position" && value.include?("..")
      from, to = value.split("..", 2)
      return { "field" => field, "operator" => "range", "from" => Take.integer(from), "to" => Take.integer(to) }
    end

    operator = %w[exists true false].include?(value) ? value : "equals"
    return { "field" => field, "operator" => operator == "exists" ? "exists" : "equals", "value" => cast(value) }
  end

  { "field" => "text", "operator" => "contains", "value" => text }
end

.parse_field_expression(expression) ⇒ Object



253
254
255
256
257
258
259
# File 'lib/markdown_composer/where.rb', line 253

def parse_field_expression(expression)
  if expression =~ /\A([a-z_]+)\[(.+)\]\z/
    return [ Regexp.last_match(1), Take.parse(Regexp.last_match(2)) ]
  end

  [ expression.strip, nil ]
end

.split_field_and_rest(text) ⇒ Object



261
262
263
264
265
266
267
268
269
270
271
272
273
274
# File 'lib/markdown_composer/where.rb', line 261

def split_field_and_rest(text)
  depth = 0
  quote = nil
  text.each_char.with_index do |char, index|
    quote = quote == char ? nil : char if %w[" '].include?(char)
    if quote.nil?
      depth += 1 if char == "["
      depth -= 1 if char == "]"
    end
    return [ text[0...index].strip, text[(index + 1)..].strip ] if char == ":" && depth.zero? && quote.nil?
  end

  [ nil, nil ]
end

.split_top_level(text, delimiter) ⇒ Object



276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
# File 'lib/markdown_composer/where.rb', line 276

def split_top_level(text, delimiter)
  depth = 0
  bracket_depth = 0
  quote = nil
  current = +""
  parts = []
  text.each_char do |char|
    quote = quote == char ? nil : char if %w[" '].include?(char)
    if quote.nil?
      depth += 1 if char == "("
      depth -= 1 if char == ")"
      bracket_depth += 1 if char == "["
      bracket_depth -= 1 if char == "]"
    end
    if char == delimiter && depth.zero? && bracket_depth.zero? && quote.nil?
      parts << current.strip
      current = +""
    else
      current << char
    end
  end
  parts << current.strip unless current.strip.empty?
  parts
end

.unquote(value) ⇒ Object



301
302
303
# File 'lib/markdown_composer/where.rb', line 301

def unquote(value)
  value.sub(/\A["']/, "").sub(/["']\z/, "")
end

.validate(condition, diagnostics:, path:, options: {}) ⇒ Object



117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
# File 'lib/markdown_composer/where.rb', line 117

def validate(condition, diagnostics:, path:, options: {})
  condition = normalize(condition)
  return if condition.nil?

  if condition.is_a?(Hash)
    group_key = GROUP_KEYS.find { |key| condition.key?(key) }
    if group_key
      if group_key == "not"
        validate(condition[group_key], diagnostics: diagnostics, path: "#{path}.not", options: options)
        return
      end

      Array(condition[group_key]).each_with_index { |child, index| validate(child, diagnostics: diagnostics, path: "#{path}.#{group_key}[#{index}]", options: options) }
      return
    end
  end

  field = condition["field"].to_s
  operator = condition["operator"].to_s
  if operator == "__malformed_predicate__"
    diagnostics.error("where.predicate_malformed", "Malformed condition for #{field}: #{condition["value"]}", path: path)
    return
  end

  registry = Registries.default.where
  field_entry = registry.fields[field]
  diagnostics.error("where.field_unknown", "Unknown condition field #{field.inspect}", path: path) unless field_entry
  diagnostics.error("where.operator_unknown", "Unknown predicate #{operator.inspect}", path: path) unless registry.predicate?(operator) && registry.predicates_for(field).include?(operator)
  if condition["field_take"]
    diagnostics.error("where.field_take_unsupported", "#{field} does not support bracketed where take", path: path) unless field_entry&.field_take
    Take.validate(condition["field_take"]).each { |message| diagnostics.error("where.field_take_invalid", message, path: path) }
  end
  validate_regex(condition["value"], diagnostics: diagnostics, path: path) if operator == "matches"
  diagnostics.error("where.position_zero", "position:0 is invalid", path: path) if field == "position" && condition["value"].to_i.zero? && condition["operator"] == "equals"
end

.validate_regex(value, diagnostics:, path:) ⇒ Object



190
191
192
193
194
# File 'lib/markdown_composer/where.rb', line 190

def validate_regex(value, diagnostics:, path:)
  Regexp.new(value.to_s)
rescue RegexpError => e
  diagnostics.error("where.regex_invalid", "Invalid regular expression: #{e.message}", path: path)
end