merge_request_diff.rb 8.32 KB
Newer Older
1
class MergeRequestDiff < ActiveRecord::Base
2
  include Sortable
3
  include Importable
Robert Speicher's avatar
Robert Speicher committed
4
  include Gitlab::Git::EncodingHelper
5

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

9
  # Valid types of serialized diffs allowed by Gitlab::Git::Diff
Douwe Maan's avatar
Douwe Maan committed
10
  VALID_CLASSES = [Hash, Rugged::Patch, Rugged::Diff::Delta].freeze
11

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
  scope :with_diff_refs, ->(diff_refs) { where(start_commit_sha: diff_refs.start_sha, head_commit_sha: diff_refs.head_sha, base_commit_sha: diff_refs.base_sha) }
30

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

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

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

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

  def ensure_commits_sha
54
    merge_request.fetch_ref
55
    self.start_commit_sha ||= merge_request.target_branch_sha
56
    self.head_commit_sha  ||= merge_request.source_branch_sha
57
    self.base_commit_sha  ||= find_base_sha
58 59 60 61 62 63 64 65 66 67 68
    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
69 70
  end

71 72 73 74 75 76 77
  # 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

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

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

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

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

104 105 106 107
  def last_commit
    commits.first
  end

108 109 110 111
  def first_commit
    commits.last
  end

112
  def base_commit
113
    return unless base_commit_sha
114

115
    project.commit(base_commit_sha)
116 117
  end

118
  def start_commit
119
    return unless start_commit_sha
120

121
    project.commit(start_commit_sha)
122 123 124
  end

  def head_commit
125
    return unless head_commit_sha
126

127
    project.commit(head_commit_sha)
128 129
  end

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

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

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

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

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

  def project
    merge_request.target_project
  end
155

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

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

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

177 178 179 180
  def commits_count
    st_commits.count
  end

181 182 183 184 185 186 187 188 189 190
  def utf8_st_diffs
    return [] if st_diffs.blank?

    st_diffs.map do |diff|
      diff.each do |k, v|
        diff[k] = encode_utf8(v) if v.respond_to?(:encoding)
      end
    end
  end

191 192
  private

193 194 195 196 197 198 199 200 201
  # 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

202 203 204 205 206 207 208 209
  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

210
  # Load all commits related to current merge request diff from repo
211
  # and save it as array of hashes in st_commits db field
212
  def save_commits
213 214
    new_attributes = {}

215
    commits = compare.commits
216

217 218 219
    if commits.present?
      commits = Commit.decorate(commits, merge_request.source_project).reverse
      new_attributes[:st_commits] = dump_commits(commits)
220 221
    end

222
    update_columns_serialized(new_attributes)
223 224
  end

225 226 227 228 229 230 231
  def dump_diffs(diffs)
    if diffs.respond_to?(:map)
      diffs.map(&:to_hash)
    end
  end

  def load_diffs(raw, options)
232
    if valid_raw_diff?(raw)
233
      if paths = options[:paths]
234
        raw = raw.select do |diff|
235
          paths.include?(diff[:old_path]) || paths.include?(diff[:new_path])
236 237 238
        end
      end

239 240 241 242 243 244
      Gitlab::Git::DiffCollection.new(raw, options)
    else
      Gitlab::Git::DiffCollection.new([])
    end
  end

245
  # Load diffs between branches related to current merge request diff from repo
246
  # and save it as array of hashes in st_diffs db field
247
  def save_diffs
248
    new_attributes = {}
249 250

    if commits.size.zero?
251
      new_attributes[:state] = :empty
252
    else
253
      diff_collection = compare.diffs(Commit.max_diff_options)
254
      new_attributes[:real_size] = compare.diffs.real_size
255

256 257
      if diff_collection.any?
        new_diffs = dump_diffs(diff_collection)
258
        new_attributes[:state] = :collected
259
      end
260 261 262 263 264 265 266 267 268

      new_attributes[:st_diffs] = new_diffs || []

      # Set our state to 'overflow' to make the #empty? and #collected?
      # methods (generated by StateMachine) return false.
      #
      # This attribution has to come at the end of the method so 'overflow'
      # state does not get overridden by 'collected'.
      new_attributes[:state] = :overflow if diff_collection.overflow?
269
    end
270

271
    update_columns_serialized(new_attributes)
272 273 274
  end

  def repository
275
    project.repository
276
  end
277

278 279
  def find_base_sha
    return unless head_commit_sha && start_commit_sha
280

281
    project.merge_base_commit(head_commit_sha, start_commit_sha).try(:sha)
282 283
  end

284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
  #
  # #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
306

307
  def keep_around_commits
308 309 310 311 312
    [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
313
  end
314
end