Class: Gitlab::StringRangeMarker

Inherits:
Object
  • Object
show all
Defined in:
lib/gitlab/string_range_marker.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(raw_line, rich_line = nil) ⇒ StringRangeMarker

Returns a new instance of StringRangeMarker.


7
8
9
10
11
12
13
14
15
16
# File 'lib/gitlab/string_range_marker.rb', line 7

def initialize(raw_line, rich_line = nil)
  @raw_line = raw_line.dup
  if rich_line.nil?
    @rich_line = raw_line.dup
    @html_escaped = false
  else
    @rich_line = ERB::Util.html_escape(rich_line)
    @html_escaped = true
  end
end

Instance Attribute Details

#html_escapedObject

Returns the value of attribute html_escaped.


5
6
7
# File 'lib/gitlab/string_range_marker.rb', line 5

def html_escaped
  @html_escaped
end

#raw_lineObject

Returns the value of attribute raw_line.


5
6
7
# File 'lib/gitlab/string_range_marker.rb', line 5

def raw_line
  @raw_line
end

#rich_lineObject

Returns the value of attribute rich_line.


5
6
7
# File 'lib/gitlab/string_range_marker.rb', line 5

def rich_line
  @rich_line
end

Instance Method Details

#mark(ranges) ⇒ Object


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
# File 'lib/gitlab/string_range_marker.rb', line 18

def mark(ranges)
  return rich_line unless ranges&.any?

  marker_ranges = ranges.map { |range| Gitlab::MarkerRange.from_range(range) }

  if html_escaped
    rich_marker_ranges = []
    marker_ranges.each do |range|
      # Map the inline-diff range based on the raw line to character positions in the rich line
      rich_positions = position_mapping[range].flatten
      # Turn the array of character positions into ranges
      rich_marker_ranges.concat(collapse_ranges(rich_positions, range.mode))
    end
  else
    rich_marker_ranges = marker_ranges
  end

  offset = 0
  # Mark each range
  rich_marker_ranges.each_with_index do |range, i|
    offset_range = (range.begin + offset)..(range.end + offset)
    original_text = rich_line[offset_range]

    text = yield(original_text, left: i == 0, right: i == rich_marker_ranges.length - 1, mode: range.mode)

    rich_line[offset_range] = text

    offset += text.length - original_text.length
  end

  @html_escaped ? rich_line.html_safe : rich_line
end