BigW Consortium Gitlab

commit.rb 8.71 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
  DIFF_SAFE_LINES = Gitlab::Git::DiffCollection::DEFAULT_LIMITS[:max_lines]
21

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

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

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

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

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

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

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

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

66
  attr_accessor :raw
67

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

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

75 76 77 78
  def id
    @raw.id
  end

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

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

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

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

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

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

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

114 115 116
  # Returns the commits title.
  #
  # Usually, the commit title is the first line of the commit message.
117
  # In case this first line is longer than 100 characters, it is cut off
118
  # after 80 characters + `...`
119
  def title
120 121 122
    return full_title if full_title.length < 100

    full_title.truncate(81, separator: ' ', omission: '…')
123
  end
124

125 126
  # Returns the full commits title
  def full_title
127
    @full_title ||=
Douwe Maan committed
128 129 130 131 132
      if safe_message.blank?
        no_commit_message
      else
        safe_message.split("\n", 2).first
      end
133 134
  end

135 136
  # Returns full commit message if title is truncated (greater than 99 characters)
  # otherwise returns commit message without first line
137
  def description
138
    return safe_message if full_title.length >= 100
139

140 141
    safe_message.split("\n", 2)[1].try(:chomp)
  end
142

143 144
  def description?
    description.present?
145 146
  end

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

    if with_changed_files
Valery Sizov committed
160
      data.merge!(repo_changes)
Valery Sizov committed
161 162 163
    end

    data
Kirill Zaitsev committed
164 165
  end

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

172
  def author
173
    User.find_by_any_email(author_email.downcase)
174
  end
175
  request_cache(:author) { author_email.downcase }
176 177

  def committer
178
    @committer ||= User.find_by_any_email(committer_email.downcase)
179 180
  end

181 182 183 184 185 186 187 188
  def parents
    @parents ||= parent_ids.map { |id| project.commit(id) }
  end

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

189
  def notes
190 191 192
    project.notes.for_commit_id(self.id)
  end

193 194 195 196
  def discussion_notes
    notes.non_diff_notes
  end

Yorick Peterse committed
197
  def notes_with_associations
198
    notes.includes(:author)
Yorick Peterse committed
199 200
  end

201 202
  def method_missing(m, *args, &block)
    @raw.send(m, *args, &block)
203
  end
204

205 206
  def respond_to_missing?(method, include_private = false)
    @raw.respond_to?(method, include_private) || super
207
  end
208

209 210 211 212 213
  # Truncate sha to 8 characters
  def short_id
    @raw.short_id(7)
  end

214 215
  def diff_refs
    Gitlab::Diff::DiffRefs.new(
216
      base_sha: self.parent_id || Gitlab::Git::BLANK_SHA,
217 218 219 220
      head_sha: self.sha
    )
  end

221
  def pipelines
222
    project.pipelines.where(sha: sha)
223 224
  end

225 226
  def last_pipeline
    @last_pipeline ||= pipelines.last
227 228
  end

229
  def status(ref = nil)
230 231
    @statuses ||= {}

232 233
    return @statuses[ref] if @statuses.key?(ref)

234
    @statuses[ref] = pipelines.latest_status(ref)
235
  end
236

237
  def revert_branch_name
238
    "revert-#{short_id}"
239
  end
Yorick Peterse committed
240

241 242 243
  def cherry_pick_branch_name
    project.repository.next_branch("cherry-pick-#{short_id}", mild: true)
  end
244

245 246 247
  def revert_description(user)
    if merged_merge_request?(user)
      "This reverts merge request #{merged_merge_request(user).to_reference}"
248 249 250 251 252
    else
      "This reverts commit #{sha}"
    end
  end

253
  def revert_message(user)
254
    %Q{Revert "#{title.strip}"\n\n#{revert_description(user)}}
255
  end
256

257 258
  def reverts_commit?(commit, user)
    description? && description.include?(commit.revert_description(user))
259 260
  end

261
  def merge_commit?
262 263 264
    parents.size > 1
  end

265 266 267 268 269
  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
270

271
    @merged_merge_request_hash[current_user]
272 273
  end

274
  def has_been_reverted?(current_user, noteable = self)
Yorick Peterse committed
275 276 277 278 279 280
    ext = all_references(current_user)

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

281
    ext.commits.any? { |commit_ref| commit_ref.reverts_commit?(self, current_user) }
282 283
  end

284 285
  def change_type_title(user)
    merged_merge_request?(user) ? 'merge request' : 'commit'
286 287
  end

288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
  # 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
305
      blob = ::Blob.decorate(Gitlab::Git::Blob.new(name: entry[:name]), @project)
306
      blob.image? || blob.video? ? :raw : :blob
307 308 309 310 311 312 313
    else
      entry[:type]
    end
  rescue Rugged::TreeError
    nil
  end

314
  def raw_diffs(*args)
315
    if Gitlab::GitalyClient.feature_enabled?(:commit_raw_diffs)
316
      Gitlab::GitalyClient::CommitService.new(project.repository).diff_from_parent(self, *args)
317 318 319
    else
      raw.diffs(*args)
    end
320 321
  end

322 323 324
  def raw_deltas
    @deltas ||= Gitlab::GitalyClient.migrate(:commit_deltas) do |is_enabled|
      if is_enabled
325
        Gitlab::GitalyClient::CommitService.new(project.repository).commit_deltas(self)
326 327 328 329 330
      else
        raw.deltas
      end
    end
  end
331

332
  def diffs(diff_options = nil)
333 334 335
    Gitlab::Diff::FileCollection::Commit.new(self, diff_options: diff_options)
  end

P.S.V.R committed
336 337 338 339 340 341 342 343
  def persisted?
    true
  end

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

344 345 346 347 348 349
  WIP_REGEX = /\A\s*(((?i)(\[WIP\]|WIP:|WIP)\s|WIP$))|(fixup!|squash!)\s/.freeze

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

350 351
  private

352 353
  def commit_reference(from_project, referable_commit_id, full: false)
    reference = project.to_reference(from_project, full: full)
354 355 356 357 358 359 360 361

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

362 363 364
  def repo_changes
    changes = { added: [], modified: [], removed: [] }

365
    raw_deltas.each do |diff|
Valery Sizov committed
366 367 368 369 370 371
      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
372 373 374 375 376
      end
    end

    changes
  end
377 378 379 380 381 382 383 384

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