Module: Crimson::Tools::DiffUtil

Defined in:
lib/crimson/tools/diff_util.rb

Overview

Diff utility using the diff/lcs library with ANSI-colored output.

Class Method Summary collapse

Class Method Details

.format_diff(old_text, new_text, path) ⇒ String

Produce a colored unified-format diff between two texts.

Parameters:

  • old_text (String)

    original content

  • new_text (String)

    new content

  • path (String)

    file path for header display

Returns:

  • (String)

    ANSI-colored diff output



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/crimson/tools/diff_util.rb', line 15

def self.format_diff(old_text, new_text, path)
  pastel = Pastel.new
  old_lines = old_text.lines.map(&:chomp)
  new_lines = new_text.lines.map(&:chomp)

  changes = Diff::LCS.sdiff(old_lines, new_lines)

  output = []
  output << pastel.dim("--- #{path}")
  output << pastel.dim("+++ #{path}")

  changes.each do |change|
    case change.action
    when "-"
      output << pastel.red("- #{change.old_element}")
    when "+"
      output << pastel.green("+ #{change.new_element}")
    when "!"
      output << pastel.red("- #{change.old_element}")
      output << pastel.green("+ #{change.new_element}")
    when "="
      output << pastel.dim("  #{change.old_element}")
    end
  end

  output.join("\n")
end