BigW Consortium Gitlab

commit.rb 9.46 KB
Newer Older
1
class Commit
2
  extend ActiveModel::Naming
3
  extend Gitlab::Cache::RequestCache
4 5

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

12
  attr_mentionable :safe_message, pipeline: :single_line
Yorick Peterse committed
13 14 15 16

  participant :author
  participant :committer
  participant :notes_with_associations
Saito committed
17

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

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

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

28
  # The SHA can be between 7 and 40 hex characters.
29
  COMMIT_SHA_PATTERN = '\h{7,40}'.freeze
30

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

    context
  end

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

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

54
    # Truncate sha to 8 characters
55
    def truncate_sha(sha)
56
      sha[0..7]
57
    end
58 59 60 61

    def max_diff_options
      {
        max_files: DIFF_HARD_LIMIT_FILES,
62
        max_lines: DIFF_HARD_LIMIT_LINES
63 64
      }
    end
65 66

    def from_hash(hash, project)
67 68
      raw_commit = Gitlab::Git::Commit.new(project.repository.raw, hash)
      new(raw_commit, project)
69
    end
70 71 72 73

    def valid_hash?(key)
      !!(/\A#{COMMIT_SHA_PATTERN}\z/ =~ key)
    end
74 75
  end

76
  attr_accessor :raw
77

78
  def initialize(raw_commit, project)
79 80
    raise "Nil as raw commit passed" unless raw_commit

81
    @raw = raw_commit
82
    @project = project
83
  end
84

85 86 87 88
  def id
    @raw.id
  end

Robert Speicher committed
89 90 91 92
  def ==(other)
    (self.class === other) && (raw == other.raw)
  end

93 94 95 96 97 98 99 100
  def self.reference_prefix
    '@'
  end

  # Pattern used to extract commit references from text
  #
  # This pattern supports cross-project references.
  def self.reference_pattern
101
    @reference_pattern ||= %r{
102
      (?:#{Project.reference_pattern}#{reference_prefix})?
103
      (?<commit>\h{7,40})
104
    }x
105 106
  end

107
  def self.link_reference_pattern
108
    @link_reference_pattern ||= super("commit", /(?<commit>#{COMMIT_SHA_PATTERN})/)
109 110
  end

111 112
  def to_reference(from_project = nil, full: false)
    commit_reference(from_project, id, full: full)
113 114
  end

115 116
  def reference_link_text(from_project = nil, full: false)
    commit_reference(from_project, short_id, full: full)
117 118
  end

119
  def diff_line_count
120
    @diff_line_count ||= Commit.diff_line_count(raw_diffs)
121 122 123
    @diff_line_count
  end

124 125 126
  # Returns the commits title.
  #
  # Usually, the commit title is the first line of the commit message.
127
  # In case this first line is longer than 100 characters, it is cut off
128
  # after 80 characters + `...`
129
  def title
130 131 132
    return full_title if full_title.length < 100

    full_title.truncate(81, separator: ' ', omission: '…')
133
  end
134

135 136
  # Returns the full commits title
  def full_title
137
    @full_title ||=
Douwe Maan committed
138 139 140 141 142
      if safe_message.blank?
        no_commit_message
      else
        safe_message.split("\n", 2).first
      end
143 144
  end

145 146
  # Returns full commit message if title is truncated (greater than 99 characters)
  # otherwise returns commit message without first line
147
  def description
148
    return safe_message if full_title.length >= 100
149

150 151
    safe_message.split("\n", 2)[1].try(:chomp)
  end
152

153 154
  def description?
    description.present?
155 156
  end

Valery Sizov committed
157
  def hook_attrs(with_changed_files: false)
Valery Sizov committed
158
    data = {
Kirill Zaitsev committed
159 160 161
      id: id,
      message: safe_message,
      timestamp: committed_date.xmlschema,
162
      url: Gitlab::UrlBuilder.build(self),
Kirill Zaitsev committed
163 164 165 166 167
      author: {
        name: author_name,
        email: author_email
      }
    }
Valery Sizov committed
168 169

    if with_changed_files
Valery Sizov committed
170
      data.merge!(repo_changes)
Valery Sizov committed
171 172 173
    end

    data
Kirill Zaitsev committed
174 175
  end

176 177
  # Discover issues should be closed when this commit is pushed to a project's
  # default branch.
178
  def closes_issues(current_user = self.committer)
179
    Gitlab::ClosingIssueExtractor.new(project, current_user).closed_by_message(safe_message)
180 181
  end

182
  def author
183
    User.find_by_any_email(author_email.downcase)
184
  end
185
  request_cache(:author) { author_email.downcase }
186 187

  def committer
188
    @committer ||= User.find_by_any_email(committer_email.downcase)
189 190
  end

191 192 193 194 195 196 197 198
  def parents
    @parents ||= parent_ids.map { |id| project.commit(id) }
  end

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

199
  def notes
200 201 202
    project.notes.for_commit_id(self.id)
  end

203 204 205 206
  def discussion_notes
    notes.non_diff_notes
  end

Yorick Peterse committed
207
  def notes_with_associations
208
    notes.includes(:author)
Yorick Peterse committed
209 210
  end

211
  def method_missing(m, *args, &block)
212
    @raw.__send__(m, *args, &block) # rubocop:disable GitlabSecurity/PublicSend
213
  end
214

215 216
  def respond_to_missing?(method, include_private = false)
    @raw.respond_to?(method, include_private) || super
217
  end
218

219 220 221 222 223
  # Truncate sha to 8 characters
  def short_id
    @raw.short_id(7)
  end

224 225
  def diff_refs
    Gitlab::Diff::DiffRefs.new(
226
      base_sha: self.parent_id || Gitlab::Git::BLANK_SHA,
227 228 229 230
      head_sha: self.sha
    )
  end

231
  def pipelines
232
    project.pipelines.where(sha: sha)
233 234
  end

235 236
  def last_pipeline
    @last_pipeline ||= pipelines.last
237 238
  end

239
  def status(ref = nil)
240 241
    @statuses ||= {}

242 243
    return @statuses[ref] if @statuses.key?(ref)

244
    @statuses[ref] = pipelines.latest_status(ref)
245
  end
246

247 248 249
  def signature
    return @signature if defined?(@signature)

250
    @signature = gpg_commit.signature
251 252
  end

253 254
  delegate :has_signature?, to: :gpg_commit

255
  def revert_branch_name
256
    "revert-#{short_id}"
257
  end
Yorick Peterse committed
258

259 260 261
  def cherry_pick_branch_name
    project.repository.next_branch("cherry-pick-#{short_id}", mild: true)
  end
262

263
  def cherry_pick_description(user)
264
    message_body = "(cherry picked from commit #{sha})"
265

266 267
    if merged_merge_request?(user)
      commits_in_merge_request = merged_merge_request(user).commits
268

269
      if commits_in_merge_request.present?
270
        message_body << "\n"
271

272
        commits_in_merge_request.reverse.each do |commit_in_merge|
273
          message_body << "\n#{commit_in_merge.short_id} #{commit_in_merge.title}"
274 275 276
        end
      end
    end
277

278
    message_body
279
  end
280

281 282
  def cherry_pick_message(user)
    %Q{#{message}\n\n#{cherry_pick_description(user)}}
283 284
  end

285 286 287
  def revert_description(user)
    if merged_merge_request?(user)
      "This reverts merge request #{merged_merge_request(user).to_reference}"
288 289 290 291 292
    else
      "This reverts commit #{sha}"
    end
  end

293
  def revert_message(user)
294
    %Q{Revert "#{title.strip}"\n\n#{revert_description(user)}}
295
  end
296

297 298
  def reverts_commit?(commit, user)
    description? && description.include?(commit.revert_description(user))
299 300
  end

301
  def merge_commit?
302 303 304
    parents.size > 1
  end

305 306 307 308 309
  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
310

311
    @merged_merge_request_hash[current_user]
312 313
  end

314
  def has_been_reverted?(current_user, noteable = self)
Yorick Peterse committed
315 316 317 318 319 320
    ext = all_references(current_user)

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

321
    ext.commits.any? { |commit_ref| commit_ref.reverts_commit?(self, current_user) }
322 323
  end

324 325
  def change_type_title(user)
    merged_merge_request?(user) ? 'merge request' : 'commit'
326 327
  end

328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
  # 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 committed
345
      blob = ::Blob.decorate(Gitlab::Git::Blob.new(name: entry[:name]), @project)
346
      blob.image? || blob.video? ? :raw : :blob
347 348 349 350 351 352 353
    else
      entry[:type]
    end
  rescue Rugged::TreeError
    nil
  end

354
  def raw_diffs(*args)
355
    raw.diffs(*args)
356 357
  end

358
  def raw_deltas
359
    @deltas ||= raw.deltas
360
  end
361

362
  def diffs(diff_options = nil)
363 364 365
    Gitlab::Diff::FileCollection::Commit.new(self, diff_options: diff_options)
  end

P.S.V.R committed
366 367 368 369 370 371 372 373
  def persisted?
    true
  end

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

374 375 376 377 378 379
  WIP_REGEX = /\A\s*(((?i)(\[WIP\]|WIP:|WIP)\s|WIP$))|(fixup!|squash!)\s/.freeze

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

380 381
  private

382 383
  def commit_reference(from_project, referable_commit_id, full: false)
    reference = project.to_reference(from_project, full: full)
384 385 386 387 388 389 390 391

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

392 393 394
  def repo_changes
    changes = { added: [], modified: [], removed: [] }

395
    raw_deltas.each do |diff|
Valery Sizov committed
396 397 398 399 400 401
      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
402 403 404 405 406
      end
    end

    changes
  end
407 408 409 410 411 412 413 414

  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
415 416

  def gpg_commit
417
    @gpg_commit ||= Gitlab::Gpg::Commit.new(self)
418
  end
419
end