BigW Consortium Gitlab

merge_request_diff.rb 8 KB
Newer Older
1
class MergeRequestDiff < ActiveRecord::Base
2
  include Sortable
3
  include Importable
4
  include EncodingHelper
5

6
  # Prevent store of diff if commits amount more then 500
7
  COMMITS_SAFE_SIZE = 100
8

9 10 11
  # Valid types of serialized diffs allowed by Gitlab::Git::Diff
  VALID_CLASSES = [Hash, Rugged::Patch, Rugged::Diff::Delta]

12 13
  belongs_to :merge_request

14 15 16
  serialize :st_commits
  serialize :st_diffs

17 18
  state_machine :state, initial: :empty do
    state :collected
19 20 21
    state :overflow
    # Deprecated states: these are no longer used but these values may still occur
    # in the database.
22 23 24 25 26 27
    state :timeout
    state :overflow_commits_safe_size
    state :overflow_diff_files_limit
    state :overflow_diff_lines_limit
  end

28
  scope :viewable, -> { without_state(:empty) }
29

30 31
  # All diff information is collected from repository after object is created.
  # It allows you to override variables like head_commit_sha before getting diff.
32
  after_create :save_git_content, unless: :importing?
33

34 35 36 37
  def self.select_without_diff
    select(column_names - ['st_diffs'])
  end

38 39 40 41
  def st_commits
    super || []
  end

42 43 44
  # Collect information about commits and diff from repository
  # and save it to the database as serialized data
  def save_git_content
45
    ensure_commits_sha
46
    save_commits
47
    reload_commits
48
    save_diffs
49 50 51 52
    keep_around_commits
  end

  def ensure_commits_sha
53
    merge_request.fetch_ref
54
    self.start_commit_sha ||= merge_request.target_branch_sha
55
    self.head_commit_sha  ||= merge_request.source_branch_sha
56
    self.base_commit_sha  ||= find_base_sha
57 58 59 60 61 62 63 64 65 66 67
    save
  end

  # Override head_commit_sha to keep compatibility with merge request diff
  # created before version 8.4 that does not store head_commit_sha in separate db field.
  def head_commit_sha
    if persisted? && super.nil?
      last_commit.try(:sha)
    else
      super
    end
68 69
  end

70 71 72 73 74 75 76
  # This method will rely on repository branch sha
  # in case start_commit_sha is nil. Its necesarry for old merge request diff
  # created before version 8.4 to work
  def safe_start_commit_sha
    start_commit_sha || merge_request.target_branch_sha
  end

77
  def size
78
    real_size.presence || raw_diffs.size
79 80
  end

81
  def raw_diffs(options = {})
82
    if options[:ignore_whitespace_change]
83
      @diffs_no_whitespace ||=
84 85 86
        Gitlab::Git::Compare.new(
          repository.raw_repository,
          safe_start_commit_sha,
87
          head_commit_sha).diffs(options)
88
    else
89 90
      @raw_diffs ||= {}
      @raw_diffs[options] ||= load_diffs(st_diffs, options)
91
    end
92 93
  end

94
  def commits
95
    @commits ||= load_commits(st_commits)
96 97
  end

98 99 100 101 102
  def reload_commits
    @commits = nil
    commits
  end

103 104 105 106
  def last_commit
    commits.first
  end

107 108 109 110
  def first_commit
    commits.last
  end

111
  def base_commit
112
    return unless base_commit_sha
113

114
    project.commit(base_commit_sha)
115 116
  end

117
  def start_commit
118
    return unless start_commit_sha
119

120
    project.commit(start_commit_sha)
121 122 123
  end

  def head_commit
124
    return unless head_commit_sha
125

126
    project.commit(head_commit_sha)
127 128
  end

129
  def commits_sha
130
    st_commits.map { |commit| commit[:id] }
131 132
  end

133
  def diff_refs
134
    return unless start_commit_sha || base_commit_sha
135 136 137 138 139 140 141 142

    Gitlab::Diff::DiffRefs.new(
      base_sha:  base_commit_sha,
      start_sha: start_commit_sha,
      head_sha:  head_commit_sha
    )
  end

143 144 145 146
  def diff_refs_by_sha?
    base_commit_sha? && head_commit_sha? && start_commit_sha?
  end

147 148 149 150 151 152 153
  def diffs(diff_options = nil)
    Gitlab::Diff::FileCollection::MergeRequestDiff.new(self, diff_options: diff_options)
  end

  def project
    merge_request.target_project
  end
154

155 156
  def compare
    @compare ||=
157 158 159 160 161
      Gitlab::Git::Compare.new(
        repository.raw_repository,
        safe_start_commit_sha,
        head_commit_sha
      )
162 163
  end

164 165 166 167
  def latest?
    self == merge_request.merge_request_diff
  end

168
  def compare_with(sha, straight: true)
