Class: Specdiff::Differ::Text

Inherits:
Object
  • Object
show all
Extended by:
Colorize
Defined in:
lib/specdiff/differ/text.rb

Constant Summary collapse

NEWLINE =
"\n".freeze
CONTEXT_LINES =
3

Class Method Summary collapse

Methods included from Colorize

blue, colorize_by_line, cyan, green, red, reset_color, yellow

Class Method Details

.diff(a, b) ⇒ Object

this implementation is based on RSpec::Support::Differ github.com/rspec/rspec-support/blob/main/lib/rspec/support/differ.rb and also the hunk generator it uses



13
14
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
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
82
83
84
# File 'lib/specdiff/differ/text.rb', line 13

def self.diff(a, b)
  a_value = a.value
  b_value = b.value

  if a_value.encoding != b_value.encoding
    return (<<~MSG) do |line|
      Strings have different encodings:
        #{a.value.encoding.inspect} != #{b.value.encoding.inspect}
    MSG
      # makes it stand out a bit more from the red of rspec output
      reset_color(line)
    end
  end

  diff = ""

  # if there are no newlines then the text differ doesn't produce any valuable
  # output. "word diffing" would improve this case.
  if a_value.count(NEWLINE) <= 1 && b_value.count(NEWLINE) <= 1
    return diff
  end

  a_lines = a_value.split(NEWLINE).map! { _1.chomp }
  b_lines = b_value.split(NEWLINE).map! { _1.chomp }

  file_length_difference = 0

  hunks = ::Diff::LCS.diff(a_lines, b_lines).map do |piece|
    ::Diff::LCS::Hunk.new(
      a_lines, b_lines, piece, CONTEXT_LINES, file_length_difference,
    ).tap { |hunk| file_length_difference = hunk.file_length_difference }
  end

  hunks.each_cons(2) do |prev_hunk, current_hunk|
    begin
      if current_hunk.overlaps?(prev_hunk)
        current_hunk.merge(prev_hunk)
      else
        diff << prev_hunk.diff(:unified)
      end
    ensure
      diff << NEWLINE
    end
  end

  if hunks.last
    diff << NEWLINE
    diff << hunks.last.diff(:unified)
  end

  return diff if diff == ""

  diff << NEWLINE
  diff.lstrip!

  return (diff) do |line|
    case line[0].chr
    when "+"
      green(line)
    when "-"
      red(line)
    when "@"
      if line[1].chr == "@"
        cyan(line)
      else
        reset_color(line)
      end
    else
      reset_color(line)
    end
  end
end

.empty?(diff) ⇒ Boolean

Returns:

  • (Boolean)


86
87
88
# File 'lib/specdiff/differ/text.rb', line 86

def self.empty?(diff)
  diff.raw == ""
end

.stringify(diff) ⇒ Object



90
91
92
# File 'lib/specdiff/differ/text.rb', line 90

def self.stringify(diff)
  diff.raw
end