Read about our upcoming Code of Conduct on this issue

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

Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
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 ::Gitlab::Utils::StrongMemoize
15

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

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

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

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

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

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

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

    context
  end

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

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

63
64
65
66
67
68
69
70
71
72
73
74
75
76
    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

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

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

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

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

    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
111
112
113
114

    def parent_class
      ::Project
    end
115
116
  end

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

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

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

128
  def id
129
    raw.id
130
131
  end

132
133
134
135
  def project_id
    project.id
  end

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

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

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

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

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

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

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

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

    full_title.truncate(81, separator: ' ', omission: '…')
181
  end
182

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

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

199
    safe_message.split("\n", 2)[1].try(:chomp)
200
  end
201

202
203
  def description?
    description.present?
204
205
  end

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

    if with_changed_files
Valery Sizov's avatar
Valery Sizov committed
219
      data.merge!(repo_changes)
Valery Sizov's avatar
Valery Sizov committed
220
221
222
    end

    data
Kirill Zaitsev's avatar
Kirill Zaitsev committed
223
224
  end

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

231
232
  def lazy_author
    BatchLoader.for(author_email.downcase).batch do |emails, loader|
233
234
235
236
237
238
239
      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
240
241
242
    end
  end

Douwe Maan's avatar
Douwe Maan committed
243
  def author
244
245
246
247
    # 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
Douwe Maan's avatar
Douwe Maan committed
248
  end
249
  request_cache(:author) { author_email.downcase }
Douwe Maan's avatar
Douwe Maan committed
250
251

  def committer
252
    @committer ||= User.find_by_any_email(committer_email)
Douwe Maan's avatar
Douwe Maan committed
253
254
  end

255
  def parents
256
    @parents ||= parent_ids.map { |oid| Commit.lazy(project, oid) }
257
258
259
  end

  def parent
260
261
262
    strong_memoize(:parent) do
      project.commit_by(oid: self.parent_id) if self.parent_id
    end
263
264
  end

265
  def notes
266
267
268
    project.notes.for_commit_id(self.id)
  end

269
270
271
272
  def discussion_notes
    notes.non_diff_notes
  end

Yorick Peterse's avatar
Yorick Peterse committed
273
  def notes_with_associations
274
    notes.includes(:author, :award_emoji)
Yorick Peterse's avatar
Yorick Peterse committed
275
276
  end

277
278
279
280
  def merge_requests
    @merge_requests ||= project.merge_requests.by_commit_sha(sha)
  end

281
282
  def method_missing(method, *args, &block)
    @raw.__send__(method, *args, &block) # rubocop:disable GitlabSecurity/PublicSend
283
  end
284

285
286
  def respond_to_missing?(method, include_private = false)
    @raw.respond_to?(method, include_private) || super
287
  end
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
288

289
  def short_id
290
    @raw.short_id(MIN_SHA_LENGTH)
291
292
  end

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

300
  def pipelines
301
    project.ci_pipelines.where(sha: sha)
Kamil Trzcinski's avatar
Kamil Trzcinski committed
302
303
  end

304
305
  def last_pipeline
    @last_pipeline ||= pipelines.last
306
307
  end

308
  def status(ref = nil)
309
310
    return @statuses[ref] if @statuses.key?(ref)

311
312
313
314
    @statuses[ref] = status_for_project(ref, project)
  end

  def status_for_project(ref, pipeline_project)
315
    pipeline_project.ci_pipelines.latest_status_per_commit(id, ref)[id]
316
317
318
319
  end

  def set_status_for_ref(ref, status)
    @statuses[ref] = status
Kamil Trzcinski's avatar
Kamil Trzcinski committed
320
  end
321

Kevin O'Connor's avatar
Kevin O'Connor committed
322
323
324
  def signature
    return @signature if defined?(@signature)

325
    @signature = gpg_commit.signature
Kevin O'Connor's avatar
Kevin O'Connor committed
326
327
  end

328
329
  delegate :has_signature?, to: :gpg_commit

330
  def revert_branch_name
331
    "revert-#{short_id}"
332
  end
Yorick Peterse's avatar
Yorick Peterse committed
333

334
335
336
  def cherry_pick_branch_name
    project.repository.next_branch("cherry-pick-#{short_id}", mild: true)
  end
337

