BigW Consortium Gitlab

commit.rb 7.8 KB
Newer Older
1
class Commit
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 committed
11 12 13 14

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

120 121 122
  # Returns the full commits title
  def full_title
    return @full_title if @full_title
123

124 125
    if safe_message.blank?
      @full_title = no_commit_message
126
    else
127
      @full_title = safe_message.split("\n", 2).first
128 129 130 131 132 133 134
    end
  end

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

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

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

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

    data
Kirill Zaitsev committed
165 166
  end

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

173
  def author
174 175 176 177 178 179 180 181 182 183 184
    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
185
    end
186 187 188
  end

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

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

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

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

Yorick Peterse committed
204
  def notes_with_associations
205
    notes.includes(:author)
Yorick Peterse committed
206 207
  end

208 209
  def method_missing(m, *args, &block)
    @raw.send(m, *args, &block)
210
  end
211

212 213
  def respond_to_missing?(method, include_private = false)
    @raw.respond_to?(method, include_private) || super
214
  end
215

216 217 218 219 220
  # Truncate sha to 8 characters
  def short_id
    @raw.short_id(7)
  end

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

228
  def pipelines
229
    project.pipelines.where(sha: sha)
230 231
  end

232
  def status(ref = nil)
233 234
    @statuses ||= {}

235 236
    if @statuses.key?(ref)
      @statuses[ref]
237
    elsif ref
238
      @statuses[ref] = pipelines.where(ref: ref).status
239
    else
240
      @statuses[ref] = pipelines.status
241
    end
242
  end
243

244
  def revert_branch_name
245
    "revert-#{short_id}"
246
  end
Yorick Peterse committed
247

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

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

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

264
  def reverts_commit?(commit)
265
    description? && description.include?(commit.revert_description)
266 267
  end

268
  def merge_commit?
269 270 271
    parents.size > 1
  end

272 273 274
  def merged_merge_request
    return @merged_merge_request if defined?(@merged_merge_request)

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

278
  def has_been_reverted?(current_user = nil, noteable = self)
Yorick Peterse committed
279 280 281 282 283 284 285
    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) }
286 287
  end

288 289 290 291
  def change_type_title
    merged_merge_request ? 'merge request' : 'commit'
  end

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

318 319 320 321 322
  def raw_diffs(*args)
    raw.diffs(*args)
  end

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

326 327
  private

328 329 330 331
  def find_author_by_any_email
    User.find_by_any_email(author_email.downcase)
  end

332 333 334
  def repo_changes
    changes = { added: [], modified: [], removed: [] }

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

    changes
  end
347
end