Module: Markdown::Merge

Defined in:
lib/markdown/merge.rb,
lib/markdown/merge/cleanse.rb,
lib/markdown/merge/version.rb,
lib/markdown/merge/freeze_node.rb,
lib/markdown/merge/link_parser.rb,
lib/markdown/merge/list_merger.rb,
lib/markdown/merge/debug_logger.rb,
lib/markdown/merge/file_aligner.rb,
lib/markdown/merge/merge_result.rb,
lib/markdown/merge/smart_merger.rb,
lib/markdown/merge/file_analysis.rb,
lib/markdown/merge/gap_line_node.rb,
lib/markdown/merge/output_builder.rb,
lib/markdown/merge/backend_support.rb,
lib/markdown/merge/comment_tracker.rb,
lib/markdown/merge/wrapper_support.rb,
lib/markdown/merge/code_block_merger.rb,
lib/markdown/merge/conflict_resolver.rb,
lib/markdown/merge/document_problems.rb,
lib/markdown/merge/smart_merger_base.rb,
lib/markdown/merge/file_analysis_base.rb,
lib/markdown/merge/list_match_refiner.rb,
lib/markdown/merge/markdown_structure.rb,
lib/markdown/merge/table_match_refiner.rb,
lib/markdown/merge/link_definition_node.rb,
lib/markdown/merge/node_type_normalizer.rb,
lib/markdown/merge/preservation_support.rb,
lib/markdown/merge/cleanse/block_spacing.rb,
lib/markdown/merge/table_match_algorithm.rb,
lib/markdown/merge/whitespace_normalizer.rb,
lib/markdown/merge/partial_template_merger.rb,
lib/markdown/merge/code_block_match_refiner.rb,
lib/markdown/merge/link_definition_formatter.rb,
lib/markdown/merge/link_reference_rehydrator.rb,
lib/markdown/merge/cleanse/code_fence_spacing.rb,
lib/markdown/merge/source_preserving_provider.rb,
lib/markdown/merge/cleanse/condensed_link_refs.rb,
lib/markdown/merge/cleanse/templating_corruption.rb,
lib/markdown/merge/cleanse/list_marker_duplication.rb,
sig/markdown/merge.rbs

Defined Under Namespace

Modules: BackendSupport, Cleanse, DebugLogger, LinkDefinitionFormatter, MarkdownStructure, NodeTypeNormalizer, PreservationSupport, Version, WrapperSupport Classes: CodeBlockMatchRefiner, CodeBlockMerger, CommentTracker, ConflictResolver, CorruptionDetectedError, DestinationParseError, DocumentProblems, Error, FileAligner, FileAnalysis, FileAnalysisBase, FreezeNode, GapLineNode, LinkDefinitionNode, LinkParser, LinkReferenceRehydrator, ListMatchRefiner, ListMerger, MergeResult, OutputBuilder, ParseError, PartialTemplateMerger, Provider, ProviderBackend, SmartMerger, SmartMergerBase, SourcePreservingProvider, TableMatchAlgorithm, TableMatchRefiner, TemplateParseError, WhitespaceNormalizer

Constant Summary collapse

PACKAGE_NAME =
'markdown-merge'
BACKEND_REFERENCES =
{
  'kreuzberg-language-pack' => TreeHaver::KREUZBERG_LANGUAGE_PACK_BACKEND,
  'commonmarker' => TreeHaver::BackendReference.new(id: 'commonmarker', family: 'native').freeze,
  'markly' => TreeHaver::BackendReference.new(id: 'markly', family: 'native').freeze,
  'kramdown' => TreeHaver::BackendReference.new(id: 'kramdown', family: 'native').freeze
}.freeze
BACKEND_REGISTRY =
Struct.new(:registered, :mutex).new(false, Mutex.new)
VERSION =

Current gem version exposed at the traditional constant location.

Returns:

  • (String)
Version::VERSION
NodeTypingNormalizer =

Alias for the shared normalizer module from ast-merge

Ast::Merge::NodeTyping::Normalizer

Class Method Summary collapse

Class Method Details

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