169
    # When compare merge request versions we want diff A..B instead of A...B
170
    # so we handle cases when user does squash and rebase of the commits between versions.
171
    # For this reason we set straight to true by default.
172
    CompareService.new.execute(project, head_commit_sha, project, sha, straight: straight)
173 174
  end

175 176 177 178
  def commits_count
    st_commits.count
  end

179 180
  private

181 182 183 184 185 186 187 188 189
  # Old GitLab implementations may have generated diffs as ["--broken-diff"].
  # Avoid an error 500 by ignoring bad elements. See:
  # https://gitlab.com/gitlab-org/gitlab-ce/issues/20776
  def valid_raw_diff?(raw)
    return false unless raw.respond_to?(:each)

    raw.any? { |element| VALID_CLASSES.include?(element.class) }
  end

190 191 192 193 194 195 196 197
  def dump_commits(commits)
    commits.map(&:to_hash)
  end

  def load_commits(array)
    array.map { |hash| Commit.new(Gitlab::Git::Commit.new(hash), merge_request.source_project) }
  end

198
  # Load all commits related to current merge request diff from repo
199
  # and save it as array of hashes in st_commits db field
200
  def save_commits
201 202
    new_attributes = {}

203
    commits = compare.commits
204

205 206 207
    if commits.present?
      commits = Commit.decorate(commits, merge_request.source_project).reverse
      new_attributes[:st_commits] = dump_commits(commits)
208 209
    end

210
    update_columns_serialized(new_attributes)
211 212
  end

213 214 215 216 217 218 219
  def dump_diffs(diffs)
    if diffs.respond_to?(:map)
      diffs.map(&:to_hash)
    end
  end

  def load_diffs(raw, options)
220
    if valid_raw_diff?(raw)
221
      if paths = options[:paths]
222
        raw = raw.select do |diff|
223
          paths.include?(diff[:old_path]) || paths.include?(diff[:new_path])
224 225 226
        end
      end

227 228 229 230 231 232
      Gitlab::Git::DiffCollection.new(raw, options)
    else
      Gitlab::Git::DiffCollection.new([])
    end
  end

233
  # Load diffs between branches related to current merge request diff from repo
234
  # and save it as array of hashes in st_diffs db field
235
  def save_diffs
236
    new_attributes = {}
237 238 239
    new_diffs = []

    if commits.size.zero?
240
      new_attributes[:state] = :empty
241
    else
242
      diff_collection = compare.diffs(Commit.max_diff_options)
243

244 245 246
      if diff_collection.overflow?
        # Set our state to 'overflow' to make the #empty? and #collected?
        # methods (generated by StateMachine) return false.
247
        new_attributes[:state] = :overflow
248 249
      end

250
      new_attributes[:real_size] = diff_collection.real_size
251

252 253
      if diff_collection.any?
        new_diffs = dump_diffs(diff_collection)
254
        new_attributes[:state] = :collected
255
      end
256
    end
257

258 259
    new_attributes[:st_diffs] = new_diffs
    update_columns_serialized(new_attributes)
260 261 262
  end

  def repository
263
    project.repository
264
  end
265

266 267
  def find_base_sha
    return unless head_commit_sha && start_commit_sha
268

269
    project.merge_base_commit(head_commit_sha, start_commit_sha).try(:sha)
270 271
  end

272 273 274 275 276 277 278 279
  def utf8_st_diffs
    st_diffs.map do |diff|
      diff.each do |k, v|
        diff[k] = encode_utf8(v) if v.respond_to?(:encoding)
      end
    end
  end

280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
  #
  # #save or #update_attributes providing changes on serialized attributes do a lot of
  # serialization and deserialization calls resulting in bad performance.
  # Using #update_columns solves the problem with just one YAML.dump per serialized attribute that we provide.
  # As a tradeoff we need to reload the current instance to properly manage time objects on those serialized
  # attributes. So to keep the same behaviour as the attribute assignment we reload the instance.
  # The difference is in the usage of
  # #write_attribute= (#update_attributes) and #raw_write_attribute= (#update_columns)
  #
  # Ex:
  #
  #   new_attributes[:st_commits].first.slice(:committed_date)
  #   => {:committed_date=>2014-02-27 11:01:38 +0200}
  #   YAML.load(YAML.dump(new_attributes[:st_commits].first.slice(:committed_date)))
  #   => {:committed_date=>2014-02-27 10:01:38 +0100}
  #
  def update_columns_serialized(new_attributes)
    return unless new_attributes.any?

    update_columns(new_attributes.merge(updated_at: current_time_from_proper_timezone))
    reload
  end
302

303
  def keep_around_commits
304 305 306 307 308
    [repository, merge_request.source_project.repository].each do |repo|
      repo.keep_around(start_commit_sha)
      repo.keep_around(head_commit_sha)
      repo.keep_around(base_commit_sha)
    end
309
  end
310
end