highlight.rb 2.05 KB
Newer Older
1 2 3
module Gitlab
  module Diff
    class Highlight
4
      attr_reader :diff_file, :diff_lines, :raw_lines, :repository
5

6
      delegate :old_path, :new_path, :old_sha, :new_sha, to: :diff_file, prefix: :diff
7

8 9 10
      def initialize(diff_lines, repository: nil)
        @repository = repository

11
        if diff_lines.is_a?(Gitlab::Diff::File)
Douwe Maan's avatar
Fix  
Douwe Maan committed
12 13
          @diff_file = diff_lines
          @diff_lines = @diff_file.diff_lines
14 15 16
        else
          @diff_lines = diff_lines
        end
17
        @raw_lines = @diff_lines.map(&:text)
18 19
      end

20
      def highlight
Douwe Maan's avatar
Douwe Maan committed
21 22
        @diff_lines.map.with_index do |diff_line, i|
          diff_line = diff_line.dup
23
          # ignore highlighting for "match" lines
24
          next diff_line if diff_line.meta?
25

26
          rich_line = highlight_line(diff_line) || diff_line.text
27 28 29 30 31

          if line_inline_diffs = inline_diffs[i]
            rich_line = InlineDiffMarker.new(diff_line.text, rich_line).mark(line_inline_diffs)
          end

32
          diff_line.text = rich_line
33

Douwe Maan's avatar
Douwe Maan committed
34 35
          diff_line
        end
36 37
      end

38 39
      private

40 41
      def highlight_line(diff_line)
        return unless diff_file && diff_file.diff_refs
42

43 44 45 46 47 48
        rich_line =
          if diff_line.unchanged? || diff_line.added?
            new_lines[diff_line.new_pos - 1]
          elsif diff_line.removed?
            old_lines[diff_line.old_pos - 1]
          end
49 50 51

        # Only update text if line is found. This will prevent
        # issues with submodules given the line only exists in diff content.
52
        if rich_line
53
          line_prefix = diff_line.text =~ /\A(.)/ ? $1 : ' '
54 55
          "#{line_prefix}#{rich_line}".html_safe
        end
56 57
      end

58
      def inline_diffs
59
        @inline_diffs ||= InlineDiff.for_lines(@raw_lines)
60 61
      end

62
      def old_lines
63
        return unless diff_file
64
        @old_lines ||= Gitlab::Highlight.highlight_lines(self.repository, diff_old_sha, diff_old_path)
65 66 67
      end

      def new_lines
68
        return unless diff_file
69
        @new_lines ||= Gitlab::Highlight.highlight_lines(self.repository, diff_new_sha, diff_new_path)
70
      end
71 72 73
    end
  end
end