merge_request.rb 10.6 KB
Newer Older
D
Dmitriy Zaporozhets 已提交
1 2 3 4
# == Schema Information
#
# Table name: merge_requests
#
D
Dmitriy Zaporozhets 已提交
5 6 7 8 9 10 11
#  id                :integer          not null, primary key
#  target_branch     :string(255)      not null
#  source_branch     :string(255)      not null
#  source_project_id :integer          not null
#  author_id         :integer
#  assignee_id       :integer
#  title             :string(255)
D
Dmitriy Zaporozhets 已提交
12 13
#  created_at        :datetime
#  updated_at        :datetime
D
Dmitriy Zaporozhets 已提交
14 15 16 17 18
#  milestone_id      :integer
#  state             :string(255)
#  merge_status      :string(255)
#  target_project_id :integer          not null
#  iid               :integer
D
Dmitriy Zaporozhets 已提交
19
#  description       :text
D
Dmitriy Zaporozhets 已提交
20
#  position          :integer          default(0)
D
Dmitriy Zaporozhets 已提交
21
#  locked_at         :datetime
D
Dmitriy Zaporozhets 已提交
22
#
D
Dmitriy Zaporozhets 已提交
23

24
require Rails.root.join("app/models/commit")
25
require Rails.root.join("lib/static_model")
26

D
Dmitriy Zaporozhets 已提交
27
class MergeRequest < ActiveRecord::Base
28
  include InternalId
29 30
  include Issuable
  include Referable
31
  include Sortable
32
  include Taskable
33

34 35
  belongs_to :target_project, foreign_key: :target_project_id, class_name: "Project"
  belongs_to :source_project, foreign_key: :source_project_id, class_name: "Project"
36

37
  has_one :merge_request_diff, dependent: :destroy
D
Dmitriy Zaporozhets 已提交
38

39
  after_create :create_merge_request_diff
D
Dmitriy Zaporozhets 已提交
40
  after_update :update_merge_request_diff
41 42

  delegate :commits, :diffs, :last_commit, :last_commit_short_sha, to: :merge_request_diff, prefix: nil
I
Izaak Alpert 已提交
43

A
Andrey Kumanyaev 已提交
44 45
  attr_accessor :should_remove_source_branch

D
Dmitriy Zaporozhets 已提交
46 47 48 49
  # When this attribute is true some MR validation is ignored
  # It allows us to close or modify broken merge requests
  attr_accessor :allow_broken

D
Dmitriy Zaporozhets 已提交
50 51
  # Temporary fields to store compare vars
  # when creating new merge request
D
Dmitriy Zaporozhets 已提交
52
  attr_accessor :can_be_created, :compare_failed,
53
    :compare_commits, :compare_diffs
D
Dmitriy Zaporozhets 已提交
54

A
Andrew8xx8 已提交
55
  state_machine :state, initial: :opened do
A
Andrew8xx8 已提交
56 57 58 59 60
    event :close do
      transition [:reopened, :opened] => :closed
    end

    event :merge do
D
Dmitriy Zaporozhets 已提交
61
      transition [:reopened, :opened, :locked] => :merged
A
Andrew8xx8 已提交
62 63 64
    end

    event :reopen do
A
Andrew8xx8 已提交
65
      transition closed: :reopened
A
Andrew8xx8 已提交
66 67
    end

68
    event :lock_mr do
D
Dmitriy Zaporozhets 已提交
69 70 71
      transition [:reopened, :opened] => :locked
    end

72
    event :unlock_mr do
D
Dmitriy Zaporozhets 已提交
73 74 75
      transition locked: :reopened
    end

76 77 78 79 80
    after_transition any => :locked do |merge_request, transition|
      merge_request.locked_at = Time.now
      merge_request.save
    end

81
    after_transition locked: (any - :locked) do |merge_request, transition|
82 83 84 85
      merge_request.locked_at = nil
      merge_request.save
    end

A
Andrew8xx8 已提交
86 87 88 89
    state :opened
    state :reopened
    state :closed
    state :merged
D
Dmitriy Zaporozhets 已提交
90
    state :locked
A
Andrew8xx8 已提交
91 92
  end

93 94 95 96 97 98
  state_machine :merge_status, initial: :unchecked do
    event :mark_as_unchecked do
      transition [:can_be_merged, :cannot_be_merged] => :unchecked
    end

    event :mark_as_mergeable do
99
      transition [:unchecked, :cannot_be_merged] => :can_be_merged
100 101 102
    end

    event :mark_as_unmergeable do
103
      transition [:unchecked, :can_be_merged] => :cannot_be_merged
104 105
    end

106
    state :unchecked
107 108
    state :can_be_merged
    state :cannot_be_merged
109 110 111 112 113 114 115 116 117

    around_transition do |merge_request, transition, block|
      merge_request.record_timestamps = false
      begin
        block.call
      ensure
        merge_request.record_timestamps = true
      end
    end
118
  end
119

