BigW Consortium Gitlab

commit.rb 9.02 KB
Newer Older
1
class Commit
2
  extend ActiveModel::Naming
3 4

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

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

  participant :author
  participant :committer
  participant :notes_with_associations
Saito committed
16

17 18
  attr_accessor :project

19
  DIFF_SAFE_LINES = Gitlab::Git::DiffCollection::DEFAULT_LIMITS[:max_lines]
20

21
  # Commits above this size will not be rendered in HTML
22 23
  DIFF_HARD_LIMIT_FILES = 1000
  DIFF_HARD_LIMIT_LINES = 50000
24

25
  # The SHA can be between 7 and 40 hex characters.
26
  COMMIT_SHA_PATTERN = '\h{7,40}'.freeze
27

28
  class << self
29
    def decorate(commits, project)
30
      commits.map do |commit|
Douwe Maan committed
31
        if commit.is_a?(Commit)
32 33
          commit
        else
34
          self.new(commit, project)
35 36
        end
      end
37
    end
38

39 40
    # Calculate number of lines to render for diffs
    def diff_line_count(diffs)
41
      diffs.reduce(0) { |sum, d| sum + Gitlab::Git::Util.count_lines(d.diff) }
42
    end
43

44
    # Truncate sha to 8 characters
45
    def truncate_sha(sha)
46
      sha[0..7]
47
    end
48 49 50 51 52 53 54

    def max_diff_options
      {
        max_files: DIFF_HARD_LIMIT_FILES,
        max_lines: DIFF_HARD_LIMIT_LINES,
      }
    end
55 56 57 58

    def from_hash(hash, project)
      new(Gitlab::Git::Commit.new(hash), project)
    end
59 60 61 62

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

65
  attr_accessor :raw
66

67
  def initialize(raw_commit, project)
68 69
    raise "Nil as raw commit passed" unless raw_commit

70
    @raw = raw_commit
71
    @project = project
72
  end
73

74 75 76 77
  def id
    @raw.id
  end

Robert Speicher committed
78 79 80 81
  def ==(other)
    (self.class === other) && (raw == other.raw)
  end

82 83 84 85 86 87 88 89
  def self.reference_prefix
    '@'
  end

  # Pattern used to extract commit references from text
  #
  # This pattern supports cross-project references.
  def self.reference_pattern
