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 ("      Strings have different encodings:\n        \#{a.value.encoding.inspect} != \#{b.value.encoding.inspect}\n    MSG\n      # makes it stand out a bit more from the red of rspec output\n      reset_color(line)\n    end\n  end\n\n  diff = \"\"\n\n  # if there are no newlines then the text differ doesn't produce any valuable\n  # output. \"word diffing\" would improve this case.\n  if a_value.count(NEWLINE) <= 1 && b_value.count(NEWLINE) <= 1\n    return diff\n  end\n\n  a_lines = a_value.split(NEWLINE).map! { _1.chomp }\n  b_lines = b_value.split(NEWLINE).map! { _1.chomp }\n\n  file_length_difference = 0\n\n  hunks = ::Diff::LCS.diff(a_lines, b_lines).map do |piece|\n    ::Diff::LCS::Hunk.new(\n      a_lines, b_lines, piece, CONTEXT_LINES, file_length_difference,\n    ).tap { |hunk| file_length_difference = hunk.file_length_difference }\n  end\n\n  hunks.each_cons(2) do |prev_hunk, current_hunk|\n    begin\n      if current_hunk.overlaps?(prev_hunk)\n        current_hunk.merge(prev_hunk)\n      else\n        diff << prev_hunk.diff(:unified)\n      end\n    ensure\n      diff << NEWLINE\n    end\n  end\n\n  if hunks.last\n    diff << NEWLINE\n    diff << hunks.last.diff(:unified)\n  end\n\n  return diff if diff == \"\"\n\n  diff << NEWLINE\n  diff.lstrip!\n\n  return colorize_by_line(diff) do |line|\n    case line[0].chr\n    when \"+\"\n      green(line)\n    when \"-\"\n      red(line)\n    when \"@\"\n      if line[1].chr == \"@\"\n        cyan(line)\n      else\n        reset_color(line)\n      end\n    else\n      reset_color(line)\n    end\n  end\nend\n") do |line|

.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