1# frozen_string_literal: true 2 3require 'set' 4 5class Compare 6 include Gitlab::Utils::StrongMemoize 7 include ActsAsPaginatedDiff 8 9 delegate :same, :head, :base, to: :@compare 10 11 attr_reader :project 12 13 def self.decorate(compare, project) 14 if compare.is_a?(Compare) 15 compare 16 else 17 self.new(compare, project) 18 end 19 end 20 21 def initialize(compare, project, base_sha: nil, straight: false) 22 @compare = compare 23 @project = project 24 @base_sha = base_sha 25 @straight = straight 26 end 27 28 # Return a Hash of parameters for passing to a URL helper 29 # 30 # See `namespace_project_compare_url` 31 def to_param 32 { 33 from: @straight ? start_commit_sha : base_commit_sha, 34 to: head_commit_sha 35 } 36 end 37 38 def cache_key 39 [@project, :compare, diff_refs.hash] 40 end 41 42 def commits 43 @commits ||= Commit.decorate(@compare.commits, project) 44 end 45 46 def start_commit 47 strong_memoize(:start_commit) do 48 commit = @compare.base 49 50 ::Commit.new(commit, project) if commit 51 end 52 end 53 54 def head_commit 55 strong_memoize(:head_commit) do 56 commit = @compare.head 57 58 ::Commit.new(commit, project) if commit 59 end 60 end 61 alias_method :commit, :head_commit 62 63 def start_commit_sha 64 start_commit&.sha 65 end 66 67 def base_commit_sha 68 strong_memoize(:base_commit) do 69 next unless start_commit && head_commit 70 71 @base_sha || project.merge_base_commit(start_commit.id, head_commit.id)&.sha 72 end 73 end 74 75 def head_commit_sha 76 commit&.sha 77 end 78 79 def raw_diffs(*args) 80 @compare.diffs(*args) 81 end 82 83 def diffs(diff_options = nil) 84 Gitlab::Diff::FileCollection::Compare.new(self, 85 project: project, 86 diff_options: diff_options, 87 diff_refs: diff_refs) 88 end 89 90 def diff_refs 91 Gitlab::Diff::DiffRefs.new( 92 base_sha: @straight ? start_commit_sha : base_commit_sha, 93 start_sha: start_commit_sha, 94 head_sha: head_commit_sha 95 ) 96 end 97 98 def modified_paths 99 paths = Set.new 100 diffs.diff_files.each do |diff| 101 paths.add diff.old_path 102 paths.add diff.new_path 103 end 104 paths.to_a 105 end 106end 107