90
    @reference_pattern ||= %r{
91
      (?:#{Project.reference_pattern}#{reference_prefix})?
92
      (?<commit>\h{7,40})
93
    }x
94 95
  end

96
  def self.link_reference_pattern
97
    @link_reference_pattern ||= super("commit", /(?<commit>#{COMMIT_SHA_PATTERN})/)
98 99
  end

100 101
  def to_reference(from_project = nil, full: false)
    commit_reference(from_project, id, full: full)
102 103
  end

104 105
  def reference_link_text(from_project = nil, full: false)
    commit_reference(from_project, short_id, full: full)
106 107
  end

108
  def diff_line_count
109
    @diff_line_count ||= Commit.diff_line_count(raw_diffs)
110 111 112
    @diff_line_count
  end

113 114 115
  # Returns the commits title.
  #
  # Usually, the commit title is the first line of the commit message.
116 117
  # In case this first line is longer than 100 characters, it is cut off
  # after 80 characters and ellipses (`&hellp;`) are appended.
118
  def title
119 120
    full_title.length > 100 ? full_title[0..79] << "…" : full_title
  end
121

122 123 124
  # Returns the full commits title
  def full_title
    return @full_title if @full_title
125

Douwe Maan committed
126 127 128 129 130 131
    @full_title =
      if safe_message.blank?
        no_commit_message
      else
        safe_message.split("\n", 2).first
      end
132 133 134 135 136 137
  end

  # Returns the commits description
  #
  # cut off, ellipses (`&hellp;`) are prepended to the commit message.
  def description
138
    title_end = safe_message.index("\n")
139 140
    @description ||=
      if (!title_end && safe_message.length > 100) || (title_end && title_end > 100)
141
        "…" << safe_message[80..-1]
142 143 144
      else
        safe_message.split("\n", 2)[1].try(:chomp)
      end
145
  end
146

147 148
  def description?
    description.present?
149 150
  end

Valery Sizov committed
151
  def hook_attrs(with_changed_files: false)
Valery Sizov committed
152
    data = {
Kirill Zaitsev committed
153 154 155
      id: id,
      message: safe_message,
      timestamp: committed_date.xmlschema,
156
      url: Gitlab::UrlBuilder.build(self),
Kirill Zaitsev committed
157 158 159 160 161
      author: {
        name: author_name,
        email: author_email
      }
    }
Valery Sizov committed
162 163

    if with_changed_files
Valery Sizov committed
164
      data.merge!(repo_changes)
Valery Sizov committed
165 166 167
    end

    data
Kirill Zaitsev committed
168 169
  end

170 171
  # Discover issues should be closed when this commit is pushed to a project's
  # default branch.
172
  def closes_issues(current_user = self.committer)
173
    Gitlab::ClosingIssueExtractor.new(project, current_user).closed_by_message(safe_message)
174 175
  end

176
  def author
177 178 179 180 181 182 183 184 185 186 187
    if RequestStore.active?
      key = "commit_author:#{author_email.downcase}"
      # nil is a valid value since no author may exist in the system
      if RequestStore.store.has_key?(key)
        @author = RequestStore.store[key]
      else
        @author = find_author_by_any_email
        RequestStore.store[key] = @author
      end
    else
      @author ||= find_author_by_any_email
188
    end
189 190 191
  end

  def committer
192
    @committer ||= User.find_by_any_email(committer_email.downcase)
193 194
  end

195 196 197 198 199 200 201 202
  def parents
    @parents ||= parent_ids.map { |id| project.commit(id) }
  end

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

203
  def notes
204 205 206
    project.notes.for_commit_id(self.id)
  end

207 208 209 210
  def discussion_notes
    notes.non_diff_notes
  end

Yorick Peterse committed
211
  def notes_with_associations
212
    notes.includes(:author)
Yorick Peterse committed
213 214
  end

215 216
  def method_missing(m, *args, &block)
    @raw.send(m, *args, &block)
217
  end
218

219 220
  def respond_to_missing?(method, include_private = false)
    @raw.respond_to?(method, include_private) || super
221
  end
222

223 224 225 226 227
  # Truncate sha to 8 characters
  def short_id
    @raw.short_id(7)
  end

228 229
  def diff_refs
    Gitlab::Diff::DiffRefs.new(
230
      base_sha: self.parent_id || Gitlab::Git::BLANK_SHA,
231 232 233 234
      head_sha: self.sha
    )
  end

235
  def pipelines
236
    project.pipelines.where(sha: sha)
237 238
  end

239 240 241 242
  def latest_pipeline
    pipelines.last
  end

243
  def status(ref = nil)
244 245
    @statuses ||= {}

246 247
    return @statuses[ref] if @statuses.key?(ref)

248
    @statuses[ref] = pipelines.latest_status(ref)
249
  end
250

251
  def revert_branch_name
252
    "revert-#{short_id}"
253
  end
Yorick Peterse committed
254

255 256 257
  def cherry_pick_branch_name
    project.repository.next_branch("cherry-pick-#{short_id}", mild: true)
  end
258

259 260 261
  def revert_description(user)
    if merged_merge_request?(user)
      "This reverts merge request #{merged_merge_request(user).to_reference}"
262 263 264 265 266
    else
      "This reverts commit #{sha}"
    end
  end

267
  def revert_message(user)
268
    %Q{Revert "#{title.strip}"\n\n#{revert_description(user)}}
269
  end
270

271 272
  def reverts_commit?(commit, user)
    description? && description.include?(commit.revert_description(user))
273 274
  end

275
  def merge_commit?
276 277 278
    parents.size > 1
  end

279 280 281 282 283
  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
284

285
    @merged_merge_request_hash[current_user]
286 287
  end

288
  def has_been_reverted?(current_user, noteable = self)
Yorick Peterse committed
289 290 291 292 293 294
    ext = all_references(current_user)

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

295
    ext.commits.any? { |commit_ref| commit_ref.reverts_commit?(self, current_user) }
296 297
  end

298 299
  def change_type_title(user)
    merged_merge_request?(user) ? 'merge request' : 'commit'
300 301
  end

302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
  # 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
319 320
      blob = ::Blob.decorate(Gitlab::Git::Blob.new(name: entry[:name]))
      blob.image? || blob.video? ? :raw : :blob
321 322 323 324 325 326 327
    else
      entry[:type]
    end
  rescue Rugged::TreeError
    nil
  end

328
  def raw_diffs(*args)
329 330 331 332 333 334 335 336
    use_gitaly = Gitlab::GitalyClient.feature_enabled?(:commit_raw_diffs)
    deltas_only = args.last.is_a?(Hash) && args.last[:deltas_only]

    if use_gitaly && !deltas_only
      Gitlab::GitalyClient::Commit.diff_from_parent(self, *args)
    else
      raw.diffs(*args)
    end
337 338 339
  end

  def diffs(diff_options = nil)
340 341 342
    Gitlab::Diff::FileCollection::Commit.new(self, diff_options: diff_options)
  end

P.S.V.R committed
343 344 345 346 347 348 349 350
  def persisted?
    true
  end

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

351 352 353 354 355 356
  WIP_REGEX = /\A\s*(((?i)(\[WIP\]|WIP:|WIP)\s|WIP$))|(fixup!|squash!)\s/.freeze

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

357 358
  private

359 360
  def commit_reference(from_project, referable_commit_id, full: false)
    reference = project.to_reference(from_project, full: full)
361 362 363 364 365 366 367 368

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

369 370 371 372
  def find_author_by_any_email
    User.find_by_any_email(author_email.downcase)
  end

373 374 375
  def repo_changes
    changes = { added: [], modified: [], removed: [] }

376
    raw_diffs(deltas_only: true).each do |diff|
Valery Sizov committed
377 378 379 380 381 382
      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
383 384 385 386 387
      end
    end

    changes
  end
388 389 390 391 392 393 394 395

  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
396
end