Class: Canon::Comparison::XmlComparator

Inherits:
MarkupComparator show all
Defined in:
lib/canon/comparison/xml_comparator.rb

Overview

XML comparison class Handles comparison of XML nodes with various options

Inherits shared comparison functionality from MarkupComparator.

Constant Summary collapse

DEFAULT_OPTS =

Default comparison options for XML

{
  # Structural filtering options
  ignore_children: false,
  ignore_text_nodes: false,
  ignore_attr_content: [],
  ignore_attrs: [],
  ignore_attrs_by_name: [],
  ignore_nodes: [],

  # Output options
  verbose: false,
  diff_children: false,

  # Match system options
  match_profile: nil,
  match: nil,
  preprocessing: nil,
  global_profile: nil,
  global_options: nil,

  # Diff display options
  diff: nil,
}.freeze

Class Method Summary collapse

Methods inherited from MarkupComparator

add_difference, build_attribute_difference_reason, build_path_for_node, build_text_difference_reason, comment_node?, determine_node_dimension, enrich_diff_metadata, extract_text_content_from_node, filter_children, node_excluded?, node_text, same_node_type?, serialize_element_node, text_node?, whitespace_only_difference?

Class Method Details

.build_attribute_diff_reason(attrs1, attrs2) ⇒ String

Build a clear reason message for attribute presence differences

Parameters:

  • attrs1 (Hash, nil)

    First node’s attributes

  • attrs2 (Hash, nil)

    Second node’s attributes

Returns:

  • (String)

    Clear explanation of the attribute difference



666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
# File 'lib/canon/comparison/xml_comparator.rb', line 666

def build_attribute_diff_reason(attrs1, attrs2)
  return "#{attrs1&.keys&.size || 0} vs #{attrs2&.keys&.size || 0} attributes" unless attrs1 && attrs2

  require "set"
  keys1 = attrs1.keys.to_set
  keys2 = attrs2.keys.to_set

  only_in_first = keys1 - keys2
  only_in_second = keys2 - keys1
  common = keys1 & keys2

  # Check if values differ for common keys
  different_values = common.reject { |k| attrs1[k] == attrs2[k] }

  parts = []
  parts << "only in first: #{only_in_first.to_a.sort.join(', ')}" if only_in_first.any?
  parts << "only in second: #{only_in_second.to_a.sort.join(', ')}" if only_in_second.any?
  parts << "different values: #{different_values.sort.join(', ')}" if different_values.any?

  if parts.empty?
    "#{keys1.size} vs #{keys2.size} attributes (same names)"
  else
    parts.join("; ")
  end
end

.build_attribute_value_diff_reason(attrs1, attrs2) ⇒ String

Build a clear reason message for attribute value differences

Parameters:

  • attrs1 (Hash, nil)

    First node’s attributes

  • attrs2 (Hash, nil)

    Second node’s attributes

Returns:

  • (String)

    Clear explanation of the attribute value difference



642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
# File 'lib/canon/comparison/xml_comparator.rb', line 642

def build_attribute_value_diff_reason(attrs1, attrs2)
  return "missing vs present attributes" unless attrs1 && attrs2

  require "set"
  keys1 = attrs1.keys.to_set
  keys2 = attrs2.keys.to_set

  common = keys1 & keys2
  different_values = common.reject { |k| attrs1[k] == attrs2[k] }

  return "all attribute values match" if different_values.empty?

  parts = different_values.map do |k|
    "#{k}: #{attrs1[k].inspect} vs #{attrs2[k].inspect}"
  end

  parts.join("; ")
end

.build_difference_reason(node1, node2, diff1, diff2, dimension) ⇒ String

Build a human-readable reason for a difference

Parameters:

  • node1 (Object)

    First node

  • node2 (Object)

    Second node

  • diff1 (String)

    Difference type for node1

  • diff2 (String)

    Difference type for node2

  • dimension (Symbol)

    The dimension of the difference

Returns:

  • (String)

    Human-readable reason



589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
# File 'lib/canon/comparison/xml_comparator.rb', line 589

