Class: Canon::DiffFormatter::ByLine::XmlFormatter
- Inherits:
-
BaseFormatter
- Object
- BaseFormatter
- Canon::DiffFormatter::ByLine::XmlFormatter
- Defined in:
- lib/canon/diff_formatter/by_line/xml_formatter.rb
Overview
XML formatter with DOM-guided diffing Uses DOM parsing and element matching for intelligent XML diffs
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
-
#append_unlocated_context(report) ⇒ Object
Trailing context for DiffNodes with no located char ranges (multiline reflowed text, relocated content): one removed DiffLine per serialized_before line, one added per serialized_after line.
-
#context_index_after(report, anchor_node) ⇒ Object
Index into report.contexts for inserting an unlocated context: after the context holding the anchor node's lines, or at the front when the anchor is nil (nothing precedes).
-
#format(doc1, doc2) ⇒ String
Format DOM-guided XML diff.
-
#format_context_from_lines(context, lines1, _lines2) ⇒ Object
Format a context using its DiffLines.
-
#format_legacy(doc1, doc2) ⇒ Object
Legacy format method (for backward compatibility).
-
#format_report(report, doc1, doc2) ⇒ Object
Format a DiffReport for display.
-
#format_with_pipeline(doc1, doc2) ⇒ Object
Format using new DiffReportBuilder pipeline.
-
#parent_chain(path) ⇒ Object
Display chain of a DiffNode's ancestor elements, e.g.
-
#preceding_located(diff_node) ⇒ Object
The nearest preceding node (in @differences walk order) that the enricher DID locate.
-
#unlocated_lines(diff_node) ⇒ Object
Mini-diff of one unlocated node's serialized sides: shared lines render as :unchanged context instead of remove-all + add-all.
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
#append_unlocated_context(report) ⇒ Object
Trailing context for DiffNodes with no located char ranges (multiline reflowed text, relocated content): one removed DiffLine per serialized_before line, one added per serialized_after line. Nil positions render as blank line numbers.
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 |
# File 'lib/canon/diff_formatter/by_line/xml_formatter.rb', line 88 def append_unlocated_context(report) unlocated = @differences.select do |dn| dn.char_ranges.nil? || dn.char_ranges.empty? end return if unlocated.empty? unlocated = unlocated.reject do |dn| (@show_diffs == :normative && !dn.normative?) || (@show_diffs == :informative && !dn.informative?) end return if unlocated.empty? # Place each unlocated node's context after the report # context containing its nearest preceding LOCATED node # (@differences is comparator-walk order = document order), # so the change reads in position instead of trailing. unlocated.each do |dn| context = Canon::Diff::DiffContext.new( lines: unlocated_lines(dn), ) anchor_index = context_index_after(report, preceding_located(dn)) report.contexts.insert(anchor_index, context) end end |
#context_index_after(report, anchor_node) ⇒ Object
Index into report.contexts for inserting an unlocated context: after the context holding the anchor node's lines, or at the front when the anchor is nil (nothing precedes).
203 204 205 206 207 208 209 210 211 212 213 |
# File 'lib/canon/diff_formatter/by_line/xml_formatter.rb', line 203 def context_index_after(report, anchor_node) return 0 if anchor_node.nil? report.contexts.each_with_index do |context, idx| has_anchor = context.lines.any? do |dl| dl.diff_node&.equal?(anchor_node) end return idx + 1 if has_anchor end report.contexts.length end |
#format(doc1, doc2) ⇒ String
Format DOM-guided XML diff
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
# File 'lib/canon/diff_formatter/by_line/xml_formatter.rb', line 17 def format(doc1, doc2) compute_line_num_width(doc1, doc2) # If we have DiffNodes from comparison, check if there are normative diffs # based on show_diffs setting if @differences&.any?(Canon::Diff::DiffNode) # Check if we should skip based on show_diffs setting if should_skip_diff_display? return "" end # Use new pipeline when DiffNodes available return format_with_pipeline(doc1, doc2) end # LEGACY: Fall back to old behavior for backward compatibility # This handles formatting-only differences (0 DiffNodes) and legacy Hash entries format_legacy(doc1, doc2) end |
#format_context_from_lines(context, lines1, _lines2) ⇒ Object
Format a context using its DiffLines
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 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 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 |
# File 'lib/canon/diff_formatter/by_line/xml_formatter.rb', line 246 def format_context_from_lines(context, lines1, _lines2) output = [] context.lines.each do |diff_line| case diff_line.type when :unchanged old_num = diff_line.line_number&.+(1) new_num = (diff_line.new_position || diff_line.line_number)&.+(1) output << format_unified_line(old_num, new_num, " ", diff_line.content) when :location_header output << format_location_header(diff_line.content) when :removed line_num = diff_line.line_number&.+(1) formatting = diff_line.formatting? informative = diff_line.informative? output << if formatting # Formatting-only removal: use theme formatting style format_unified_line(line_num, nil, "[", diff_line.content, theme_color(:formatting, :content), formatting: true) elsif informative # Informative removal: use theme informative style format_unified_line(line_num, nil, "<", diff_line.content, theme_color(:informative, :content), informative: true) elsif diff_line.has_char_ranges? # Use character-level highlighting when char_ranges available. highlighted = render_line_from_char_ranges( diff_line.content, diff_line.char_ranges, :old ) old_str = "%#{@line_num_width}d" % line_num blank = " " * @line_num_width if @use_color yellow_old = colorize(old_str, structure_color(:line_number) || :yellow) yellow_pipe1 = colorize("|", structure_color(:pipe) || :yellow) yellow_pipe2 = colorize("|", structure_color(:pipe) || :yellow) red_marker = styled_marker("-", :removed) "#{yellow_old}#{yellow_pipe1}#{blank}#{red_marker} #{yellow_pipe2} #{highlighted}" else "#{old_str}|#{blank}- | #{highlighted}" end else # Normative removal: use theme removed style format_unified_line(line_num, nil, "-", diff_line.content, theme_color(:removed, :content)) end when :added line_num = (diff_line.new_position || diff_line.line_number)&.+(1) formatting = diff_line.formatting? informative = diff_line.informative? output << if formatting # Formatting-only addition: use theme formatting style format_unified_line(nil, line_num, "]", diff_line.content, theme_color(:formatting, :content), formatting: true) elsif informative # Informative addition: use theme informative style format_unified_line(nil, line_num, ">", diff_line.content, theme_color(:informative, :content), informative: true) else # Normative addition: use theme added style format_unified_line(nil, line_num, "+", diff_line.content, theme_color(:added, :content)) end when :changed output << format_changed_line(diff_line, lines1) when :reflow_summary # Reflow summary: show collapsed formatting-only reflow output << format_reflow_summary(diff_line) end end output.join("\n") end |
#format_legacy(doc1, doc2) ⇒ Object
Legacy format method (for backward compatibility)
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 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 |
# File 'lib/canon/diff_formatter/by_line/xml_formatter.rb', line 336 def format_legacy(doc1, doc2) # Check if we should show any diffs based on differences array if should_skip_diff_display? return "" end # If documents are equivalent (no normative diffs), do NOT run legacy formatter. # The legacy formatter shows ALL differences it finds via LCS on lines, # which can be misleading when the comparison found no normative differences. # Only run legacy formatter when we have actual DiffNode data to display. if @equivalent == true && (@differences.nil? || @differences.empty? || @differences.none?(Canon::Diff::DiffNode)) return "" end output = [] begin # Parse to DOM root1 = Canon::Xml::DataModel.from_xml(doc1) root2 = Canon::Xml::DataModel.from_xml(doc2) # Match elements semantically matcher = Canon::Xml::ElementMatcher.new matches = matcher.match_trees(root1, root2) # Build line range maps using ORIGINAL documents mapper1 = Canon::Xml::LineRangeMapper.new(indent: 2) mapper2 = Canon::Xml::LineRangeMapper.new(indent: 2) map1 = mapper1.build_map(root1, doc1) map2 = mapper2.build_map(root2, doc2) # Use ORIGINAL document lines for display lines1 = doc1.split("\n") lines2 = doc2.split("\n") # Display diffs based on element matches output << format_element_matches(matches, map1, map2, lines1, lines2) rescue StandardError => e # Fall back to simple diff on error output << colorize("Warning: DOM parsing failed, using simple diff", :yellow) output << colorize("Error: #{e.class}: #{e.}", :red) # Include relevant backtrace lines relevant_trace = e.backtrace.select do |line| line.include?("canon") end.take(3) unless relevant_trace.empty? output << colorize("Backtrace:", :yellow) relevant_trace.each do |line| output << colorize(" #{line}", :yellow) end end output << "" 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 |
#format_report(report, doc1, doc2) ⇒ Object
Format a DiffReport for display
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 |
# File 'lib/canon/diff_formatter/by_line/xml_formatter.rb', line 216 def format_report(report, doc1, doc2) return "" if report.contexts.empty? lines1 = @pipeline_lines1 || doc1.split("\n") lines2 = @pipeline_lines2 || doc2.split("\n") output = [] # Detect non-ASCII characters — scan the source strings # directly; joining the split lines back into one document # per render was pure garbage. non_ascii = Legend.detect_non_ascii(doc1, @visualization_map) non_ascii.merge!(Legend.detect_non_ascii(doc2, @visualization_map)) # Add Unicode legend if needed unless non_ascii.empty? output << Legend.build_legend(non_ascii, use_color: @use_color) output << "" end # Format each context report.contexts.each_with_index do |context, idx| output << "" if idx.positive? output << format_context_from_lines(context, lines1, lines2) end output.join("\n") end |
#format_with_pipeline(doc1, doc2) ⇒ Object
Format using new DiffReportBuilder pipeline
38 39 40 41 42 43 44 45 46 47 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 81 |
# File 'lib/canon/diff_formatter/by_line/xml_formatter.rb', line 38 def format_with_pipeline(doc1, doc2) # Check if we should show any diffs if should_skip_diff_display? return "" end # Compute line number width BEFORE formatting compute_line_num_width(doc1, doc2) # The pipeline splits both documents once here; every stage # downstream reuses the arrays (three redundant full-doc # splits per render before). @pipeline_lines1 = doc1.split("\n") @pipeline_lines2 = doc2.split("\n") # Phase 1: Enrich DiffNodes with character positions Canon::Diff::DiffNodeEnricher.build(@differences, doc1, doc2, lines1: @pipeline_lines1, lines2: @pipeline_lines2) # Phase 2: Assemble DiffLines from enriched DiffNodes diff_lines = Canon::Diff::DiffLineBuilder.build(@differences, doc1, doc2, lines1: @pipeline_lines1, lines2: @pipeline_lines2) # Layers 3-5: Build report through pipeline report = Canon::Diff::DiffReportBuilder.build( diff_lines, show_diffs: @show_diffs, context_lines: @context_lines, grouping_lines: @diff_grouping_lines, ) # #85/#86: DiffNodes the enricher could not locate were # previously dropped silently — the absorption mechanism. # Their serialized content renders as a trailing context so # the change is always visible, without perturbing the # located walk's line accounting. append_unlocated_context(report) # Layer 6: Format the report format_report(report, doc1, doc2) end |
#parent_chain(path) ⇒ Object
Display chain of a DiffNode's ancestor elements, e.g. "bibitem > formattedref" — gives the blank-numbered unlocated lines a readable home (#86).
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 |
# File 'lib/canon/diff_formatter/by_line/xml_formatter.rb', line 169 def parent_chain(path) return nil if path.nil? segments = path.split("/").reject(&:empty?) return nil if segments.length < 2 chain = segments[0...-1].filter_map do |seg| seg[/\A(?:\{[^}]+\})?([a-zA-Z0-9_:-]+)/, 1] end # Comparator paths repeat the element name before the node # segment ("formattedref/formattedref/text()") — collapse # consecutive repeats for display. collapsed = chain.each_with_object([]) do |name, acc| acc << name unless acc.last == name end collapsed.join(" > ") end |
#preceding_located(diff_node) ⇒ Object
The nearest preceding node (in @differences walk order) that the enricher DID locate.
189 190 191 192 193 194 195 196 197 198 |
# File 'lib/canon/diff_formatter/by_line/xml_formatter.rb', line 189 def preceding_located(diff_node) index = @differences.index(diff_node) return nil unless index (index - 1).downto(0) do |i| dn = @differences[i] return dn if dn.char_ranges && !dn.char_ranges.empty? end nil end |
#unlocated_lines(diff_node) ⇒ Object
Mini-diff of one unlocated node's serialized sides: shared lines render as :unchanged context instead of remove-all + add-all. Blank line numbers throughout — no located position.
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 |
# File 'lib/canon/diff_formatter/by_line/xml_formatter.rb', line 116 def unlocated_lines(diff_node) before = diff_node.serialized_before&.split("\n") || [] after = diff_node.serialized_after&.split("\n") || [] fmt = diff_node.formatting? lines = [] header = parent_chain(diff_node.path) if header lines << Canon::Diff::DiffLine.new( line_number: nil, new_position: nil, content: header, type: :location_header ) end require "diff/lcs" unless defined?(::Diff::LCS) ::Diff::LCS.sdiff(before, after).each do |change| case change.action when "=" lines << Canon::Diff::DiffLine.new( line_number: nil, new_position: nil, content: change.old_element, type: :unchanged, diff_node: diff_node ) when "-" lines << Canon::Diff::DiffLine.new( line_number: nil, new_position: nil, content: change.old_element, type: :removed, diff_node: diff_node, formatting: fmt ) when "+" lines << Canon::Diff::DiffLine.new( line_number: nil, new_position: nil, content: change.new_element, type: :added, diff_node: diff_node, formatting: fmt ) when "!" lines << Canon::Diff::DiffLine.new( line_number: nil, new_position: nil, content: change.old_element, type: :removed, diff_node: diff_node, formatting: fmt ) lines << Canon::Diff::DiffLine.new( line_number: nil, new_position: nil, content: change.new_element, type: :added, diff_node: diff_node, formatting: fmt ) end end lines end |