Module: Markdown::Merge

Defined in:
lib/markdown/merge.rb,
lib/markdown/merge/version.rb

Defined Under Namespace

Modules: Version

Constant Summary collapse

PACKAGE_NAME =
"markdown-merge"
BACKEND_REFERENCES =
{
  "kreuzberg-language-pack" => TreeHaver::KREUZBERG_LANGUAGE_PACK_BACKEND
}.freeze
VERSION =
Version::VERSION

Class Method Summary collapse

Class Method Details

.apply_markdown_delegated_child_outputs(source, delegated_operations, apply_plan, applied_children) ⇒ Object



173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
# File 'lib/markdown/merge.rb', line 173

def apply_markdown_delegated_child_outputs(source, delegated_operations, apply_plan, applied_children)
  lines = normalize_source(source).split("\n")
  ranges = markdown_fence_ranges(source)
  operations_by_id = delegated_operations.to_h { |operation| [operation[:operation_id], operation] }
  outputs_by_id = applied_children.to_h { |entry| [entry[:operation_id], entry[:output]] }

  replacements = apply_plan[:entries].filter_map do |entry|
    operation = operations_by_id[entry.dig(:delegated_group, :child_operation_id)]
    output = outputs_by_id[entry.dig(:delegated_group, :child_operation_id)]
    next if operation.nil? || output.nil?

    owner_path = operation.dig(:surface, :owner, :address)
    range = ranges[owner_path]
    return {
      ok: false,
      diagnostics: [{ severity: "error", category: "configuration_error", message: "missing fenced-code range for #{owner_path}" }],
      policies: []
    } if range.nil?

    { range: range, output: output }
  end

  replacements.sort_by { |entry| -entry[:range][:start] }.each do |entry|
    body_lines = entry[:output].empty? ? [] : entry[:output].sub(/\n\z/, "").split("\n")
    lines[entry[:range][:start] + 1...entry[:range][:end]] = body_lines
  end

  {
    ok: true,
    diagnostics: [],
    output: "#{lines.join("\n").sub(/\n+\z/, "")}\n",
    policies: []
  }
end

.available_markdown_backendsObject



20
21
22
# File 'lib/markdown/merge.rb', line 20

def available_markdown_backends
  BACKEND_REFERENCES.values
end

.code_fence_dialect(info_string, family) ⇒ Object



499
500
501
502
503
504
505
506
# File 'lib/markdown/merge.rb', line 499

def code_fence_dialect(info_string, family)
  case family
  when "typescript", "rust", "go", "yaml", "toml"
    family
  when "json"
    info_string.to_s.downcase == "jsonc" ? "jsonc" : "json"
  end
end

.code_fence_family(info_string) ⇒ Object



482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
# File 'lib/markdown/merge.rb', line 482

def code_fence_family(info_string)
  case info_string.to_s.downcase
  when "ts", "typescript"
    "typescript"
  when "rust", "rs"
    "rust"
  when "go"
    "go"
  when "json", "jsonc"
    "json"
  when "yaml", "yml"
    "yaml"
  when "toml"
    "toml"
  end
end

.collect_markdown_owners(source) ⇒ Object



330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
# File 'lib/markdown/merge.rb', line 330