def build_difference_reason(node1, node2, diff1, diff2, dimension)
  # For deleted/inserted nodes, include namespace information if available
  if dimension == :text_content && (node1.nil? || node2.nil?)
    node = node1 || node2
    if node.respond_to?(:name) && node.respond_to?(:namespace_uri)
      ns = node.namespace_uri
      ns_info = if ns.nil? || ns.empty?
                  ""
                else
                  " (namespace: #{ns})"
                end
      return "element '#{node.name}'#{ns_info}: #{diff1} vs #{diff2}"
    elsif node.respond_to?(:name) && !node.respond_to?(:namespace_uri)
      return "element missing: #{node}"
    end
  end

  # For attribute presence differences, show what attributes differ
  if dimension == :attribute_presence
    attrs1 = extract_attributes(node1)
    attrs2 = extract_attributes(node2)
    return build_attribute_diff_reason(attrs1, attrs2)
  end

  # For text content differences, show the actual text (truncated if needed)
  if dimension == :text_content
    text1 = extract_text_from_node(node1)
    text2 = extract_text_from_node(node2)
    return build_text_diff_reason(text1, text2)
  end

  # For attribute values differences, show the actual values
  if dimension == :attribute_values
    attrs1 = extract_attributes(node1)
    attrs2 = extract_attributes(node2)
    return build_attribute_value_diff_reason(attrs1, attrs2)
  end

  # For attribute order differences, show the actual attribute names
  if dimension == :attribute_order
    attrs1 = extract_attributes(node1)&.keys || []
    attrs2 = extract_attributes(node2)&.keys || []
    return "Attribute order changed: [#{attrs1.join(', ')}] → [#{attrs2.join(', ')}]"
  end

  "#{diff1} vs #{diff2}"
end

.build_text_diff_reason(text1, text2) ⇒ String

Build a clear reason message for text content differences

Parameters:

  • text1 (String, nil)

    First text content

  • text2 (String, nil)

    Second text content

Returns:

  • (String)

    Clear explanation of the text difference



728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
# File 'lib/canon/comparison/xml_comparator.rb', line 728

def build_text_diff_reason(text1, text2)
  # Handle nil cases
  return "missing vs '#{truncate_text(text2)}'" if text1.nil? && text2
  return "'#{truncate_text(text2)}' vs missing" if text1 && text2.nil?
  return "both missing" if text1.nil? && text2.nil?

  # Check if both are whitespace-only
  if whitespace_only?(text1) && whitespace_only?(text2)
    return "whitespace: #{describe_whitespace(text1)} vs #{describe_whitespace(text2)}"
  end

  # Show text with visible whitespace markers
  # Use escaped representations for clarity: \n for newline, \t for tab, · for spaces
  vis1 = visualize_whitespace(text1)
  vis2 = visualize_whitespace(text2)

  "Text: \"#{vis1}\" vs \"#{vis2}\""
end

.character_visualization_mapHash

Get the character visualization map (lazy-loaded to avoid circular dependency)

Returns:

  • (Hash)

    Character to visualization symbol mapping



775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
# File 'lib/canon/comparison/xml_comparator.rb', line 775

def character_visualization_map
  @character_visualization_map ||= begin
    # Load the YAML file directly to avoid circular dependency
    require "yaml"
    lib_root = File.expand_path("../..", __dir__)
    yaml_path = File.join(lib_root,
                          "canon/diff_formatter/character_map.yml")
    data = YAML.load_file(yaml_path)

    # Build visualization map from the YAML data
    visualization_map = {}
    data["characters"].each do |char_data|
      # Get the character from either unicode code point or character field
      char = if char_data["unicode"]
               # Convert hex string to character
               [char_data["unicode"].to_i(16)].pack("U")
             else
               # Use character field directly (handles \n, \t, etc.)
               char_data["character"]
             end

      vis = char_data["visualization"]
      visualization_map[char] = vis
    end

    visualization_map
  end
end

.compare_attribute_sets(n1, n2, opts, differences) ⇒ Object

Compare attribute sets Delegates to XmlComparatorHelpers::AttributeComparator



356
357
358
359
# File 'lib/canon/comparison/xml_comparator.rb', line 356

def compare_attribute_sets(n1, n2, opts, differences)
  XmlComparatorHelpers::AttributeComparator.compare(n1, n2, opts,
                                                    differences)
end

.compare_children(n1, n2, opts, child_opts, diff_children, differences) ⇒ Object

Compare children of two nodes using semantic matching

Delegates to ChildComparison module which handles both ElementMatcher (semantic matching) and simple positional comparison.



529
530
531
532
533
534
# File 'lib/canon/comparison/xml_comparator.rb', line 529

def compare_children(n1, n2, opts, child_opts, diff_children,
differences)
  XmlComparatorHelpers::ChildComparison.compare(
    n1, n2, self, opts, child_opts, diff_children, differences
  )
end

.compare_comment_nodes(n1, n2, opts, differences) ⇒ Object