D
Dmitriy Zaporozhets 已提交
120
  validates :source_project, presence: true, unless: :allow_broken
A
Andrey Kumanyaev 已提交
121
  validates :source_branch, presence: true
I
Izaak Alpert 已提交
122
  validates :target_project, presence: true
A
Andrey Kumanyaev 已提交
123
  validates :target_branch, presence: true
I
Izaak Alpert 已提交
124
  validate :validate_branches
125
  validate :validate_fork
D
Dmitriy Zaporozhets 已提交
126

127
  scope :of_group, ->(group) { where("source_project_id in (:group_project_ids) OR target_project_id in (:group_project_ids)", group_project_ids: group.project_ids) }
A
Andrew8xx8 已提交
128
  scope :merged, -> { with_state(:merged) }
I
Izaak Alpert 已提交
129
  scope :by_branch, ->(branch_name) { where("(source_branch LIKE :branch) OR (target_branch LIKE :branch)", branch: branch_name) }
A
Andrew8xx8 已提交
130
  scope :cared, ->(user) { where('assignee_id = :user OR author_id = :user', user: user.id) }
131
  scope :by_milestone, ->(milestone) { where(milestone_id: milestone) }
I
Izaak Alpert 已提交
132
  scope :in_projects, ->(project_ids) { where("source_project_id in (:project_ids) OR target_project_id in (:project_ids)", project_ids: project_ids) }
133
  scope :of_projects, ->(ids) { where(target_project_id: ids) }
134 135 136
  # Closed scope for merge request should return
  # both merged and closed mr's
  scope :closed, -> { with_states(:closed, :merged) }
137
  scope :declined, -> { with_states(:closed) }
138

139 140 141 142 143 144 145 146 147 148 149 150 151 152
  def self.reference_prefix
    '!'
  end

  def to_reference(from_project = nil)
    reference = "#{self.class.reference_prefix}#{iid}"

    if cross_project_reference?(from_project)
      reference = project.to_reference + reference
    end

    reference
  end

153
  def validate_branches
154
    if target_project == source_project && target_branch == source_branch
I
Izaak Alpert 已提交
155
      errors.add :branch_conflict, "You can not use same project/branch for source and target"
156
    end
157

158
    if opened? || reopened?
I
Izaak Alpert 已提交
159
      similar_mrs = self.target_project.merge_requests.where(source_branch: source_branch, target_branch: target_branch, source_project_id: source_project.id).opened
160 161
      similar_mrs = similar_mrs.where('id not in (?)', self.id) if self.id
      if similar_mrs.any?
J
jubianchi 已提交
162 163 164 165
        errors.add :validate_branches,
                   "Cannot Create: This merge request already exists: #{
                   similar_mrs.pluck(:title)
                   }"
166
      end
167
    end
168 169
  end

170
  def validate_fork
171 172 173
    return true unless target_project && source_project

    if target_project == source_project
174 175 176 177 178 179 180
      true
    else
      # If source and target projects are different
      # we should check if source project is actually a fork of target project
      if source_project.forked_from?(target_project)
        true
      else
J
jubianchi 已提交
181 182
        errors.add :validate_fork,
                   'Source project is not a fork of target project'
183 184 185 186
      end
    end
  end

D
Dmitriy Zaporozhets 已提交
187 188 189 190 191 192 193
  def update_merge_request_diff
    if source_branch_changed? || target_branch_changed?
      reload_code
      mark_as_unchecked
    end
  end

194
  def reload_code
195
    if merge_request_diff && open?
196 197
      merge_request_diff.reload_content
    end
198 199
  end

200
  def check_if_can_be_merged
201 202 203 204 205
    if Gitlab::Satellite::MergeAction.new(self.author, self).can_be_merged?
      mark_as_mergeable
    else
      mark_as_unmergeable
    end
206 207
  end

D
Dmitriy Zaporozhets 已提交
208
  def merge_event
I
Izaak Alpert 已提交
209
    self.target_project.events.where(target_id: self.id, target_type: "MergeRequest", action: Event::MERGED).last
D
Dmitriy Zaporozhets 已提交
210 211
  end

212
  def closed_event
I
Izaak Alpert 已提交
213
    self.target_project.events.where(target_id: self.id, target_type: "MergeRequest", action: Event::CLOSED).last
214 215
  end

D
Dmitriy Zaporozhets 已提交
216
  def automerge!(current_user, commit_message = nil)
217 218
    return unless automergeable?

219 220 221
    MergeRequests::AutoMergeService.
      new(target_project, current_user).
      execute(self, commit_message)
222
  end
R
randx 已提交
223

224 225 226 227
  def open?
    opened? || reopened?
  end

228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
  def work_in_progress?
    title =~ /\A\[?WIP\]?:? /i
  end

  def automergeable?
    open? && !work_in_progress? && can_be_merged?
  end

  def automerge_status
    if work_in_progress?
      "work_in_progress"
    else
      merge_status_name
    end
  end

