merge_request.rb 10.0 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 Issuable
29
  include Taskable
30
  include InternalId
31
  include Sortable
32

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

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

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

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

A
Andrey Kumanyaev 已提交
43 44
  attr_accessor :should_remove_source_branch

D
Dmitriy Zaporozhets 已提交
45 46 47 48
  # 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 已提交
49 50
  # Temporary fields to store compare vars
  # when creating new merge request
D
Dmitriy Zaporozhets 已提交
51
  attr_accessor :can_be_created, :compare_failed,
52
    :compare_commits, :compare_diffs
D
Dmitriy Zaporozhets 已提交
53

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

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

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

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

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

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

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

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

92 93 94 95 96 97
  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
98
      transition [:unchecked, :cannot_be_merged] => :can_be_merged
99 100 101
    end

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

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

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

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

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

138
  def validate_branches
139
    if target_project == source_project && target_branch == source_branch
I
Izaak Alpert 已提交
140
      errors.add :branch_conflict, "You can not use same project/branch for source and target"
141
    end
142

143
    if opened? || reopened?
I
Izaak Alpert 已提交
144
      similar_mrs = self.target_project.merge_requests.where(source_branch: source_branch, target_branch: target_branch, source_project_id: source_project.id).opened
145 146
      similar_mrs = similar_mrs.where('id not in (?)', self.id) if self.id
      if similar_mrs.any?
J
jubianchi 已提交
147 148 149 150
        errors.add :validate_branches,
                   "Cannot Create: This merge request already exists: #{
                   similar_mrs.pluck(:title)
                   }"
151
      end
152
    end
153 154
  end

155
  def validate_fork
156 157 158
    return true unless target_project && source_project

    if target_project == source_project
159 160 161 162 163 164 165
      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 已提交
166 167
        errors.add :validate_fork,
                   'Source project is not a fork of target project'
168 169 170 171
      end
    end
  end

D
Dmitriy Zaporozhets 已提交
172 173 174 175 176 177 178
  def update_merge_request_diff
    if source_branch_changed? || target_branch_changed?
      reload_code
      mark_as_unchecked
    end
  end

179
  def reload_code
180
    if merge_request_diff && open?
181 182
      merge_request_diff.reload_content
    end
183 184
  end

185
  def check_if_can_be_merged
186 187 188 189 190
    if Gitlab::Satellite::MergeAction.new(self.author, self).can_be_merged?
      mark_as_mergeable
    else
      mark_as_unmergeable
    end
191 192
  end

D
Dmitriy Zaporozhets 已提交
193
  def merge_event
I
Izaak Alpert 已提交
194
    self.target_project.events.where(target_id: self.id, target_type: "MergeRequest", action: Event::MERGED).last
D
Dmitriy Zaporozhets 已提交
195 196
  end

197
  def closed_event
I
Izaak Alpert 已提交
198
    self.target_project.events.where(target_id: self.id, target_type: "MergeRequest", action: Event::CLOSED).last
199 200
  end

D
Dmitriy Zaporozhets 已提交
201
  def automerge!(current_user, commit_message = nil)
202 203 204
    MergeRequests::AutoMergeService.
      new(target_project, current_user).
      execute(self, commit_message)
205
  end
R
randx 已提交
206

207 208 209 210
  def open?
    opened? || reopened?
  end

211
  def mr_and_commit_notes
212 213 214 215
    # Fetch comments only from last 100 commits
    commits_for_notes_limit = 100
    commit_ids = commits.last(commits_for_notes_limit).map(&:id)

216 217 218 219 220
    project.notes.where(
      "(noteable_type = 'MergeRequest' AND noteable_id = :mr_id) OR (noteable_type = 'Commit' AND commit_id IN (:commit_ids))",
      mr_id: id,
      commit_ids: commit_ids
    )
221
  end
222

223 224 225
  # Returns the raw diff for this merge request
  #
  # see "git diff"
I
Izaak Alpert 已提交
226 227
  def to_diff(current_user)
    Gitlab::Satellite::MergeAction.new(current_user, self).diff_in_satellite
228 229 230 231 232
  end

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

K
Kirill Zaitsev 已提交
237 238 239 240 241 242 243 244 245 246 247 248 249 250
  def hook_attrs
    attrs = {
      source: source_project.hook_attrs,
      target: target_project.hook_attrs,
      last_commit: nil
    }

    unless last_commit.nil?
      attrs.merge!(last_commit: last_commit.hook_attrs(source_project))
    end

    attributes.merge!(attrs)
  end

I
Izaak Alpert 已提交
251 252 253 254
  def for_fork?
    target_project != source_project
  end

255 256 257 258
  def project
    target_project
  end

259
  # Return the set of issues that will be closed if this merge request is accepted.
260
  def closes_issues(current_user = self.author)
261
    if target_branch == project.default_branch
262
      issues = commits.flat_map { |c| c.closes_issues(project, current_user) }
D
Douwe Maan 已提交
263 264
      issues.push(*Gitlab::ClosingIssueExtractor.new(project, current_user).
                  closed_by_message(description))
265
      issues.uniq.sort_by(&:id)
266 267 268 269 270 271 272 273 274 275
    else
      []
    end
  end

  # Mentionable override.
  def gfm_reference
    "merge request !#{iid}"
  end

276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
  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

292 293 294 295 296 297 298 299
  def source_project_namespace
    if source_project && source_project.namespace
      source_project.namespace.path
    else
      "(removed)"
    end
  end

300 301 302 303 304 305 306 307
  def target_project_namespace
    if target_project && target_project.namespace
      target_project.namespace.path
    else
      "(removed)"
    end
  end

308 309 310 311 312 313 314 315 316 317 318 319
  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 已提交
320 321 322 323 324 325 326 327 328
  # 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
329
    Event.reset_event_cache_for(self)
D
Drew Blessing 已提交
330 331
  end

332 333 334
  def merge_commit_message
    message = "Merge branch '#{source_branch}' into '#{target_branch}'"
    message << "\n\n"
D
Dmitriy Zaporozhets 已提交
335
    message << title.to_s
336
    message << "\n\n"
D
Dmitriy Zaporozhets 已提交
337
    message << description.to_s
338 339
    message << "\n\n"
    message << "See merge request !#{iid}"
D
Dmitriy Zaporozhets 已提交
340
    message
341
  end
342 343

  # Return array of possible target branches
S
Steven Burgart 已提交
344
  # depends on target project of MR
345 346 347 348 349 350 351 352 353
  def target_branches
    if target_project.nil?
      []
    else
      target_project.repository.branch_names
    end
  end

  # Return array of possible source branches
S
Steven Burgart 已提交
354
  # depends on source project of MR
355 356 357 358 359 360 361
  def source_branches
    if source_project.nil?
      []
    else
      source_project.repository.branch_names
    end
  end
362 363

  def locked_long_ago?
B
Ben Bodenmiller 已提交
364 365 366
    return false unless locked?

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