commit.rb 10.6 KB
Newer Older
1
# coding: utf-8
2
class Commit
3
  extend ActiveModel::Naming
4
  extend Gitlab::Cache::RequestCache
5 6

  include ActiveModel::Conversion
7
  include Noteable
8
  include Participable
9
  include Mentionable
10 11
  include Referable
  include StaticModel
12

13
  attr_mentionable :safe_message, pipeline: :single_line
Yorick Peterse's avatar
Yorick Peterse committed
14 15 16 17

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

19
  attr_accessor :project, :author
20 21
  attr_accessor :redacted_description_html
  attr_accessor :redacted_title_html
22

23
  DIFF_SAFE_LINES = Gitlab::Git::DiffCollection::DEFAULT_LIMITS[:max_lines]
24

25
  # Commits above this size will not be rendered in HTML
26 27
  DIFF_HARD_LIMIT_FILES = 1000
  DIFF_HARD_LIMIT_LINES = 50000
28

29
  MIN_SHA_LENGTH = Gitlab::Git::Commit::MIN_SHA_LENGTH
30
  COMMIT_SHA_PATTERN = /\h{#{MIN_SHA_LENGTH},40}/.freeze
31

32 33 34 35 36 37 38
  def banzai_render_context(field)
    context = { pipeline: :single_line, project: self.project }
    context[:author] = self.author if self.author

    context
  end

39
  class << self
40
    def decorate(commits, project)
41
      commits.map do |commit|
Douwe Maan's avatar
Douwe Maan committed
42
        if commit.is_a?(Commit)
43 44
          commit
        else
45
          self.new(commit, project)
46 47
        end
      end
48
    end
49

50 51
    # Calculate number of lines to render for diffs
    def diff_line_count(diffs)
52
      diffs.reduce(0) { |sum, d| sum + Gitlab::Git::Util.count_lines(d.diff) }
53
    end
54

55 56 57 58 59 60 61 62 63 64 65 66 67 68
    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

69
    # Truncate sha to 8 characters
70
    def truncate_sha(sha)
71
      sha[0..MIN_SHA_LENGTH]
72
    end
73 74 75 76

    def max_diff_options
      {
        max_files: DIFF_HARD_LIMIT_FILES,
77
        max_lines: DIFF_HARD_LIMIT_LINES
78 79
      }
    end
80 81

    def from_hash(hash, project)
82 83
      raw_commit = Gitlab::Git::Commit.new(project.repository.raw, hash)
      new(raw_commit, project)
84
    end
85 86 87 88

    def valid_hash?(key)
      !!(/\A#{COMMIT_SHA_PATTERN}\z/ =~ key)
    end
89 90 91 92 93 94 95 96 97 98 99 100 101 102

    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
103 104
  end

105
  attr_accessor :raw
106

107
  def initialize(raw_commit, project)
108 109
    raise "Nil as raw commit passed" unless raw_commit

110
    @raw = raw_commit
111
    @project = project
112
    @statuses = {}
113
  end
114

115
  def id
116
    raw.id
117 118
  end

Robert Speicher's avatar
Robert Speicher committed
119
  def ==(other)
120
    other.is_a?(self.class) && raw == other.raw
Robert Speicher's avatar
Robert Speicher committed
121 122
  end

123 124 125 126 127 128 129 130
  def self.reference_prefix
    '@'
  end

  # Pattern used to extract commit references from text
  #
  # This pattern supports cross-project references.
  def self.reference_pattern
131
    @reference_pattern ||= %r{
132
      (?:#{Project.reference_pattern}#{reference_prefix})?
133
      (?<commit>#{COMMIT_SHA_PATTERN})
134
    }x
135 136
  end

137
  def self.link_reference_pattern
138
    @link_reference_pattern ||= super("commit", /(?<commit>#{COMMIT_SHA_PATTERN})/)
139 140
  end

141 142
  def to_reference(from = nil, full: false)
    commit_reference(from, id, full: full)
143 144
  end

145 146
  def reference_link_text(from = nil, full: false)
    commit_reference(from, short_id, full: full)
147 148
  end

149
  def diff_line_count
150
    @diff_line_count ||= Commit.diff_line_count(raw_diffs)
151 152 153
    @diff_line_count
  end

154 155 156
  # Returns the commits title.
  #
  # Usually, the commit title is the first line of the commit message.
157
  # In case this first line is longer than 100 characters, it is cut off
158
  # after 80 characters + `...`
159
  def title
160 161 162
    return full_title if full_title.length < 100

    full_title.truncate(81, separator: ' ', omission: '…')
163
  end
164

165 166
  # Returns the full commits title
  def full_title
167
    @full_title ||=
Douwe Maan's avatar
Douwe Maan committed
168 169 170 171 172
      if safe_message.blank?
        no_commit_message
      else
        safe_message.split("\n", 2).first
      end
173 174
  end

175 176
  # Returns full commit message if title is truncated (greater than 99 characters)
  # otherwise returns commit message without first line
177
  def description
178
    return safe_message if full_title.length >= 100
179

180 181
    safe_message.split("\n", 2)[1].try(:chomp)
  end
182

183 184
  def description?
    description.present?
185 186
  end

Valery Sizov's avatar
Valery Sizov committed
187
  def hook_attrs(with_changed_files: false)
Valery Sizov's avatar
Valery Sizov committed
188
    data = {
Kirill Zaitsev's avatar
Kirill Zaitsev committed
189 190 191
      id: id,
      message: safe_message,
      timestamp: committed_date.xmlschema,
192
      url: Gitlab::UrlBuilder.build(self),
Kirill Zaitsev's avatar
Kirill Zaitsev committed
193 194 195 196 197
      author: {
        name: author_name,
        email: author_email
      }
    }
Valery Sizov's avatar
Valery Sizov committed
198 199

    if with_changed_files
Valery Sizov's avatar
Valery Sizov committed
200
      data.merge!(repo_changes)
Valery Sizov's avatar
Valery Sizov committed
201 202 203
    end

    data
Kirill Zaitsev's avatar
Kirill Zaitsev committed
204 205
  end

206 207
  # Discover issues should be closed when this commit is pushed to a project's
  # default branch.
208
  def closes_issues(current_user = self.committer)
209
    Gitlab::ClosingIssueExtractor.new(project, current_user).closed_by_message(safe_message)
210 211
  end

212
  def author
213
    User.find_by_any_email(author_email.downcase)
214
  end
215
  request_cache(:author) { author_email.downcase }
216 217

  def committer
218
    @committer ||= User.find_by_any_email(committer_email.downcase)
219 220
  end

221 222 223 224 225 226 227 228
  def parents
    @parents ||= parent_ids.map { |id| project.commit(id) }
  end

  def parent
    @parent ||= project.commit(self.parent_id) if self.parent_id
  end

229
  def notes
230 231 232
    project.notes.for_commit_id(self.id)
  end

233 234 235 236
  def discussion_notes
    notes.non_diff_notes
  end

Yorick Peterse's avatar
Yorick Peterse committed
237
  def notes_with_associations
238
    notes.includes(:author)
Yorick Peterse's avatar
Yorick Peterse committed
239 240
  end

241 242
  def method_missing(method, *args, &block)
    @raw.__send__(method, *args, &block) # rubocop:disable GitlabSecurity/PublicSend
243
  end
244

245 246
  def respond_to_missing?(method, include_private = false)
    @raw.respond_to?(method, include_private) || super
247
  end
248

249
  def short_id
250
    @raw.short_id(MIN_SHA_LENGTH)
251 252
  end

253 254
  def diff_refs
    Gitlab::Diff::DiffRefs.new(
255
      base_sha: self.parent_id || Gitlab::Git::BLANK_SHA,
256 257 258 259
      head_sha: self.sha
    )
  end

260
  def pipelines
261
    project.pipelines.where(sha: sha)
262 263
  end

264 265
  def last_pipeline
    @last_pipeline ||= pipelines.last
266 267
  end

268
  def status(ref = nil)
269 270
    return @statuses[ref] if @statuses.key?(ref)

271 272 273 274 275
    @statuses[ref] = project.pipelines.latest_status_per_commit(id, ref)[id]
  end

  def set_status_for_ref(ref, status)
    @statuses[ref] = status
276
  end
277

278 279 280
  def signature
    return @signature if defined?(@signature)

281
    @signature = gpg_commit.signature
282 283
  end

284 285
  delegate :has_signature?, to: :gpg_commit

286
  def revert_branch_name
287
    "revert-#{short_id}"
288
  end
Yorick Peterse's avatar
Yorick Peterse committed
289

290 291 292
  def cherry_pick_branch_name
    project.repository.next_branch("cherry-pick-#{short_id}", mild: true)
  end
293

294
  def cherry_pick_description(user)
295
    message_body = "(cherry picked from commit #{sha})"
296

297 298
    if merged_merge_request?(user)
      commits_in_merge_request = merged_merge_request(user).commits
299

300
      if commits_in_merge_request.present?
301
        message_body << "\n"
302

303
        commits_in_merge_request.reverse.each do |commit_in_merge|
304
          message_body << "\n#{commit_in_merge.short_id} #{commit_in_merge.title}"
305 306 307
        end
      end
    end
308

309
    message_body
310
  end
311

312 313
  def cherry_pick_message(user)
    %Q{#{message}\n\n#{cherry_pick_description(user)}}
314 315
  end

316 317 318
  def revert_description(user)
    if merged_merge_request?(user)
      "This reverts merge request #{merged_merge_request(user).to_reference}"
319 320 321 322 323
    else
      "This reverts commit #{sha}"
    end
  end

324
  def revert_message(user)
325
    %Q{Revert "#{title.strip}"\n\n#{revert_description(user)}}
326
  end
327

328 329
  def reverts_commit?(commit, user)
    description? && description.include?(commit.revert_description(user))
330 331
  end

332
  def merge_commit?
333 334 335
    parents.size > 1
  end

336 337 338 339 340
  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
341

342
    @merged_merge_request_hash[current_user]
343 344
  end

345
  def has_been_reverted?(current_user, noteable = self)
Yorick Peterse's avatar
Yorick Peterse committed
346 347 348 349 350 351
    ext = all_references(current_user)

    noteable.notes_with_associations.system.each do |note|
      note.all_references(current_user, extractor: ext)
    end

352
    ext.commits.any? { |commit_ref| commit_ref.reverts_commit?(self, current_user) }
353 354
  end

355 356
  def change_type_title(user)
    merged_merge_request?(user) ? 'merge request' : 'commit'
357 358
  end

359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
  # 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
  #   uri_type('not/found')     # => :nil
  #
  # Returns a symbol
  def uri_type(path)
    entry = @raw.tree.path(path)
    if entry[:type] == :blob
Douwe Maan's avatar
Douwe Maan committed
376
      blob = ::Blob.decorate(Gitlab::Git::Blob.new(name: entry[:name]), @project)
377
      blob.image? || blob.video? ? :raw : :blob
378 379 380 381 382 383 384
    else
      entry[:type]
    end
  rescue Rugged::TreeError
    nil
  end

385
  def raw_diffs(*args)
386
    raw.diffs(*args)
387 388
  end

389
  def raw_deltas
390
    @deltas ||= raw.deltas
391
  end
392

393
  def diffs(diff_options = {})
394 395 396
    Gitlab::Diff::FileCollection::Commit.new(self, diff_options: diff_options)
  end

P.S.V.R's avatar
P.S.V.R committed
397 398 399 400 401 402 403 404
  def persisted?
    true
  end

  def touch
    # no-op but needs to be defined since #persisted? is defined
  end

405 406 407 408 409 410
  WIP_REGEX = /\A\s*(((?i)(\[WIP\]|WIP:|WIP)\s|WIP$))|(fixup!|squash!)\s/.freeze

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

411 412
  private

413 414
  def commit_reference(from, referable_commit_id, full: false)
    reference = project.to_reference(from, full: full)
415 416 417 418 419 420 421 422

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

423 424 425
  def repo_changes
    changes = { added: [], modified: [], removed: [] }

426
    raw_deltas.each do |diff|
Valery Sizov's avatar
Valery Sizov committed
427 428 429 430 431 432
      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
433 434 435 436 437
      end
    end

    changes
  end
438 439 440 441 442 443 444 445

  def merged_merge_request?(user)
    !!merged_merge_request(user)
  end

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

  def gpg_commit
448
    @gpg_commit ||= Gitlab::Gpg::Commit.new(self)
449
  end
450
end