commit.rb 12.2 KB
Newer Older
1
# coding: utf-8
2 3
# frozen_string_literal: true

4
class Commit
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
5
  extend ActiveModel::Naming
6
  extend Gitlab::Cache::RequestCache
7 8

  include ActiveModel::Conversion
9
  include Noteable
10
  include Participable
11
  include Mentionable
12 13
  include Referable
  include StaticModel
14
  include Presentable
15
  include ::Gitlab::Utils::StrongMemoize
16

17
  attr_mentionable :safe_message, pipeline: :single_line
Yorick Peterse's avatar
Yorick Peterse committed
18 19 20 21

  participant :author
  participant :committer
  participant :notes_with_associations
Saito's avatar
Saito committed
22

23
  attr_accessor :project, :author
24 25
  attr_accessor :redacted_description_html
  attr_accessor :redacted_title_html
26
  attr_accessor :redacted_full_title_html
27
  attr_reader :gpg_commit
28

29
  DIFF_SAFE_LINES = Gitlab::Git::DiffCollection::DEFAULT_LIMITS[:max_lines]
30

31
  # Commits above this size will not be rendered in HTML
32 33
  DIFF_HARD_LIMIT_FILES = 1000
  DIFF_HARD_LIMIT_LINES = 50000
34

35
  MIN_SHA_LENGTH = Gitlab::Git::Commit::MIN_SHA_LENGTH