Compare comment nodes



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
# File 'lib/canon/comparison/xml_comparator.rb', line 459

def compare_comment_nodes(n1, n2, opts, differences)
  match_opts = opts[:match_opts]
  behavior = match_opts[:comments]

  # Canon::Xml::Node CommentNode uses .value, Nokogiri uses .content
  content1 = node_text(n1)
  content2 = node_text(n2)

  # Check if content differs
  contents_differ = content1 != content2

  # Create DiffNode in verbose mode when content differs
  # This ensures informative diffs are created even for :ignore behavior
  if contents_differ && opts[:verbose]
    add_difference(n1, n2, Comparison::UNEQUAL_COMMENTS,
                   Comparison::UNEQUAL_COMMENTS, :comments, opts,
                   differences)
  end

  # Return based on behavior and whether content matches
  if behavior == :ignore || !contents_differ
    Comparison::EQUIVALENT
  else
    Comparison::UNEQUAL_COMMENTS
  end
end

.compare_document_nodes(n1, n2, opts, child_opts, diff_children, differences) ⇒ Object

Compare document nodes



509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
# File 'lib/canon/comparison/xml_comparator.rb', line 509

def compare_document_nodes(n1, n2, opts, child_opts, diff_children,
                           differences)
  # Compare root elements
  root1 = n1.root
  root2 = n2.root

  if root1.nil? || root2.nil?
    add_difference(n1, n2, Comparison::MISSING_NODE,
                   Comparison::MISSING_NODE, :text_content, opts, differences)
    return Comparison::MISSING_NODE
  end

  compare_nodes(root1, root2, opts, child_opts, diff_children,
                differences)
end

.compare_element_nodes(n1, n2, opts, child_opts, diff_children, differences) ⇒ Object

Compare two element nodes



311
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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
# File 'lib/canon/comparison/xml_comparator.rb', line 311

def compare_element_nodes(n1, n2, opts, child_opts, diff_children,
                          differences)
  # Compare element names
  unless n1.name == n2.name
    add_difference(n1, n2, Comparison::UNEQUAL_ELEMENTS,
                   Comparison::UNEQUAL_ELEMENTS, :element_structure, opts,
                   differences)
    return Comparison::UNEQUAL_ELEMENTS
  end

  # Compare namespace URIs - elements with different namespaces are different elements
  ns1 = n1.respond_to?(:namespace_uri) ? n1.namespace_uri : nil
  ns2 = n2.respond_to?(:namespace_uri) ? n2.namespace_uri : nil

  unless ns1 == ns2
    # Create descriptive reason showing the actual namespace URIs
    ns1_display = ns1.nil? || ns1.empty? ? "(no namespace)" : ns1
    ns2_display = ns2.nil? || ns2.empty? ? "(no namespace)" : ns2

    diff_node = Canon::Diff::DiffNode.new(
      node1: n1,
      node2: n2,
      dimension: :namespace_uri,
      reason: "namespace '#{ns1_display}' vs '#{ns2_display}' on element '#{n1.name}'",
    )
    differences << diff_node if opts[:verbose]
    return Comparison::UNEQUAL_ELEMENTS
  end

  # Compare namespace declarations (xmlns and xmlns:* attributes)
  ns_result = compare_namespace_declarations(n1, n2, opts, differences)
  return ns_result unless ns_result == Comparison::EQUIVALENT

  # Compare attributes
  attr_result = compare_attribute_sets(n1, n2, opts, differences)
  return attr_result unless attr_result == Comparison::EQUIVALENT

  # Compare children if not ignored
  return Comparison::EQUIVALENT if opts[:ignore_children]

  compare_children(n1, n2, opts, child_opts, diff_children, differences)
end

.compare_namespace_declarations(n1, n2, opts, differences) ⇒ Object

Compare namespace declarations (xmlns and xmlns:* attributes) Delegates to XmlComparatorHelpers::NamespaceComparator



841
842
843
844
# File 'lib/canon/comparison/xml_comparator.rb', line 841

def compare_namespace_declarations(n1, n2, opts, differences)
  XmlComparatorHelpers::NamespaceComparator.compare(n1, n2, opts,
                                                    differences)
end

.compare_processing_instruction_nodes(n1, n2, opts, differences) ⇒ Object

Compare processing instruction nodes



487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
# File 'lib/canon/comparison/xml_comparator.rb', line 487

