BigW Consortium Gitlab

merge_request_diff.rb 2.52 KB
Newer Older
1 2 3
module Gitlab
  module Diff
    module FileCollection
4 5 6
      class MergeRequestDiff < Base
        def initialize(merge_request_diff, diff_options:)
          @merge_request_diff = merge_request_diff
7

8 9
          super(merge_request_diff,
            project: merge_request_diff.project,
10
            diff_options: diff_options,
11 12
            diff_refs: merge_request_diff.diff_refs,
            fallback_diff_refs: merge_request_diff.fallback_diff_refs)
13 14 15 16 17
        end

        def diff_files
          super.tap { |_| store_highlight_cache }
        end
18 19 20 21

        def real_size
          @merge_request_diff.real_size
        end
22 23 24

        private

25
        # Extracted method to highlight in the same iteration to the diff_collection.
26
        def decorate_diff!(diff)
27
          diff_file = super
28
          cache_highlight!(diff_file) if cacheable?(diff_file)
29
          diff_file
30 31 32 33 34 35 36 37 38 39 40 41 42
        end

        def highlight_diff_file_from_cache!(diff_file, cache_diff_lines)
          diff_file.highlighted_diff_lines = cache_diff_lines.map do |line|
            Gitlab::Diff::Line.init_from_hash(line)
          end
        end

        #
        # If we find the highlighted diff files lines on the cache we replace existing diff_files lines (no highlighted)
        # for the highlighted ones, so we just skip their execution.
        # If the highlighted diff files lines are not cached we calculate and cache them.
        #
43
        # The content of the cache is a Hash where the key identifies the file and the values are Arrays of
44 45 46
        # hashes that represent serialized diff lines.
        #
        def cache_highlight!(diff_file)
47
          item_key = diff_file.file_identifier
48

49 50
          if highlight_cache[item_key]
            highlight_diff_file_from_cache!(diff_file, highlight_cache[item_key])
51
          else
52
            highlight_cache[item_key] = diff_file.highlighted_diff_lines.map(&:to_hash)
53 54 55 56 57 58 59
          end
        end

        def highlight_cache
          return @highlight_cache if defined?(@highlight_cache)

          @highlight_cache = Rails.cache.read(cache_key) || {}
60
          @highlight_cache_was_empty = @highlight_cache.empty?
61 62 63 64 65 66 67
          @highlight_cache
        end

        def store_highlight_cache
          Rails.cache.write(cache_key, highlight_cache) if @highlight_cache_was_empty
        end

68
        def cacheable?(diff_file)
69
          @merge_request_diff.present? && diff_file.text? && diff_file.diffable?
70 71 72
        end

        def cache_key
73
          [@merge_request_diff, 'highlighted-diff-files', diff_options]
74 75 76 77 78
        end
      end
    end
  end
end