36
  COMMIT_SHA_PATTERN = /\h{#{MIN_SHA_LENGTH},40}/.freeze
37 38
  # Used by GFM to match and present link extensions on node texts and hrefs.
  LINK_EXTENSION_PATTERN = /(patch)/.freeze
39

40
  def banzai_render_context(field)
41 42
    pipeline = field == :description ? :commit_description : :single_line
    context = { pipeline: pipeline, project: self.project }
43
    context[:author] = self.author if self.author
44 45 46 47

    context
  end

48
  class << self
49
    def decorate(commits, project)
50
      commits.map do |commit|
Douwe Maan's avatar
Douwe Maan committed
51
        if commit.is_a?(Commit)
52 53
          commit
        else
54
          self.new(commit, project)
55 56
        end
      end
57
    end
58

59 60
    # Calculate number of lines to render for diffs
    def diff_line_count(diffs)
61
      diffs.reduce(0) { |sum, d| sum + Gitlab::Git::Util.count_lines(d.diff) }
62
    end
63

64 65 66 67 68 69 70 71 72 73 74 75 76 77
    def order_by(collection:, order_by:, sort:)
      return collection unless %w[email name commits].include?(order_by)
      return collection unless %w[asc desc].include?(sort)

      collection.sort do |a, b|
        operands = [a, b].tap { |o| o.reverse! if sort == 'desc' }

        attr1, attr2 = operands.first.public_send(order_by), operands.second.public_send(order_by) # rubocop:disable PublicSend

        # use case insensitive comparison for string values
        order_by.in?(%w[email name]) ? attr1.casecmp(attr2) : attr1 <=> attr2
      end
    end

78
    # Truncate sha to 8 characters
79
    def truncate_sha(sha)
80
      sha[0..MIN_SHA_LENGTH]
81
    end
82 83 84 85

    def max_diff_options
      {
        max_files: DIFF_HARD_LIMIT_FILES,
86
        max_lines: DIFF_HARD_LIMIT_LINES
87 88
      }
    end
89 90

    def from_hash(hash, project)
91 92
      raw_commit = Gitlab::Git::Commit.new(project.repository.raw, hash)
      new(raw_commit, project)
93
    end
94 95 96 97

    def valid_hash?(key)
      !!(/\A#{COMMIT_SHA_PATTERN}\z/ =~ key)
    end
98 99 100 101 102 103 104 105 106 107 108 109 110 111

    def lazy(project, oid)
      BatchLoader.for({ project: project, oid: oid }).batch do |items, loader|
        items_by_project = items.group_by { |i| i[:project] }

        items_by_project.each do |project, commit_ids|
          oids = commit_ids.map { |i| i[:oid] }

          project.repository.commits_by(oids: oids).each do |commit|
            loader.call({ project: commit.project, oid: commit.id }, commit) if commit
          end
        end
      end
    end
112 113 114 115

    def parent_class
      ::Project
    end
116 117
  end

118
  attr_accessor :raw
Nihad Abbasov's avatar
Nihad Abbasov committed
119

120
  def initialize(raw_commit, project)
121 122
    raise "Nil as raw commit passed" unless raw_commit

123
    @raw = raw_commit
124
    @project = project
125
    @statuses = {}
126
    @gpg_commit = Gitlab::Gpg::Commit.new(self) if project
127
  end
128

129
  def id
130
    raw.id
131 132
  end

133 134 135 136
  def project_id
    project.id
  end

Robert Speicher's avatar
Robert Speicher committed
137
  def ==(other)
138
    other.is_a?(self.class) && raw == other.raw
Robert Speicher's avatar
Robert Speicher committed
139 140
  end

141 142 143 144 145 146 147 148
  def self.reference_prefix
    '@'
  end

  # Pattern used to extract commit references from text
  #
  # This pattern supports cross-project references.
  def self.reference_pattern
149
    @reference_pattern ||= %r{
150
      (?:#{Project.reference_pattern}#{reference_prefix})?
151
      (?<commit>#{COMMIT_SHA_PATTERN})
152
    }x
153 154
  end

155
  def self.link_reference_pattern
156 157
    @link_reference_pattern ||=
      super("commit", /(?<commit>#{COMMIT_SHA_PATTERN})?(\.(?<extension>#{LINK_EXTENSION_PATTERN}))?/)
158 159
  end

160 161
  def to_reference(from = nil, full: false)
    commit_reference(from, id, full: full)
162 163
  end

164 165
  def reference_link_text(from = nil, full: false)
    commit_reference(from, short_id, full: full)
166 167
  end

168
  def diff_line_count
Douwe Maan's avatar
Douwe Maan committed
169
    @diff_line_count ||= Commit.diff_line_count(raw_diffs)
170 171 172
    @diff_line_count
  end

173 174 175
  # Returns the commits title.
  #
  # Usually, the commit title is the first line of the commit message.
176
  # In case this first line is longer than 100 characters, it is cut off
177
  # after 80 characters + `...`
178
  def title
179 180
    return full_title if full_title.length < 100

181 182 183
    # Use three dots instead of the ellipsis Unicode character because
    # some clients show the raw Unicode value in the merge commit.
    full_title.truncate(81, separator: ' ', omission: '...')
184
  end
185

186 187
  # Returns the full commits title
  def full_title
188
    @full_title ||=
Douwe Maan's avatar
Douwe Maan committed
189 190 191
      if safe_message.blank?
        no_commit_message
      else
192
        safe_message.split(/[\r\n]/, 2).first
Douwe Maan's avatar
Douwe Maan committed
193
      end
194 195
  end

196 197
  # Returns full commit message if title is truncated (greater than 99 characters)
  # otherwise returns commit message without first line
198
  def description
199
    return safe_message if full_title.length >= 100
200
    return no_commit_message if safe_message.blank?
201

202
    safe_message.split("\n", 2)[1].try(:chomp)
203
  end
204

205 206
  def description?
    description.present?
207 208
  end

Valery Sizov's avatar
Valery Sizov committed
209
  def hook_attrs(with_changed_files: false)
Valery Sizov's avatar
Valery Sizov committed
210
    data = {
Kirill Zaitsev's avatar
Kirill Zaitsev committed
211 212 213
      id: id,
      message: safe_message,
      timestamp: committed_date.xmlschema,
214
      url: Gitlab::UrlBuilder.build(self),
Kirill Zaitsev's avatar
Kirill Zaitsev committed
215 216 217 218 219
      author: {
        name: author_name,
        email: author_email
      }
    }
Valery Sizov's avatar
Valery Sizov committed
220 221

    if with_changed_files
Valery Sizov's avatar
Valery Sizov committed
222
      data.merge!(repo_changes)
Valery Sizov's avatar
Valery Sizov committed
223 224 225
    end

    data
Kirill Zaitsev's avatar
Kirill Zaitsev committed
226 227
  end

228 229
  # Discover issues should be closed when this commit is pushed to a project's
  # default branch.
230
  def closes_issues(current_user = self.committer)
Douwe Maan's avatar
Douwe Maan committed
231
    Gitlab::ClosingIssueExtractor.new(project, current_user).closed_by_message(safe_message)
232 233
  end

234 235
  def lazy_author
    BatchLoader.for(author_email.downcase).batch do |emails, loader|
236 237 238 239 240 241 242
      users = User.by_any_email(emails).includes(:emails)

      emails.each do |email|
        user = users.find { |u| u.any_email?(email) }

        loader.call(email, user)
      end
243 244 245
    end
  end

246
  def author
247 248 249 250
    # We use __sync so that we get the actual objects back (including an actual
    # nil), instead of a wrapper, as returning a wrapped nil breaks a lot of
    # code.
    lazy_author.__sync
251
  end
252
  request_cache(:author) { author_email.downcase }
253 254

  def committer
255
    @committer ||= User.find_by_any_email(committer_email)
256 257
  end

258
  def parents
259
    @parents ||= parent_ids.map { |oid| Commit.lazy(project, oid) }
260 261 262
  end

  def parent
263 264 265
    strong_memoize(:parent) do
      project.commit_by(oid: self.parent_id) if self.parent_id
    end
266 267
  end

268
  def notes
269 270 271
    project.notes.for_commit_id(self.id)
  end

272 273 274 275
  def discussion_notes
    notes.non_diff_notes
  end

Yorick Peterse's avatar
Yorick Peterse committed
276
  def notes_with_associations
277
    notes.includes(:author, :award_emoji)
Yorick Peterse's avatar
Yorick Peterse committed
278 279
  end

280 281 282 283
  def merge_requests
    @merge_requests ||= project.merge_requests.by_commit_sha(sha)
  end

284 285
  def method_missing(method, *args, &block)
    @raw.__send__(method, *args, &block) # rubocop:disable GitlabSecurity/PublicSend
286
  end
287

288 289
  def respond_to_missing?(method, include_private = false)
    @raw.respond_to?(method, include_private) || super
290
  end
291

292
  def short_id
293
    @raw.short_id(MIN_SHA_LENGTH)
294 295
  end

296 297
  def diff_refs
    Gitlab::Diff::DiffRefs.new(
298
      base_sha: self.parent_id || Gitlab::Git::BLANK_SHA,
299 300 301 302
      head_sha: self.sha
    )
  end

303
  def pipelines
304
    project.ci_pipelines.where(sha: sha)
305 306
  end

307
  def last_pipeline
308 309 310
    strong_memoize(:last_pipeline) do
      pipelines.last
    end
311 312
  end

313
  def status(ref = nil)
314 315
    return @statuses[ref] if @statuses.key?(ref)

316 317 318 319
    @statuses[ref] = status_for_project(ref, project)
  end

  def status_for_project(ref, pipeline_project)
320
    pipeline_project.ci_pipelines.latest_status_per_commit(id, ref)[id]
321 322 323 324
  end

  def set_status_for_ref(ref, status)
    @statuses[ref] = status
325
  end
326

Kevin O'Connor's avatar
Kevin O'Connor committed
327 328 329
  def signature
    return @signature if defined?(@signature)

330
    @signature = gpg_commit.signature
Kevin O'Connor's avatar
Kevin O'Connor committed
331 332
  end

333 334
  delegate :has_signature?, to: :gpg_commit

335
  def revert_branch_name
336
    "revert-#{short_id}"
337
  end
Yorick Peterse's avatar
Yorick Peterse committed
338

339 340 341
  def cherry_pick_branch_name
    project.repository.next_branch("cherry-pick-#{short_id}", mild: true)
  end
342

343
  def cherry_pick_description(user)
344
    message_body = ["(cherry picked from commit #{sha})"]
345

346 347
    if merged_merge_request?(user)
      commits_in_merge_request = merged_merge_request(user).commits
348

349
      if commits_in_merge_request.present?
350
        message_body << ""
351

352
        commits_in_merge_request.reverse.each do |commit_in_merge|
353
          message_body << "#{commit_in_merge.short_id} #{commit_in_merge.title}"
354 355 356
        end
      end
    end
357

358
    message_body.join("\n")
359
  end
360

361 362
  def cherry_pick_message(user)
    %Q{#{message}\n\n#{cherry_pick_description(user)}}
363 364
  end

365 366 367
  def revert_description(user)
    if merged_merge_request?(user)
      "This reverts merge request #{merged_merge_request(user).to_reference}"
368 369 370 371 372
    else
      "This reverts commit #{sha}"
    end
  end

373
  def revert_message(user)
374
    %Q{Revert "#{title.strip}"\n\n#{revert_description(user)}}
375
  end
376

377 378
  def reverts_commit?(commit, user)
    description? && description.include?(commit.revert_description(user))
379 380
  end

381
  def merge_commit?
382
    parent_ids.size > 1
383 384
  end

385 386 387 388 389
  def merged_merge_request(current_user)
    # Memoize with per-user access check
    @merged_merge_request_hash ||= Hash.new do |hash, user|
      hash[user] = merged_merge_request_no_cache(user)
    end
390

391
    @merged_merge_request_hash[current_user]
392 393
  end

394
  def has_been_reverted?(current_user, notes_association = nil)
Yorick Peterse's avatar
Yorick Peterse committed
395
    ext = all_references(current_user)
396
    notes_association ||= notes_with_associations
Yorick Peterse's avatar
Yorick Peterse committed
397

398
    notes_association.system.each do |note|
Yorick Peterse's avatar
Yorick Peterse committed
399 400 401
      note.all_references(current_user, extractor: ext)
    end

402
    ext.commits.any? { |commit_ref| commit_ref.reverts_commit?(self, current_user) }
403 404
  end

405 406
  def change_type_title(user)
    merged_merge_request?(user) ? 'merge request' : 'commit'
407 408
  end

409 410 411 412 413 414 415 416 417 418 419
  # Get the URI type of the given path
  #
  # Used to build URLs to files in the repository in GFM.
  #
  # path - String path to check
  #
  # Examples:
  #
  #   uri_type('doc/README.md') # => :blob
  #   uri_type('doc/logo.png')  # => :raw
  #   uri_type('doc/api')       # => :tree
420
  #   uri_type('not/found')     # => nil
421 422 423
  #
  # Returns a symbol
  def uri_type(path)
424 425 426
    entry = @raw.tree_entry(path)
    return unless entry

427
    if entry[:type] == :blob
Douwe Maan's avatar
Douwe Maan committed
428
      blob = ::Blob.decorate(Gitlab::Git::Blob.new(name: entry[:name]), @project)
429
      blob.image? || blob.video? ? :raw : :blob
430 431 432 433 434
    else
      entry[:type]
    end
  end

435
  def raw_diffs(*args)
436
    raw.diffs(*args)
437 438
  end

439
  def raw_deltas
440
    @deltas ||= raw.deltas
441
  end
442

443
  def diffs(diff_options = {})
444 445 446
    Gitlab::Diff::FileCollection::Commit.new(self, diff_options: diff_options)
  end

P.S.V.R's avatar
P.S.V.R committed
447 448 449 450
  def persisted?
    true
  end

451 452 453 454
  def to_ability_name
    model_name.singular
  end

P.S.V.R's avatar
P.S.V.R committed
455 456 457 458
  def touch
    # no-op but needs to be defined since #persisted? is defined
  end

459 460 461 462 463 464
  def touch_later
    # No-op.
    # This method is called by ActiveRecord.
    # We don't want to do anything for `Commit` model, so this is empty.
  end

465 466 467 468 469 470
  WIP_REGEX = /\A\s*(((?i)(\[WIP\]|WIP:|WIP)\s|WIP$))|(fixup!|squash!)\s/.freeze

  def work_in_progress?
    !!(title =~ WIP_REGEX)
  end

471 472 473 474
  def merged_merge_request?(user)
    !!merged_merge_request(user)
  end

475 476 477 478
  def cache_key
    "commit:#{sha}"
  end

479 480
  private

481 482
  def commit_reference(from, referable_commit_id, full: false)
    reference = project.to_reference(from, full: full)
483 484 485 486 487 488 489 490

    if reference.present?
      "#{reference}#{self.class.reference_prefix}#{referable_commit_id}"
    else
      referable_commit_id
    end
  end

491 492 493
  def repo_changes
    changes = { added: [], modified: [], removed: [] }

494
    raw_deltas.each do |diff|
Valery Sizov's avatar
Valery Sizov committed
495 496 497 498 499 500
      if diff.deleted_file
        changes[:removed] << diff.old_path
      elsif diff.renamed_file || diff.new_file
        changes[:added] << diff.new_path
      else
        changes[:modified] << diff.new_path
501 502 503 504 505
      end
    end

    changes
  end
506 507 508 509

  def merged_merge_request_no_cache(user)
    MergeRequestsFinder.new(user, project_id: project.id).find_by(merge_commit_sha: id) if merge_commit?
  end
510
end