summaryrefslogtreecommitdiff
path: root/lib/gitlab/discussions_diff/file_collection.rb
blob: 60b3a1738f1bc353646d4fd80b139c1a98c7a31e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# frozen_string_literal: true

module Gitlab
  module DiscussionsDiff
    class FileCollection
      include Gitlab::Utils::StrongMemoize
      include Enumerable

      def initialize(collection)
        @collection = collection
      end

      def each(&block)
        @collection.each(&block)
      end

      # Returns a Gitlab::Diff::File with the given ID (`unique_identifier` in
      # Gitlab::Diff::File).
      def find_by_id(id)
        diff_files_indexed_by_id[id]
      end

      # Writes cache and preloads highlighted diff lines for
      # highlightable object IDs, in @collection.
      #
      # - Highlight cache is written just for uncached diff files
      # - The cache content is not updated (there's no need to do so)
      def load_highlight
        ids = highlightable_collection_ids
        return if ids.empty?

        cached_content = read_cache(ids)

        uncached_ids = ids.select.each_with_index { |_, i| cached_content[i].nil? }
        mapping = highlighted_lines_by_ids(uncached_ids)

        HighlightCache.write_multiple(mapping) if mapping.any?

        diffs = diff_files_indexed_by_id.values_at(*ids)

        diffs.zip(cached_content).each do |diff, cached_lines|
          next unless diff && cached_lines

          diff.highlighted_diff_lines = cached_lines
        end
      end

      private

      def highlightable_collection_ids
        each.with_object([]) { |file, memo| memo << file.id unless file.resolved_at }
      end

      def read_cache(ids)
        HighlightCache.read_multiple(ids)
      end

      def diff_files_indexed_by_id
        strong_memoize(:diff_files_indexed_by_id) do
          diff_files.index_by(&:unique_identifier)
        end
      end

      def diff_files
        strong_memoize(:diff_files) { map(&:raw_diff_file) }
      end

      # Processes the diff lines highlighting for diff files matching the given
      # IDs.
      #
      # Returns a Hash with { id => [Array of Gitlab::Diff::line], ...]
      def highlighted_lines_by_ids(ids)
        diff_files_indexed_by_id.slice(*ids).transform_values do |file|
          file.highlighted_diff_lines.map(&:to_hash)
        end
      end
    end
  end
end