BigW Consortium Gitlab

highlight.rb 2.13 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 committed
12 13
          @diff_file = diff_lines
          @diff_lines = @diff_file.diff_lines
14 15 16
        else
          @diff_lines = diff_lines
        end
17

18
        @raw_lines = @diff_lines.map(&:text)
19 20
      end

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

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

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

33
          diff_line.text = rich_line
34

Douwe Maan committed
35 36
          diff_line
        end
37 38
      end

39 40
      private

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

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

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

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

63
      def old_lines
64
        @old_lines ||= highlighted_blob_lines(diff_file.old_blob)
65 66 67
      end

      def new_lines
68 69 70 71 72 73 74 75
        @new_lines ||= highlighted_blob_lines(diff_file.new_blob)
      end

      def highlighted_blob_lines(blob)
        return [] unless blob

        blob.load_all_data!
        Gitlab::Highlight.highlight(blob.path, blob.data, repository: repository).lines
76
      end
77 78 79
    end
  end
end