274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
# File 'lib/markdown/merge.rb', line 274

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]
    if range.nil?
      return {
        ok: false,
        diagnostics: [{ severity: 'error', category: 'configuration_error',
                        message: "missing fenced-code range for #{owner_path}" }],
        policies: []
      }
    end

    { 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



121
122
123
124
125
# File 'lib/markdown/merge.rb', line 121

def available_markdown_backends
  BACKEND_REFERENCES.filter_map do |backend_id, reference|
    reference if markdown_backend_available_for_analysis?(backend_id)
  end
end

.code_fence_dialect(info_string, family) ⇒ Object



620
621
622
623
624
625
626
627
# File 'lib/markdown/merge.rb', line 620

def code_fence_dialect(info_string, family)
  case family
  when 'typescript', 'rust', 'go', 'yaml', 'toml'
    family
  when 'json'
    %w[json jsonc json5].include?(info_string.to_s.downcase) ? info_string.to_s.downcase : 'json'
  end
end

.code_fence_family(info_string) ⇒ Object



603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
# File 'lib/markdown/merge.rb', line 603

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', 'json5'
    'json'
  when 'yaml', 'yml'
    'yaml'
  when 'toml'
    'toml'
  end
end

.collect_markdown_owners(source) ⇒ Object



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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
# File 'lib/markdown/merge.rb', line 451

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



546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
# File 'lib/markdown/merge.rb', line 546

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

.collect_parse_errors(node) ⇒ Object

Raises:

  • (TreeHaver::NotAvailable)


654
655
656
657
658
659
660
# File 'lib/markdown/merge.rb', line 654

def collect_parse_errors(node)
  raise TreeHaver::NotAvailable, 'Markdown parse returned no root node' unless node
  return unless node.respond_to?(:has_error?) && node.has_error?

  raise TreeHaver::NotAvailable,
        'Markdown parse contains syntax errors'
end

.markdown_backend_available_for_analysis?(backend_id) ⇒ Boolean

Returns:

  • (Boolean)


639
640
641
642
643
644
645
646
647
648
649
650
651
652
# File 'lib/markdown/merge.rb', line 639

def markdown_backend_available_for_analysis?(backend_id)
  register_backend!
  registrations = TreeHaver.registered_languages(:markdown)
  case backend_id.to_s
  when 'commonmarker', 'markly', 'kramdown'
    registrations.dig(backend_id.to_sym, :backend_module)&.then do |backend_module|
      !backend_module.respond_to?(:available?) || backend_module.available?
    end
  when 'kreuzberg-language-pack'
    registrations.key?(:tree_sitter) || registrations.key?(:tslp)
  else
    false
  end
end

.markdown_backend_feature_profile(backend: nil) ⇒ Object



127
128
129
130
131
132
133
134
135
136
137
# File 'lib/markdown/merge.rb', line 127

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

  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



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

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



243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
# File 'lib/markdown/merge.rb', line 243

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



225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
# File 'lib/markdown/merge.rb', line 225

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



113
114
115
116
117
118
119
# File 'lib/markdown/merge.rb', line 113

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

.markdown_fence_ranges(source) ⇒ Object



565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
# File 'lib/markdown/merge.rb', line 565

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



505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
# File 'lib/markdown/merge.rb', line 505

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



139
140
141
142
143
144
145
146
147
148
149
150
151
# File 'lib/markdown/merge.rb', line 139

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



183
184
185
186
187
188
189
190
191
192
193
194
# File 'lib/markdown/merge.rb', line 183

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



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/merge.rb', line 196

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



312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
# File 'lib/markdown/merge.rb', line 312

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



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

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



367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
# File 'lib/markdown/merge.rb', line 367

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' }
  unless execution
    return { ok: false,
             diagnostics: [{ severity: 'error', category: 'configuration_error', message: 'review replay bundle does not include a reviewed nested execution for markdown.' }], policies: [] }
  end

  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



403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
# File 'lib/markdown/merge.rb', line 403

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)
  if import_error
    return { ok: false,
             diagnostics: [{ severity: 'error', category: import_error[:category], message: import_error[:message] }], policies: [] }
  end

  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



385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
# File 'lib/markdown/merge.rb', line 385

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' }
  unless execution
    return { ok: false,
             diagnostics: [{ severity: 'error', category: 'configuration_error', message: 'review state does not include a reviewed nested execution for markdown.' }], policies: [] }
  end

  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



420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
# File 'lib/markdown/merge.rb', line 420

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)
  if import_error
    return { ok: false,
             diagnostics: [{ severity: 'error', category: import_error[:category], message: import_error[:message] }], policies: [] }
  end

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

.merge_providerProvider

Returns:



89
90
91
# File 'lib/markdown/merge.rb', line 89

def merge_provider
  @merge_provider ||= Provider.new
end

.normalize_source(source) ⇒ Object



437
438
439
# File 'lib/markdown/merge.rb', line 437

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

.parse_failure_result(error) ⇒ Object



662
663
664
665
666
667
668
# File 'lib/markdown/merge.rb', line 662

def parse_failure_result(error)
  {
    ok: false,
    diagnostics: [{ severity: 'error', category: 'parse_error', message: error.message }],
    policies: []
  }
end

.parse_markdown(source, dialect, backend: nil) ⇒ 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
# File 'lib/markdown/merge.rb', line 153

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

  resolved_backend = resolve_backend(backend)
  unless BACKEND_REFERENCES.key?(resolved_backend)
    return unsupported_feature_result("Unsupported Markdown backend #{resolved_backend}.")
  end

  register_backend!
  parser = TreeHaver.with_backend(resolved_backend) { TreeHaver.parser_for(:markdown) }
  tree = parser.parse(source)
  collect_parse_errors(tree.root_node)

  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 TreeHaver::Error, StandardError => e
  parse_failure_result(e)
end

.register_backend!Object



100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/markdown/merge.rb', line 100

def register_backend!
  BACKEND_REGISTRY.mutex.synchronize do
    return if BACKEND_REGISTRY.registered

    TreeHaver::BackendRegistry.register(BACKEND_REFERENCES.fetch('kreuzberg-language-pack'))

    grammar_finder = TreeHaver::GrammarFinder.new(:markdown)
    grammar_finder.register! if grammar_finder.available?

    BACKEND_REGISTRY.registered = true
  end
end

.register_provider!(replace: false) ⇒ Object

Parameters:

  • replace: (Boolean) (defaults to: false)

Returns:

  • (Object)


93
94
95
96
97
# File 'lib/markdown/merge.rb', line 93

def register_provider!(replace: false)
  return unless Ast::Merge.respond_to?(:register_provider)

  Ast::Merge.register_provider(merge_provider, replace: replace)
end

.resolve_backend(backend) ⇒ Object



629
630
631
632
633
634
635
636
637
# File 'lib/markdown/merge.rb', line 629

def resolve_backend(backend)
  return backend.to_s unless backend.to_s.empty?

  current = TreeHaver.current_backend_id
  return current if BACKEND_REFERENCES.key?(current.to_s) && markdown_backend_available_for_analysis?(current)

  BACKEND_REFERENCES.keys.find { |backend_id| markdown_backend_available_for_analysis?(backend_id) } ||
    'kreuzberg-language-pack'
end

.slugify(value) ⇒ Object



441
442
443
444
445
446
447
448
449
# File 'lib/markdown/merge.rb', line 441

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



670
671
672
673
674
675
676
# File 'lib/markdown/merge.rb', line 670

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