338
  def cherry_pick_description(user)
339
    message_body = ["(cherry picked from commit #{sha})"]
340

341
342
    if merged_merge_request?(user)
      commits_in_merge_request = merged_merge_request(user).commits
343

344
      if commits_in_merge_request.present?
345
        message_body << ""
346

347
        commits_in_merge_request.reverse.each do |commit_in_merge|
348
          message_body << "#{commit_in_merge.short_id} #{commit_in_merge.title}"
349
350
351
        end
      end
    end
352

353
    message_body.join("\n")
354
  end
355

356
357
  def cherry_pick_message(user)
    %Q{#{message}\n\n#{cherry_pick_description(user)}}
358
359
  end

360
361
362
  def revert_description(user)
    if merged_merge_request?(user)
      "This reverts merge request #{merged_merge_request(user).to_reference}"
363
364
365
366
367
    else
      "This reverts commit #{sha}"
    end
  end

368
  def revert_message(user)
369
    %Q{Revert "#{title.strip}"\n\n#{revert_description(user)}}
370
  end
371

372
373
  def reverts_commit?(commit, user)
    description? && description.include?(commit.revert_description(user))
374
375
  end

376
  def merge_commit?
377
378
379
    parents.size > 1
  end

380
381
382
383
384
  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
385

386
    @merged_merge_request_hash[current_user]
387
388
  end

389
  def has_been_reverted?(current_user, notes_association = nil)
Yorick Peterse's avatar
Yorick Peterse committed
390
    ext = all_references(current_user)
391
    notes_association ||= notes_with_associations
Yorick Peterse's avatar
Yorick Peterse committed
392

393
    notes_association.system.each do |note|
Yorick Peterse's avatar
Yorick Peterse committed
394
395
396
      note.all_references(current_user, extractor: ext)
    end

397
    ext.commits.any? { |commit_ref| commit_ref.reverts_commit?(self, current_user) }
398
399
  end

400
401
  def change_type_title(user)
    merged_merge_request?(user) ? 'merge request' : 'commit'
402
403
  end

404
405
406
407
408
409
410
411
412
413
414
  # 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
415
  #   uri_type('not/found')     # => nil
416
417
418
  #
  # Returns a symbol
  def uri_type(path)
419
420
421
    entry = @raw.tree_entry(path)
    return unless entry

422
    if entry[:type] == :blob
Douwe Maan's avatar
Douwe Maan committed
423
      blob = ::Blob.decorate(Gitlab::Git::Blob.new(name: entry[:name]), @project)
424
      blob.image? || blob.video? ? :raw : :blob
425
426
427
428
429
    else
      entry[:type]
    end
  end

430
  def raw_diffs(*args)
431
    raw.diffs(*args)
432
433
  end

434
  def raw_deltas
435
    @deltas ||= raw.deltas
436
  end
437

438
  def diffs(diff_options = {})
439
440
441
    Gitlab::Diff::FileCollection::Commit.new(self, diff_options: diff_options)
  end

P.S.V.R's avatar
P.S.V.R committed
442
443
444
445
  def persisted?
    true
  end

446
447
448
449
  def to_ability_name
    model_name.singular
  end

P.S.V.R's avatar
P.S.V.R committed
450
451
452
453
  def touch
    # no-op but needs to be defined since #persisted? is defined
  end

454
455
456
457
458
459
  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

460
461
462
463
464
465
  WIP_REGEX = /\A\s*(((?i)(\[WIP\]|WIP:|WIP)\s|WIP$))|(fixup!|squash!)\s/.freeze

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

466
467
468
469
  def merged_merge_request?(user)
    !!merged_merge_request(user)
  end

470
471
  private

472
473
  def commit_reference(from, referable_commit_id, full: false)
    reference = project.to_reference(from, full: full)
474
475
476
477
478
479
480
481

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

482
483
484
  def repo_changes
    changes = { added: [], modified: [], removed: [] }

485
    raw_deltas.each do |diff|
Valery Sizov's avatar
Valery Sizov committed
486
487
488
489
490
491
      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
492
493
494
495
496
      end
    end

    changes
  end
497
498
499
500

  def merged_merge_request_no_cache(user)
    MergeRequestsFinder.new(user, project_id: project.id).find_by(merge_commit_sha: id) if merge_commit?
  end
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
501
end