Class: Gitlab::Diff::CharDiff

Inherits:
Object
  • Object
show all
Includes:
Utils::StrongMemoize
Defined in:
lib/gitlab/diff/char_diff.rb

Instance Method Summary collapse

Constructor Details

#initialize(old_string, new_string) ⇒ CharDiff

Returns a new instance of CharDiff.



8
9
10
11
12
# File 'lib/gitlab/diff/char_diff.rb', line 8

def initialize(old_string, new_string)
  @old_string = old_string.to_s
  @new_string = new_string.to_s
  @changes = []
end

Instance Method Details

#changed_ranges(offset: 0) ⇒ Object



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
# File 'lib/gitlab/diff/char_diff.rb', line 21

def changed_ranges(offset: 0)
  old_diffs = []
  new_diffs = []
  new_pointer = old_pointer = offset

  generate_diff.each do |(action, content)|
    content_size = content.size

    if action == :equal
      new_pointer += content_size
      old_pointer += content_size
    end

    if action == :delete
      old_diffs << MarkerRange.new(old_pointer, old_pointer + content_size - 1, mode: MarkerRange::DELETION)
      old_pointer += content_size
    end

    if action == :insert
      new_diffs << MarkerRange.new(new_pointer, new_pointer + content_size - 1, mode: MarkerRange::ADDITION)
      new_pointer += content_size
    end
  end

  [old_diffs, new_diffs]
end

#generate_diffObject



14
15
16
17
18
19
# File 'lib/gitlab/diff/char_diff.rb', line 14

def generate_diff
  @changes = diff_match_patch.diff_main(@old_string, @new_string)
  diff_match_patch.diff_cleanupSemantic(@changes)

  @changes
end

#to_htmlObject



48
49
50
51
52
# File 'lib/gitlab/diff/char_diff.rb', line 48

def to_html
  @changes.map do |op, text|
    %(<span class="#{html_class_names(op)}">#{ERB::Util.html_escape(text)}</span>)
  end.join.html_safe
end