def compare_processing_instruction_nodes(n1, n2, opts, differences)
  unless n1.target == n2.target
    add_difference(n1, n2, Comparison::UNEQUAL_NODES_TYPES,
                   Comparison::UNEQUAL_NODES_TYPES, :text_content, opts,
                   differences)
    return Comparison::UNEQUAL_NODES_TYPES
  end

  content1 = n1.respond_to?(:content) ? n1.content.to_s.strip : ""
  content2 = n2.respond_to?(:content) ? n2.content.to_s.strip : ""

  if content1 == content2
    Comparison::EQUIVALENT
  else
    add_difference(n1, n2, Comparison::UNEQUAL_TEXT_CONTENTS,
                   Comparison::UNEQUAL_TEXT_CONTENTS, :text_content,
                   opts, differences)
    Comparison::UNEQUAL_TEXT_CONTENTS
  end
end

.compare_text_nodes(n1, n2, opts, differences) ⇒ Object

Compare text nodes



362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
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
# File 'lib/canon/comparison/xml_comparator.rb', line 362

def compare_text_nodes(n1, n2, opts, differences)
  return Comparison::EQUIVALENT if opts[:ignore_text_nodes]

  text1 = node_text(n1)
  text2 = node_text(n2)

  # Use match options
  match_opts = opts[:match_opts]
  behavior = match_opts[:text_content]

  # For HTML, check if text node is inside whitespace-preserving element
  # If so, always use strict comparison regardless of text_content setting
  sensitive_element = should_preserve_whitespace_strictly?(n1, n2, opts)
  if sensitive_element
    behavior = :strict
  end

  # Check if raw content differs
  raw_differs = text1 != text2

  # Check if matches according to behavior
  matches_per_behavior = MatchOptions.match_text?(text1, text2,
                                                  behavior)

  # Determine the correct dimension for this difference
  # - If text_content is :strict, ALL differences use :text_content dimension
  # - If text_content is :normalize, whitespace-only diffs could use :structural_whitespace
  #   but we keep :text_content to ensure correct classification behavior
  # - Otherwise use :text_content
  # However, if element is whitespace-sensitive (like <pre> in HTML),
  # always use :text_content dimension regardless of behavior
  #
  # NOTE: We keep the dimension as :text_content even for whitespace-only diffs
  # when text_content: :normalize. This ensures that the classification uses
  # the text_content behavior (:normalize) instead of structural_whitespace
  # behavior (:strict for XML), which would incorrectly mark the diff as normative.
  if sensitive_element
  # Whitespace-sensitive element: always use :text_content dimension
  else
    # Always use :text_content for text differences
    # This ensures correct classification based on text_content behavior
  end
  dimension = :text_content

  # Create DiffNode in verbose mode when raw content differs
  # This ensures informative diffs are created even for :ignore/:normalize
  if raw_differs && opts[:verbose]
    add_difference(n1, n2, Comparison::UNEQUAL_TEXT_CONTENTS,
                   Comparison::UNEQUAL_TEXT_CONTENTS, dimension,
                   opts, differences)
  end

  # Return based on whether behavior makes difference acceptable
  matches_per_behavior ? Comparison::EQUIVALENT : Comparison::UNEQUAL_TEXT_CONTENTS
end

.describe_whitespace(text) ⇒ String

Describe whitespace content in a readable way

Parameters:

  • text (String)

    Whitespace text

Returns:

  • (String)

    Description like “4 chars (2 newlines, 2 spaces)”



808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
# File 'lib/canon/comparison/xml_comparator.rb', line 808

def describe_whitespace(text)
  return "0 chars" if text.nil? || text.empty?

  char_count = text.length
  newline_count = text.count("\n")
  space_count = text.count(" ")
  tab_count = text.count("\t")

  parts = []
  parts << "#{newline_count} newlines" if newline_count.positive?
  parts << "#{space_count} spaces" if space_count.positive?
  parts << "#{tab_count} tabs" if tab_count.positive?

  description = parts.join(", ")
  "#{char_count} chars (#{description})"
end

.equivalent?(n1, n2, opts = {}, child_opts = {}) ⇒ Boolean, Array

Compare two XML nodes for equivalence

Parameters:

  • n1 (String, Moxml::Node)

    First node

  • n2 (String, Moxml::Node)

    Second node

  • opts (Hash) (defaults to: {})

    Comparison options

  • child_opts (Hash) (defaults to: {})

    Options for child comparison

Returns:

  • (Boolean, Array)

    true if equivalent, or array of diffs if verbose



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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
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
152
153
154
155
156
# File 'lib/canon/comparison/xml_comparator.rb', line 65

