Class: Canon::Comparison::XmlComparator
- Inherits:
-
MarkupComparator
- Object
- MarkupComparator
- Canon::Comparison::XmlComparator
- 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
-
.build_attribute_diff_reason(attrs1, attrs2) ⇒ String
Build a clear reason message for attribute presence differences.
-
.build_attribute_value_diff_reason(attrs1, attrs2) ⇒ String
Build a clear reason message for attribute value differences.
-
.build_difference_reason(node1, node2, diff1, diff2, dimension) ⇒ String
Build a human-readable reason for a difference.
-
.build_text_diff_reason(text1, text2) ⇒ String
Build a clear reason message for text content differences.
-
.character_visualization_map ⇒ Hash
Get the character visualization map (lazy-loaded to avoid circular dependency).
-
.compare_attribute_sets(n1, n2, opts, differences) ⇒ Object
Compare attribute sets Delegates to XmlComparatorHelpers::AttributeComparator.
-
.compare_children(n1, n2, opts, child_opts, diff_children, differences) ⇒ Object
Compare children of two nodes using semantic matching.
-
.compare_comment_nodes(n1, n2, opts, differences) ⇒ Object
Compare comment nodes.
-
.compare_document_nodes(n1, n2, opts, child_opts, diff_children, differences) ⇒ Object
Compare document nodes.
-
.compare_element_nodes(n1, n2, opts, child_opts, diff_children, differences) ⇒ Object
Compare two element nodes.
-
.compare_namespace_declarations(n1, n2, opts, differences) ⇒ Object
Compare namespace declarations (xmlns and xmlns:* attributes) Delegates to XmlComparatorHelpers::NamespaceComparator.
-
.compare_processing_instruction_nodes(n1, n2, opts, differences) ⇒ Object
Compare processing instruction nodes.
-
.compare_text_nodes(n1, n2, opts, differences) ⇒ Object
Compare text nodes.
-
.describe_whitespace(text) ⇒ String
Describe whitespace content in a readable way.
-
.equivalent?(n1, n2, opts = {}, child_opts = {}) ⇒ Boolean, Array
Compare two XML nodes for equivalence.
-
.extract_attributes(node) ⇒ Hash?
Extract attributes from a node as a normalized hash.
-
.extract_element_path(node) ⇒ Array<String>
Extract element path for context (best effort).
-
.extract_text_from_node(node) ⇒ String?
Extract text from a node for diff reason.
-
.in_preserve_element?(node, preserve_list) ⇒ Boolean
Check if a node is inside a whitespace-preserving element.
-
.serialize_node(node) ⇒ String?
Serialize a node to string for display.
-
.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.
-
.truncate_text(text, max_length = 40) ⇒ String
Truncate text for display in reason messages.
-
.visualize_whitespace(text) ⇒ String
Make whitespace visible in text content Uses the existing character visualization map from DiffFormatter (single source of truth).
-
.whitespace_only?(text) ⇒ Boolean
Check if text is only whitespace.
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
746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 |
# File 'lib/canon/comparison/xml_comparator.rb', line 746 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
722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 |
# File 'lib/canon/comparison/xml_comparator.rb', line 722 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
659 660 661 662 663 664 665 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 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 |
# File 'lib/canon/comparison/xml_comparator.rb', line 659 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) # TextNode and other nodes without namespace_uri display = if node.respond_to?(:value) && node.node_type == :text "\"#{truncate_text(node.value)}\"" else node.name.to_s end return "element missing: #{display}" 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 if diff1 == Canon::Comparison::MISSING_NODE && diff2 == Canon::Comparison::MISSING_NODE "element structure mismatch (children differ)" else "#{diff1} vs #{diff2}" end end |
.build_text_diff_reason(text1, text2) ⇒ String
Build a clear reason message for text content differences
808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 |
# File 'lib/canon/comparison/xml_comparator.rb', line 808 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_map ⇒ Hash
Get the character visualization map (lazy-loaded to avoid circular dependency)
855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 |
# File 'lib/canon/comparison/xml_comparator.rb', line 855 def character_visualization_map @character_visualization_map ||= begin # Load the YAML file directly to avoid circular dependency require "yaml" lib_root = File.("../..", __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
424 425 426 427 |
# File 'lib/canon/comparison/xml_comparator.rb', line 424 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.
599 600 601 602 603 604 |
# File 'lib/canon/comparison/xml_comparator.rb', line 599 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
529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 |
# File 'lib/canon/comparison/xml_comparator.rb', line 529 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
579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 |
# File 'lib/canon/comparison/xml_comparator.rb', line 579 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
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 417 418 419 420 |
# File 'lib/canon/comparison/xml_comparator.rb', line 379 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
921 922 923 924 |
# File 'lib/canon/comparison/xml_comparator.rb', line 921 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
557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 |
# File 'lib/canon/comparison/xml_comparator.rb', line 557 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
430 431 432 433 434 435 436 437 438 439 440 441 442 443 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 481 482 483 484 485 486 |
# File 'lib/canon/comparison/xml_comparator.rb', line 430 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 whitespace_type = match_opts[:whitespace_type] || :strict matches_per_behavior = MatchOptions.match_text?(text1, text2, behavior, whitespace_type: whitespace_type) # 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
888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 |
# File 'lib/canon/comparison/xml_comparator.rb', line 888 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
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 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 |
# File 'lib/canon/comparison/xml_comparator.rb', line 65 def equivalent?(n1, n2, opts = {}, child_opts = {}) # FAST PATH: Object identity - same object is always equivalent # Skip when semantic_diff is requested (caller needs tree diff metadata) if n1.equal?(n2) && !opts.dig(:match, :semantic_diff) return build_trivial_equivalent_result(n1, n2, opts) end # FAST PATH: String content equality - identical strings are equivalent # Skip in verbose mode since caller may need full metadata (e.g. tree_diff statistics) if !opts[:verbose] && n1.is_a?(String) && n2.is_a?(String) && n1 == n2 return true end 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. # Only structural_whitespace: :strict forces whitespace-only text # nodes to survive parsing. whitespace_type is about distinguishing # Unicode whitespace *types* in surviving text-node content, and # does NOT require indent text nodes to be kept — libxml's NOBLANKS # only strips pure-ASCII whitespace-only nodes, so NBSP-only nodes # survive regardless. Coupling whitespace_type: :strict to # parsing-time preservation made pretty-printed fixtures produce # spurious element-position diffs (issue #112). 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
646 647 648 649 650 |
# File 'lib/canon/comparison/xml_comparator.rb', line 646 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)
609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 |
# File 'lib/canon/comparison/xml_comparator.rb', line 609 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
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 |
# File 'lib/canon/comparison/xml_comparator.rb', line 776 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
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 |
# File 'lib/canon/comparison/xml_comparator.rb', line 512 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
636 637 638 639 640 |
# File 'lib/canon/comparison/xml_comparator.rb', line 636 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).
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 |
# File 'lib/canon/comparison/xml_comparator.rb', line 495 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
910 911 912 913 914 915 916 917 |
# File 'lib/canon/comparison/xml_comparator.rb', line 910 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)
842 843 844 845 846 847 848 849 850 |
# File 'lib/canon/comparison/xml_comparator.rb', line 842 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
831 832 833 834 835 |
# File 'lib/canon/comparison/xml_comparator.rb', line 831 def whitespace_only?(text) return false if text.nil? text.to_s.strip.empty? end |