base.rb 2.24 KB
Newer Older
1 2 3 4
module Gitlab
  module Diff
    module FileCollection
      class Base
5 6
        include Gitlab::Utils::StrongMemoize

7
        attr_reader :project, :diff_options, :diff_refs, :fallback_diff_refs, :diffable
8 9 10

        delegate :count, :size, :real_size, to: :diff_files

11
        def self.default_options
12
          ::Commit.max_diff_options.merge(ignore_whitespace_change: false, expanded: false, include_stats: true)
13 14
        end

15
        def initialize(diffable, project:, diff_options: nil, diff_refs: nil, fallback_diff_refs: nil)
16 17
          diff_options = self.class.default_options.merge(diff_options || {})

18
          @diffable = diffable
19
          @include_stats = diff_options.delete(:include_stats)
20 21
          @diffs = diffable.raw_diffs(diff_options)
          @project = project
22
          @diff_options = diff_options
23 24
          @diff_refs = diff_refs
          @fallback_diff_refs = fallback_diff_refs
25
          @repository = project.repository
26 27 28
        end

        def diff_files
29
          @diff_files ||= @diffs.decorate! { |diff| decorate_diff!(diff) }
30 31
        end

32 33 34 35 36 37 38 39
        def diff_file_with_old_path(old_path)
          diff_files.find { |diff_file| diff_file.old_path == old_path }
        end

        def diff_file_with_new_path(new_path)
          diff_files.find { |diff_file| diff_file.new_path == new_path }
        end

40 41 42 43 44 45 46 47
        def clear_cache
          # No-op
        end

        def write_cache
          # No-op
        end

48 49
        private

50 51 52 53 54 55 56 57 58 59 60
        def diff_stats_collection
          strong_memoize(:diff_stats) do
            # There are scenarios where we don't need to request Diff Stats,
            # when caching for instance.
            next unless @include_stats
            next unless diff_refs

            @repository.diff_stats(diff_refs.base_sha, diff_refs.head_sha)
          end
        end

61
        def decorate_diff!(diff)
62 63
          return diff if diff.is_a?(File)

64 65 66 67 68 69 70
          stats = diff_stats_collection&.find_by_path(diff.new_path)

          Gitlab::Diff::File.new(diff,
                                 repository: project.repository,
                                 diff_refs: diff_refs,
                                 fallback_diff_refs: fallback_diff_refs,
                                 stats: stats)
71 72 73 74 75
        end
      end
    end
  end
end