def equivalent?(n1, n2, opts = {}, child_opts = {})
  opts = DEFAULT_OPTS.merge(opts)

  # Resolve match options with format-specific defaults
  match_opts_hash = MatchOptions::Xml.resolve(
    format: :xml,
    match_profile: opts[:match_profile],
    match: opts[:match],
    preprocessing: opts[:preprocessing],
    global_profile: opts[:global_profile],
    global_options: opts[:global_options],
  )

  # Wrap in ResolvedMatchOptions for DiffClassifier
  match_opts = Canon::Comparison::ResolvedMatchOptions.new(
    match_opts_hash,
    format: :xml,
  )

  # Store resolved match options hash for use in comparison logic
  opts[:match_opts] = match_opts_hash

  # Use tree diff if semantic_diff option is enabled
  if match_opts.semantic_diff?
    return perform_semantic_tree_diff(n1, n2, opts, match_opts_hash)
  end

  # Create child_opts with resolved options
  child_opts = opts.merge(child_opts)

  # Determine if we should preserve whitespace during parsing
  # When structural_whitespace is :strict, preserve all whitespace-only text nodes
  preserve_whitespace = match_opts_hash[:structural_whitespace] == :strict

  # Parse nodes if they are strings, applying preprocessing if needed
  node1 = parse_node(n1, match_opts_hash[:preprocessing],
                     preserve_whitespace: preserve_whitespace)
  node2 = parse_node(n2, match_opts_hash[:preprocessing],
                     preserve_whitespace: preserve_whitespace)

  # Store original strings for line diff display (before preprocessing)
  original1 = if n1.is_a?(String)
                n1
              else
                (n1.respond_to?(:to_xml) ? n1.to_xml : n1.to_s)
              end
  original2 = if n2.is_a?(String)
                n2
              else
                (n2.respond_to?(:to_xml) ? n2.to_xml : n2.to_s)
              end

  differences = []
  diff_children = opts[:diff_children] || false

  result = compare_nodes(node1, node2, opts, child_opts,
                         diff_children, differences)

  # Classify DiffNodes as normative/informative if we have verbose output
  if opts[:verbose] && !differences.empty?
    classifier = Canon::Diff::DiffClassifier.new(match_opts)
    classifier.classify_all(differences.grep(Canon::Diff::DiffNode))
  end

  if opts[:verbose]
    # Serialize parsed nodes for consistent formatting
    # This ensures both sides formatted identically, showing only real differences
    preprocessed = [
      serialize_node(node1).gsub("><", ">\n<"),
      serialize_node(node2).gsub("><", ">\n<"),
    ]

    ComparisonResult.new(
      differences: differences,
      preprocessed_strings: preprocessed,
      original_strings: [original1, original2],
      format: :xml,
      match_options: match_opts_hash,
      algorithm: :dom,
    )
  elsif result != Comparison::EQUIVALENT && !differences.empty?
    # Non-verbose mode: check equivalence
    # If comparison found differences, classify them to determine if normative
    classifier = Canon::Diff::DiffClassifier.new(match_opts)
    classifier.classify_all(differences.grep(Canon::Diff::DiffNode))
    # Equivalent if no normative differences (matches semantic algorithm)
    differences.none?(&:normative?)
  else
    # Either equivalent or no differences tracked
    result == Comparison::EQUIVALENT
  end
end

.extract_attributes(node) ⇒ Hash?

Extract attributes from a node as a normalized hash

Parameters:

  • node (Object, nil)

    Node to extract attributes from

Returns:

  • (Hash, nil)

    Normalized attributes hash



576
577
578
579
580
# File 'lib/canon/comparison/xml_comparator.rb', line 576

def extract_attributes(node)
  return nil if node.nil?

  Canon::Diff::NodeSerializer.extract_attributes(node)
end

.extract_element_path(node) ⇒ Array<String>

Extract element path for context (best effort)

Parameters:

  • node (Object)

    Node to extract path from

Returns:

  • (Array<String>)

    Path components



539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
# File 'lib/canon/comparison/xml_comparator.rb', line 539

def extract_element_path(node)
  path = []
  current = node
  max_depth = 20
  depth = 0

  while current && depth < max_depth
    if current.respond_to?(:name) && current.name
      path.unshift(current.name)
    end

    break unless current.respond_to?(:parent)

    current = current.parent
    depth += 1

    # Stop at document root
    break if current.respond_to?(:root)
  end

  path
end

.extract_text_from_node(node) ⇒ String?

Extract text from a node for diff reason