244
  def mr_and_commit_notes
245 246 247 248
    # Fetch comments only from last 100 commits
    commits_for_notes_limit = 100
    commit_ids = commits.last(commits_for_notes_limit).map(&:id)

249 250 251
    Note.where(
      "(project_id = :target_project_id AND noteable_type = 'MergeRequest' AND noteable_id = :mr_id) OR" +
      "(project_id = :source_project_id AND noteable_type = 'Commit' AND commit_id IN (:commit_ids))",
252
      mr_id: id,
253 254 255
      commit_ids: commit_ids,
      target_project_id: target_project_id,
      source_project_id: source_project_id
256
    )
257
  end
258

259 260 261
  # Returns the raw diff for this merge request
  #
  # see "git diff"
I
Izaak Alpert 已提交
262 263
  def to_diff(current_user)
    Gitlab::Satellite::MergeAction.new(current_user, self).diff_in_satellite
264 265 266 267 268
  end

  # Returns the commit as a series of email patches.
  #
  # see "git format-patch"
I
Izaak Alpert 已提交
269 270
  def to_patch(current_user)
    Gitlab::Satellite::MergeAction.new(current_user, self).format_patch
271
  end
272

K
Kirill Zaitsev 已提交
273 274 275 276 277 278 279 280
  def hook_attrs
    attrs = {
      source: source_project.hook_attrs,
      target: target_project.hook_attrs,
      last_commit: nil
    }

    unless last_commit.nil?
281
      attrs.merge!(last_commit: last_commit.hook_attrs)
K
Kirill Zaitsev 已提交
282 283 284 285 286
    end

    attributes.merge!(attrs)
  end

I
Izaak Alpert 已提交
287 288 289 290
  def for_fork?
    target_project != source_project
  end

291 292 293 294
  def project
    target_project
  end

295
  # Return the set of issues that will be closed if this merge request is accepted.
296
  def closes_issues(current_user = self.author)
297
    if target_branch == project.default_branch
298
      issues = commits.flat_map { |c| c.closes_issues(current_user) }
D
Douwe Maan 已提交
299 300
      issues.push(*Gitlab::ClosingIssueExtractor.new(project, current_user).
                  closed_by_message(description))
301
      issues.uniq.sort_by(&:id)
302 303 304 305 306
    else
      []
    end
  end

307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
  def target_project_path
    if target_project
      target_project.path_with_namespace
    else
      "(removed)"
    end
  end

  def source_project_path
    if source_project
      source_project.path_with_namespace
    else
      "(removed)"
    end
  end

323 324 325 326 327 328 329 330
  def source_project_namespace
    if source_project && source_project.namespace
      source_project.namespace.path
    else
      "(removed)"
    end
  end

331 332 333 334 335 336 337 338
  def target_project_namespace
    if target_project && target_project.namespace
      target_project.namespace.path
    else
      "(removed)"
    end
  end

339 340 341 342 343 344 345 346 347 348 349 350
  def source_branch_exists?
    return false unless self.source_project

    self.source_project.repository.branch_names.include?(self.source_branch)
  end

  def target_branch_exists?
    return false unless self.target_project

    self.target_project.repository.branch_names.include?(self.target_branch)
  end

D
Drew Blessing 已提交
351 352 353 354 355 356 357 358 359
  # Reset merge request events cache
  #
  # Since we do cache @event we need to reset cache in special cases:
  # * when a merge request is updated
  # Events cache stored like  events/23-20130109142513.
  # The cache key includes updated_at timestamp.
  # Thus it will automatically generate a new fragment
  # when the event is updated because the key changes.
  def reset_events_cache
360
    Event.reset_event_cache_for(self)
D
Drew Blessing 已提交
361 362
  end

363 364 365
  def merge_commit_message
    message = "Merge branch '#{source_branch}' into '#{target_branch}'"
    message << "\n\n"
D
Dmitriy Zaporozhets 已提交
366
    message << title.to_s
367
    message << "\n\n"
D
Dmitriy Zaporozhets 已提交
368
    message << description.to_s
369 370
    message << "\n\n"
    message << "See merge request !#{iid}"
D
Dmitriy Zaporozhets 已提交
371
    message
372
  end
373 374

  # Return array of possible target branches
S
Steven Burgart 已提交
375
  # depends on target project of MR
376 377 378 379 380 381 382 383 384
  def target_branches
    if target_project.nil?
      []
    else
      target_project.repository.branch_names
    end
  end

  # Return array of possible source branches
S
Steven Burgart 已提交
385
  # depends on source project of MR
386 387 388 389 390 391 392
  def source_branches
    if source_project.nil?
      []
    else
      source_project.repository.branch_names
    end
  end
393 394

  def locked_long_ago?
B
Ben Bodenmiller 已提交
395 396 397
    return false unless locked?

    locked_at.nil? || locked_at < (Time.now - 1.day)
398
  end
D
Dmitriy Zaporozhets 已提交
399
end