def collect_markdown_owners(source)
  owners = []
  heading_index = 0
  code_fence_index = 0
  lines = source.split("\n")
  index = 0

  while index < lines.length
    line = lines[index]
    if (heading = line.match(/^(#+)\s+(.+?)\s*#*\s*$/)) && heading[1].length.between?(1, 6)
      level = heading[1].length
      owners << {
        path: "/heading/#{heading_index}",
        owner_kind: "heading",
        match_key: "h#{level}:#{slugify(heading[2])}",
        level: level
      }
      heading_index += 1
      index += 1
      next
    end

    if (fence = line.match(/^\s*(`{3,}|~{3,})\s*(.*?)\s*$/))
      marker = fence[1]
      marker_char = marker[0]
      marker_length = marker.length
      info_string = fence[2].strip.split(/\s+/).first.to_s
      owners << {
        path: "/code_fence/#{code_fence_index}",
        owner_kind: "code_fence",
        match_key: "fence:#{info_string.empty? ? "plain" : info_string}",
        **(info_string.empty? ? {} : { info_string: info_string })
      }
      code_fence_index += 1

      index += 1
      while index < lines.length
        trimmed = lines[index].strip
        break if trimmed.length >= marker_length &&
          trimmed.start_with?(marker_char * marker_length) &&
          trimmed.delete(marker_char).empty?

        index += 1
      end
      index += 1
      next
    end

    index += 1
  end

  owners
end

.collect_markdown_sections(source, owners) ⇒ Object



425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
# File 'lib/markdown/merge.rb', line 425

def collect_markdown_sections(source, owners)
  lines = normalize_source(source).split("\n")
  starts = markdown_owner_start_indices(source)
  ordered = owners.filter_map do |owner|
    start = starts[owner[:path]]
    next if start.nil?

    { owner: owner, start: start }
  end.sort_by { |entry| entry[:start] }

  ordered.each_with_index.map do |entry, index|
    finish = ordered[index + 1]&.dig(:start) || lines.length
    {
      path: entry.dig(:owner, :path),
      text: lines[entry[:start]...finish].join("\n").strip
    }
  end
end

.markdown_backend_feature_profile(backend: nil) ⇒ Object



24
25
26
27
28
29
30
31
32
# File 'lib/markdown/merge.rb', line 24

def markdown_backend_feature_profile(backend: nil)
  resolved_backend = resolve_backend(backend)
  return unsupported_feature_result("Unsupported Markdown backend #{resolved_backend}.") unless BACKEND_REFERENCES.key?(resolved_backend)

  markdown_feature_profile.merge(
    backend: resolved_backend,
    backend_ref: BACKEND_REFERENCES.fetch(resolved_backend).to_h
  )
end

.markdown_delegated_child_operations(analysis, parent_operation_id: "markdown-document-0") ⇒ Object



161
162
163
164
165
166
167
168
169
170
171
# File 'lib/markdown/merge.rb', line 161

def markdown_delegated_child_operations(analysis, parent_operation_id: "markdown-document-0")
  markdown_discovered_surfaces(analysis).each_with_index.map do |surface, index|
    Ast::Merge.delegated_child_operation(
      operation_id: "markdown-fence-#{index}",
      parent_operation_id: parent_operation_id,
      requested_strategy: "delegate_child_surface",
      language_chain: ["markdown", surface[:effective_language]],
      surface: surface
    )
  end
end

.markdown_discovered_surfaces(analysis) ⇒ Object



142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
# File 'lib/markdown/merge.rb', line 142

def markdown_discovered_surfaces(analysis)
  markdown_embedded_families(analysis).map do |candidate|
    Ast::Merge.discovered_surface(
      surface_kind: "markdown_fenced_code_block",
      declared_language: candidate[:language],
      effective_language: candidate[:dialect],
      address: "document[0] > fenced_code_block[#{candidate[:path]}]",
      parent_address: "document[0]",
      owner: Ast::Merge.surface_owner_ref(kind: "structural_owner", address: candidate[:path]),
      reconstruction_strategy: "portable_write",
      metadata: {
        family: candidate[:family],
        dialect: candidate[:dialect],
        path: candidate[:path]
      }
    )
  end
end

.markdown_embedded_families(analysis) ⇒ Object



124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
# File 'lib/markdown/merge.rb', line 124

def markdown_embedded_families(analysis)
  analysis[:owners].filter_map do |owner|
    next unless owner[:owner_kind] == "code_fence"
    next if owner[:info_string].to_s.empty?

    family = code_fence_family(owner[:info_string])
    dialect = code_fence_dialect(owner[:info_string], family)
    next unless family && dialect

    {
      path: owner[:path],
      language: owner[:info_string],
      family: family,
      dialect: dialect
    }
  end
end

.markdown_feature_profileObject



12
13
14
15
16
17
18
# File 'lib/markdown/merge.rb', line 12

def markdown_feature_profile
  {
    family: "markdown",
    supported_dialects: ["markdown"],
    supported_policies: []
  }
end

.markdown_fence_ranges(source) ⇒ Object



444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
# File 'lib/markdown/merge.rb', line 444

def markdown_fence_ranges(source)
  ranges = {}
  code_fence_index = 0
  lines = normalize_source(source).split("\n")
  index = 0

  while index < lines.length
    line = lines[index]
    if (fence = line.match(/^\s*(`{3,}|~{3,})\s*(.*?)\s*$/))
      marker = fence[1]
      marker_char = marker[0]
      marker_length = marker.length
      closing_index = index
      cursor = index + 1
      while cursor < lines.length
        trimmed = lines[cursor].strip
        if trimmed.length >= marker_length &&
            trimmed.start_with?(marker_char * marker_length) &&
            trimmed.delete(marker_char).empty?
          closing_index = cursor
          break
        end
        closing_index = cursor if cursor == lines.length - 1
        cursor += 1
      end

      ranges["/code_fence/#{code_fence_index}"] = { start: index, end: closing_index }
      code_fence_index += 1
      index = closing_index + 1
      next
    end

    index += 1
  end

  ranges
end

.markdown_owner_start_indices(source) ⇒ Object



384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
# File 'lib/markdown/merge.rb', line 384

def markdown_owner_start_indices(source)
  starts = {}
  lines = normalize_source(source).split("\n")
  heading_index = 0
  code_fence_index = 0
  index = 0

  while index < lines.length
    line = lines[index]
    if (heading = line.match(/^(#+)\s+(.+?)\s*#*\s*$/)) && heading[1].length.between?(1, 6)
      starts["/heading/#{heading_index}"] = index
      heading_index += 1
      index += 1
      next
    end

    if (fence = line.match(/^\s*(`{3,}|~{3,})\s*(.*?)\s*$/))
      starts["/code_fence/#{code_fence_index}"] = index
      code_fence_index += 1
      marker = fence[1]
      marker_char = marker[0]
      marker_length = marker.length
      index += 1
      while index < lines.length
        trimmed = lines[index].strip
        break if trimmed.length >= marker_length &&
          trimmed.start_with?(marker_char * marker_length) &&
          trimmed.delete(marker_char).empty?

        index += 1
      end
      index += 1
      next
    end

    index += 1
  end

  starts
end

.markdown_plan_context(backend: nil) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/markdown/merge.rb', line 34

def markdown_plan_context(backend: nil)
  profile = markdown_backend_feature_profile(backend: backend)
  return profile if profile[:ok] == false

  {
    family_profile: markdown_feature_profile,
    feature_profile: {
      backend: profile[:backend],
      supports_dialects: false,
      supported_policies: profile[:supported_policies]
    }
  }
end

.match_markdown_owners(template, destination) ⇒ Object



82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/markdown/merge.rb', line 82

def match_markdown_owners(template, destination)
  destination_paths = destination[:owners].to_h { |owner| [owner[:path], true] }
  template_paths = template[:owners].to_h { |owner| [owner[:path], true] }

  {
    matched: template[:owners]
      .filter { |owner| destination_paths[owner[:path]] }
      .map { |owner| { template_path: owner[:path], destination_path: owner[:path] } },
    unmatched_template: template[:owners].map { |owner| owner[:path] }.reject { |path| destination_paths[path] },
    unmatched_destination: destination[:owners].map { |owner| owner[:path] }.reject { |path| template_paths[path] }
  }
end

.merge_markdown(template_source, destination_source, dialect, backend: nil) ⇒ Object



95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
# File 'lib/markdown/merge.rb', line 95

def merge_markdown(template_source, destination_source, dialect, backend: nil)
  template = parse_markdown(template_source, dialect, backend: backend)
  return template unless template[:ok]

  destination = parse_markdown(destination_source, dialect, backend: backend)
  return destination unless destination[:ok]

  destination_sections = collect_markdown_sections(
    destination.dig(:analysis, :normalized_source),
    destination.dig(:analysis, :owners)
  )
  template_sections = collect_markdown_sections(
    template.dig(:analysis, :normalized_source),
    template.dig(:analysis, :owners)
  )
  destination_paths = destination_sections.to_h { |section| [section[:path], true] }
  merged_sections = destination_sections.map { |section| section[:text] }.reject(&:empty?) +
    template_sections
      .reject { |section| destination_paths[section[:path]] || section[:text].empty? }
      .map { |section| section[:text] }

  {
    ok: true,
    diagnostics: [],
    output: "#{merged_sections.join("\n\n").strip}\n",
    policies: []
  }
end

.merge_markdown_with_nested_outputs(template_source, destination_source, dialect, nested_outputs, backend: nil) ⇒ Object



208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
# File 'lib/markdown/merge.rb', line 208

def merge_markdown_with_nested_outputs(template_source, destination_source, dialect, nested_outputs, backend: nil)
  Ast::Merge.execute_nested_merge(
    nested_outputs,
    default_family: "markdown",
    request_id_prefix: "nested_markdown_child",
    merge_parent: -> { merge_markdown(template_source, destination_source, dialect, backend: backend) },
    discover_operations: lambda { |merged_output|
      analysis = parse_markdown(merged_output, dialect, backend: backend)
      next { ok: false, diagnostics: analysis[:diagnostics] || [] } unless analysis[:ok]

      {
        ok: true,
        diagnostics: [],
        operations: markdown_delegated_child_operations(analysis[:analysis])
      }
    },
    apply_resolved_outputs: lambda { |merged_output, operations, apply_plan, applied_children|
      apply_markdown_delegated_child_outputs(
        merged_output,
        operations,
        apply_plan,
        applied_children
      )
    }
  )
end

.merge_markdown_with_reviewed_nested_outputs(template_source, destination_source, dialect, review_state, applied_children, backend: nil) ⇒ Object



235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
# File 'lib/markdown/merge.rb', line 235

def merge_markdown_with_reviewed_nested_outputs(template_source, destination_source, dialect, review_state, applied_children, backend: nil)
  Ast::Merge.execute_reviewed_nested_merge(
    review_state,
    "markdown",
    applied_children,
    merge_parent: -> { merge_markdown(template_source, destination_source, dialect, backend: backend) },
    discover_operations: lambda { |merged_output|
      analysis = parse_markdown(merged_output, dialect, backend: backend)
      next({ ok: false, diagnostics: analysis[:diagnostics] || [] }) unless analysis[:ok]

      {
        ok: true,
        diagnostics: [],
        operations: markdown_delegated_child_operations(analysis[:analysis])
      }
    },
    apply_resolved_outputs: lambda { |merged_output, operations, apply_plan, resolved_children|
      apply_markdown_delegated_child_outputs(
        merged_output,
        operations,
        apply_plan,
        resolved_children
      )
    }
  )
end

.merge_markdown_with_reviewed_nested_outputs_from_replay_bundle(template_source, destination_source, dialect, replay_bundle, backend: nil) ⇒ Object



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

def merge_markdown_with_reviewed_nested_outputs_from_replay_bundle(template_source, destination_source, dialect, replay_bundle, backend: nil)
  execution = Array(replay_bundle[:reviewed_nested_executions]).find { |entry| entry[:family] == "markdown" }
  return { ok: false, diagnostics: [{ severity: "error", category: "configuration_error", message: "review replay bundle does not include a reviewed nested execution for markdown." }], policies: [] } unless execution

  merge_markdown_with_reviewed_nested_outputs(
    template_source,
    destination_source,
    dialect,
    execution[:review_state],
    execution[:applied_children],
    backend: backend
  )
end

.merge_markdown_with_reviewed_nested_outputs_from_replay_bundle_envelope(template_source, destination_source, dialect, envelope, backend: nil) ⇒ Object



290
291
292
293
294
295
296
297
298
299
300
301
# File 'lib/markdown/merge.rb', line 290

def merge_markdown_with_reviewed_nested_outputs_from_replay_bundle_envelope(template_source, destination_source, dialect, envelope, backend: nil)
  replay_bundle, import_error = Ast::Merge.import_review_replay_bundle_envelope(envelope)
  return { ok: false, diagnostics: [{ severity: "error", category: import_error[:category], message: import_error[:message] }], policies: [] } if import_error

  merge_markdown_with_reviewed_nested_outputs_from_replay_bundle(
    template_source,
    destination_source,
    dialect,
    replay_bundle,
    backend: backend
  )
end

.merge_markdown_with_reviewed_nested_outputs_from_review_state(template_source, destination_source, dialect, review_state, backend: nil) ⇒ Object



276
277
278
279
280
281
282
283
284
285
286
287
288
# File 'lib/markdown/merge.rb', line 276

def merge_markdown_with_reviewed_nested_outputs_from_review_state(template_source, destination_source, dialect, review_state, backend: nil)
  execution = Array(review_state[:reviewed_nested_executions]).find { |entry| entry[:family] == "markdown" }
  return { ok: false, diagnostics: [{ severity: "error", category: "configuration_error", message: "review state does not include a reviewed nested execution for markdown." }], policies: [] } unless execution

  merge_markdown_with_reviewed_nested_outputs(
    template_source,
    destination_source,
    dialect,
    execution[:review_state],
    execution[:applied_children],
    backend: backend
  )
end

.merge_markdown_with_reviewed_nested_outputs_from_review_state_envelope(template_source, destination_source, dialect, envelope, backend: nil) ⇒ Object



303
304
305
306
307
308
309
310
311
312
313
314
# File 'lib/markdown/merge.rb', line 303

def merge_markdown_with_reviewed_nested_outputs_from_review_state_envelope(template_source, destination_source, dialect, envelope, backend: nil)
  review_state, import_error = Ast::Merge.import_conformance_manifest_review_state_envelope(envelope)
  return { ok: false, diagnostics: [{ severity: "error", category: import_error[:category], message: import_error[:message] }], policies: [] } if import_error

  merge_markdown_with_reviewed_nested_outputs_from_review_state(
    template_source,
    destination_source,
    dialect,
    review_state,
    backend: backend
  )
end

.normalize_source(source) ⇒ Object



316
317
318
# File 'lib/markdown/merge.rb', line 316

def normalize_source(source)
  source.gsub(/\r\n?/, "\n")
end

.parse_markdown(source, dialect, backend: nil) ⇒ Object



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
# File 'lib/markdown/merge.rb', line 48

def parse_markdown(source, dialect, backend: nil)
  return unsupported_feature_result("Unsupported Markdown dialect #{dialect}.") unless dialect == "markdown"

  resolved_backend = resolve_backend(backend)
  unless resolved_backend == "kreuzberg-language-pack"
    return unsupported_feature_result("Unsupported Markdown backend #{resolved_backend}.")
  end

  syntax = TreeHaver.parse_with_language_pack(
    TreeHaver::ParserRequest.new(source: source, language: "markdown", dialect: dialect)
  )
  return { ok: false, diagnostics: syntax[:diagnostics], policies: [] } unless syntax[:ok]

  normalized_source = normalize_source(source)
  {
    ok: true,
    diagnostics: [],
    analysis: {
      kind: "markdown",
      dialect: dialect,
      normalized_source: normalized_source,
      root_kind: "document",
      owners: collect_markdown_owners(normalized_source)
    },
    policies: []
  }
rescue StandardError => e
  {
    ok: false,
    diagnostics: [{ severity: "error", category: "parse_error", message: e.message }],
    policies: []
  }
end

.resolve_backend(backend) ⇒ Object



508
509
510
# File 'lib/markdown/merge.rb', line 508

def resolve_backend(backend)
  backend.to_s.empty? ? "kreuzberg-language-pack" : backend.to_s
end

.slugify(value) ⇒ Object



320
321
322
323
324
325
326
327
328
# File 'lib/markdown/merge.rb', line 320

def slugify(value)
  slug = value
    .strip
    .downcase
    .gsub(/[`*_~\[\]()<>]/, "")
    .gsub(/[^a-z0-9]+/, "-")
    .gsub(/\A-+|-+\z/, "")
  slug.empty? ? "section" : slug
end

.unsupported_feature_result(message) ⇒ Object



512
513
514
515
516
517
518
# File 'lib/markdown/merge.rb', line 512

def unsupported_feature_result(message)
  {
    ok: false,
    diagnostics: [{ severity: "error", category: "unsupported_feature", message: message }],
    policies: []
  }
end