commit.rb 7.88 KB
Newer Older
1
class Commit
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
2
  extend ActiveModel::Naming
3 4

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

10
  attr_mentionable :safe_message, pipeline: :single_line
Yorick Peterse's avatar
Yorick Peterse committed
11 12 13 14

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

16 17
  attr_accessor :project

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

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

24
  class << self
25
    def decorate(commits, project)
26 27 28 29
      commits.map do |commit|
        if commit.kind_of?(Commit)
          commit
        else
30
          self.new(commit, project)
31 32
        end
      end
33
    end
34

35 36
    # Calculate number of lines to render for diffs
    def diff_line_count(diffs)
37
      diffs.reduce(0) { |sum, d| sum + Gitlab::Git::Util.count_lines(d.diff) }
38
    end
39

40
    # Truncate sha to 8 characters
41
    def truncate_sha(sha)
42
      sha[0..7]
43
    end
44 45 46 47 48 49 50

    def max_diff_options
      {
        max_files: DIFF_HARD_LIMIT_FILES,
        max_lines: DIFF_HARD_LIMIT_LINES,
      }
    end
51 52
  end

53
  attr_accessor :raw
Nihad Abbasov's avatar
Nihad Abbasov committed
54

55
  def initialize(raw_commit, project)
56 57
    raise "Nil as raw commit passed" unless raw_commit

58
    @raw = raw_commit
59
    @project = project
60
  end
61

62 63 64 65
  def id
    @raw.id
  end

Robert Speicher's avatar
Robert Speicher committed
66 67 68 69
  def ==(other)
    (self.class === other) && (raw == other.raw)
  end

70 71 72 73 74 75
  def self.reference_prefix
    '@'
  end

  # Pattern used to extract commit references from text
  #
76
  # The SHA can be between 7 and 40 hex characters.
77 78 79
  #
  # This pattern supports cross-project references.
  def self.reference_pattern
80
    @reference_pattern ||= %r{
81
      (?:#{Project.reference_pattern}#{reference_prefix})?
82
      (?<commit>\h{7,40})
83
    }x
84 85
  end

86
  def self.link_reference_pattern
87
    @link_reference_pattern ||= super("commit", /(?<commit>\h{7,40})/)
88 89
  end

90 91
  def to_reference(from_project = nil)
    if cross_project_reference?(from_project)
92 93 94 95 96 97 98
      project.to_reference + self.class.reference_prefix + self.id
    else
      self.id
    end
  end

  def reference_link_text(from_project = nil)
99
    if cross_project_reference?(from_project)
100
      project.to_reference + self.class.reference_prefix + self.short_id
101
    else
102
      self.short_id
103 104 105
    end
  end

106
  def diff_line_count
107
    @diff_line_count ||= Commit::diff_line_count(raw_diffs)
108 109 110
    @diff_line_count
  end

111 112 113 114 115 116 117 118 119 120 121 122
  # Returns a string describing the commit for use in a link title
  #
  # Example
  #
  #   "Commit: Alex Denisov - Project git clone panel"
  def link_title
    "Commit: #{author_name} - #{title}"
  end

  # Returns the commits title.
  #
  # Usually, the commit title is the first line of the commit message.
123 124
  # In case this first line is longer than 100 characters, it is cut off
  # after 80 characters and ellipses (`&hellp;`) are appended.
125
  def title
126 127
    full_title.length > 100 ? full_title[0..79] << "…" : full_title
  end
128

129 130 131
  # Returns the full commits title
  def full_title
    return @full_title if @full_title
132

133 134
    if safe_message.blank?
      @full_title = no_commit_message
135
    else
136
      @full_title = safe_message.split("\n", 2).first
137 138 139 140 141 142 143
    end
  end

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

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

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

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

    data
Kirill Zaitsev's avatar
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 184 185 186 187 188 189 190 191 192 193
    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
194
    end
195 196 197
  end

  def committer
198
    @committer ||= User.find_by_any_email(committer_email.downcase)
199 200
  end

201 202 203 204 205 206 207 208
  def parents
    @parents ||= parent_ids.map { |id| project.commit(id) }
  end

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

209
  def notes
210 211 212
    project.notes.for_commit_id(self.id)
  end

Yorick Peterse's avatar
Yorick Peterse committed
213
  def notes_with_associations
214
    notes.includes(:author)
Yorick Peterse's avatar
Yorick Peterse committed
215 216
  end

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

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

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

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

237 238
  def pipelines
    @pipeline ||= project.pipelines.where(sha: sha)
239 240 241
  end

  def status
242
    return @status if defined?(@status)
243
    @status ||= pipelines.status
244
  end
245

246
  def revert_branch_name
247
    "revert-#{short_id}"
248
  end
Yorick Peterse's avatar
Yorick Peterse committed
249

250 251 252
  def cherry_pick_branch_name
    project.repository.next_branch("cherry-pick-#{short_id}", mild: true)
  end
253

254 255 256 257 258 259 260 261
  def revert_description
    if merged_merge_request
      "This reverts merge request #{merged_merge_request.to_reference}"
    else
      "This reverts commit #{sha}"
    end
  end

262
  def revert_message
263
    %Q{Revert "#{title.strip}"\n\n#{revert_description}}
264
  end
265

266
  def reverts_commit?(commit)
267
    description? && description.include?(commit.revert_description)
268 269
  end

270
  def merge_commit?
271 272 273
    parents.size > 1
  end

274 275 276
  def merged_merge_request
    return @merged_merge_request if defined?(@merged_merge_request)

277
    @merged_merge_request = project.merge_requests.find_by(merge_commit_sha: id) if merge_commit?
278 279
  end

280
  def has_been_reverted?(current_user = nil, noteable = self)
Yorick Peterse's avatar
Yorick Peterse committed
281 282 283 284 285 286 287
    ext = all_references(current_user)

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

    ext.commits.any? { |commit_ref| commit_ref.reverts_commit?(self) }
288 289
  end

290 291 292 293
  def change_type_title
    merged_merge_request ? 'merge request' : 'commit'
  end

294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
  # 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
311 312
      blob = ::Blob.decorate(Gitlab::Git::Blob.new(name: entry[:name]))
      blob.image? || blob.video? ? :raw : :blob
313 314 315 316 317 318 319
    else
      entry[:type]
    end
  rescue Rugged::TreeError
    nil
  end

320 321 322 323 324
  def raw_diffs(*args)
    raw.diffs(*args)
  end

  def diffs(diff_options = nil)
325 326 327
    Gitlab::Diff::FileCollection::Commit.new(self, diff_options: diff_options)
  end

328 329
  private

330 331 332 333
  def find_author_by_any_email
    User.find_by_any_email(author_email.downcase)
  end

334 335 336
  def repo_changes
    changes = { added: [], modified: [], removed: [] }

337
    raw_diffs(deltas_only: true).each do |diff|
Valery Sizov's avatar
Valery Sizov committed
338 339 340 341 342 343
      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
344 345 346 347 348
      end
    end

    changes
  end
349
end