Class: Canon::DiffFormatter::ByLine::YamlFormatter

Inherits:
BaseFormatter
  • Object
show all
Defined in:
lib/canon/diff_formatter/by_line/yaml_formatter.rb

Overview

YAML formatter with semantic token-level highlighting Pretty-prints YAML before diffing for better structure awareness

Instance Attribute Summary

Attributes inherited from BaseFormatter

#context_lines, #diff_grouping_lines, #diff_mode, #legacy_terminal, #show_diffs, #use_color, #visualization_map

Instance Method Summary collapse

Methods inherited from BaseFormatter

#apply_bg, #apply_color, #apply_theme_style, #changed_content_styles, #compute_line_num_width, #content_style, #display_mode, for_format, #initialize, #marker_style, #normalize_color_for_rainbow, #structure_color, #structure_styles, #styled_marker, #theme, #theme_color, #theme_style, #unchanged_content_style, #visualization_chars

Constructor Details

This class inherits a constructor from Canon::DiffFormatter::ByLine::BaseFormatter

Instance Method Details

#format(doc1, doc2) ⇒ String

Format semantic YAML diff with token-level highlighting

Parameters:

  • doc1 (String)

    First YAML document

  • doc2 (String)

    Second YAML document

Returns:

  • (String)

    Formatted diff



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/canon/diff_formatter/by_line/yaml_formatter.rb', line 18

def format(doc1, doc2)
  compute_line_num_width(doc1, doc2)
  output = []

  begin
    # Pretty print both YAML files (canonicalized)
    require "canon"
    pretty1 = Canon.format(doc1, :yaml)
    pretty2 = Canon.format(doc2, :yaml)

    lines1 = pretty1.split("\n")
    lines2 = pretty2.split("\n")

    # Get LCS diff
    diffs = ::Diff::LCS.sdiff(lines1, lines2)

    # Format with semantic token highlighting
    output << format_semantic_diff(diffs, lines1, lines2)
  rescue StandardError => e
    output << colorize(
      "Warning: YAML parsing failed (#{e.message}), using simple diff", :yellow
    )
    require_relative "simple_formatter"
    simple = SimpleFormatter.new(
      use_color: @use_color,
      context_lines: @context_lines,
      diff_grouping_lines: @diff_grouping_lines,
      visualization_map: @visualization_map,
    )
    output << simple.format(doc1, doc2)
  end

  output.join("\n")
end