Parameters:

  • node (Object, nil)

    Node to extract text from

Returns:

  • (String, nil)

    Text content or nil



696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
# File 'lib/canon/comparison/xml_comparator.rb', line 696

def extract_text_from_node(node)
  return nil if node.nil?

  # For Canon::Xml::Nodes::TextNode
  return node.value if node.respond_to?(:value) && node.is_a?(Canon::Xml::Nodes::TextNode)

  # For XML/HTML nodes with text_content method
  return node.text_content if node.respond_to?(:text_content)

  # For nodes with text method
  return node.text if node.respond_to?(:text)

  # For nodes with content method (Moxml::Text)
  return node.content if node.respond_to?(:content)

  # For nodes with value method (other types)
  return node.value if node.respond_to?(:value)

  # For simple text nodes or strings
  return node.to_s if node.is_a?(String)

  # For other node types, try to_s
  node.to_s
rescue StandardError
  nil
end

.in_preserve_element?(node, preserve_list) ⇒ Boolean

Check if a node is inside a whitespace-preserving element

Returns:

  • (Boolean)


442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
# File 'lib/canon/comparison/xml_comparator.rb', line 442

def in_preserve_element?(node, preserve_list)
  current = node.parent
  while current.respond_to?(:name)
    return true if preserve_list.include?(current.name.downcase)

    # Stop at document root
    break if current.is_a?(Nokogiri::XML::Document) ||
      current.is_a?(Nokogiri::HTML4::Document) ||
      current.is_a?(Nokogiri::HTML5::Document)

    current = current.parent if current.respond_to?(:parent)
    break unless current
  end
  false
end

.serialize_node(node) ⇒ String?

Serialize a node to string for display

Parameters:

  • node (Object, nil)

    Node to serialize

Returns:

  • (String, nil)

    Serialized content



566
567
568
569
570
# File 'lib/canon/comparison/xml_comparator.rb', line 566

def serialize_node(node)
  return nil if node.nil?

  Canon::Diff::NodeSerializer.serialize(node)
end

.should_preserve_whitespace_strictly?(n1, n2, opts) ⇒ Boolean

Check if whitespace should be preserved strictly for these text nodes This applies to HTML elements like pre, code, textarea, script, style and elements with xml:space=“preserve” or in user-configured preserve list.

IMPORTANT: This returns true ONLY for :preserve classification. For :collapse classification, whitespace differences ARE acceptable (they are detected as formatting-only by DiffClassifier).

Returns:

  • (Boolean)


425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
# File 'lib/canon/comparison/xml_comparator.rb', line 425

def should_preserve_whitespace_strictly?(n1, n2, opts)
  # Check both n1 and n2 - if either is in a preserve whitespace element, preserve strictly
  [n1, n2].each do |node|
    next unless node.respond_to?(:parent)

    parent = node.parent
    next unless parent

    classification = WhitespaceSensitivity.classify_element(parent,
                                                            opts[:match_opts])
    return true if classification == :preserve
  end

  false
end

.truncate_text(text, max_length = 40) ⇒ String

Truncate text for display in reason messages

Parameters:

  • text (String)

    Text to truncate

  • max_length (Integer) (defaults to: 40)

    Maximum length

Returns:

  • (String)

    Truncated text



830
831
832
833
834
835
836
837
# File 'lib/canon/comparison/xml_comparator.rb', line 830

def truncate_text(text, max_length = 40)
  return "" if text.nil?

  text = text.to_s
  return text if text.length <= max_length

  "#{text[0...max_length]}..."
end

.visualize_whitespace(text) ⇒ String

Make whitespace visible in text content Uses the existing character visualization map from DiffFormatter (single source of truth)

Parameters:

  • text (String)

    Text to visualize

Returns:

  • (String)

    Text with visible whitespace markers



762
763
764
765
766
767
768
769
770
# File 'lib/canon/comparison/xml_comparator.rb', line 762

def visualize_whitespace(text)
  return "" if text.nil?

  # Use the character map loader as the single source of truth
  viz_map = character_visualization_map

  # Replace each character with its visualization
  text.chars.map { |char| viz_map[char] || char }.join
end

.whitespace_only?(text) ⇒ Boolean

Check if text is only whitespace

Parameters:

  • text (String)

    Text to check

Returns:

  • (Boolean)

    true if whitespace-only



751
752
753
754
755
# File 'lib/canon/comparison/xml_comparator.rb', line 751

def whitespace_only?(text)
  return false if text.nil?

  text.to_s.strip.empty?
end