This instance will be upgraded to Heptapod 0.31.0rc on 2022-05-19 at 11:00 UTC+2 (a few minutes of down time)

merge_request.rb 30.1 KB
Newer Older
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
1
class MergeRequest < ActiveRecord::Base
2
  include NonatomicInternalId
3
  include Issuable
4
  include Noteable
5
  include Referable
6
  include IgnorableColumn
7
  include TimeTrackable
8
9
  include ManualInverseAssociation
  include EachBatch
10
  include ThrottledTouch
11
  include Gitlab::Utils::StrongMemoize
12

13
  ignore_column :locked_at,
14
15
                :ref_fetched,
                :deleted_at
16

17
18
  belongs_to :target_project, class_name: "Project"
  belongs_to :source_project, class_name: "Project"
19
  belongs_to :merge_user, class_name: "User"
20

21
  has_many :merge_request_diffs
22

23
  has_one :merge_request_diff,
24
    -> { order('merge_request_diffs.id DESC') }, inverse_of: :merge_request
25

26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
  belongs_to :latest_merge_request_diff, class_name: 'MergeRequestDiff'
  manual_inverse_association :latest_merge_request_diff, :merge_request

  # This is the same as latest_merge_request_diff unless:
  # 1. There are arguments - in which case we might be trying to force-reload.
  # 2. This association is already loaded.
  # 3. The latest diff does not exist.
  #
  # The second one in particular is important - MergeRequestDiff#merge_request
  # is the inverse of MergeRequest#merge_request_diff, which means it may not be
  # the latest diff, because we could have loaded any diff from this particular
  # MR. If we haven't already loaded a diff, then it's fine to load the latest.
  def merge_request_diff(*args)
    fallback = latest_merge_request_diff if args.empty? && !association(:merge_request_diff).loaded?

    fallback || super
  end

44
45
  belongs_to :head_pipeline, foreign_key: "head_pipeline_id", class_name: "Ci::Pipeline"

46
  has_many :events, as: :target, dependent: :destroy # rubocop:disable Cop/ActiveRecordDependent
47

48
49
50
  has_many :merge_requests_closing_issues,
    class_name: 'MergeRequestsClosingIssues',
    dependent: :delete_all # rubocop:disable Cop/ActiveRecordDependent
51

52
53
  belongs_to :assignee, class_name: "User"

54
  serialize :merge_params, Hash # rubocop:disable Cop/ActiveRecordSerialize
55

56
  after_create :ensure_merge_request_diff, unless: :importing?
57
  after_update :clear_memoized_shas
58
  after_update :reload_diff_if_branch_changed
59

Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
60
61
62
63
  # When this attribute is true some MR validation is ignored
  # It allows us to close or modify broken merge requests
  attr_accessor :allow_broken

64
65
  # Temporary fields to store compare vars
  # when creating new merge request
66
  attr_accessor :can_be_created, :compare_commits, :diff_options, :compare
67

Andrew8xx8's avatar
Andrew8xx8 committed
68
  state_machine :state, initial: :opened do
69
    event :close do
70
      transition [:opened] => :closed
71
72
    end

73
    event :mark_as_merged do
74
      transition [:opened, :locked] => :merged
75
76
77
    end

    event :reopen do
78
      transition closed: :opened
79
80
    end

81
    event :lock_mr do
82
      transition [:opened] => :locked
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
83
84
    end

85
    event :unlock_mr do
86
      transition locked: :opened
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
87
88
    end

89
90
91
92
93
94
95
96
    before_transition any => :opened do |merge_request|
      merge_request.merge_jid = nil

      merge_request.run_after_commit do
        UpdateHeadPipelineForMergeRequestWorker.perform_async(merge_request.id)
      end
    end

97
98
99
    state :opened
    state :closed
    state :merged
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
100
    state :locked
101
102
  end

103
104
105
106
107
108
  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
109
      transition [:unchecked, :cannot_be_merged] => :can_be_merged
110
111
112
    end

    event :mark_as_unmergeable do
113
      transition [:unchecked, :can_be_merged] => :cannot_be_merged
114
115
    end

116
    state :unchecked
117
118
    state :can_be_merged
    state :cannot_be_merged
119
120

    around_transition do |merge_request, transition, block|
121
      Gitlab::Timeless.timeless(merge_request, &block)
122
    end
123
  end
124

125
  validates :source_project, presence: true, unless: [:allow_broken, :importing?, :closed_without_fork?]
Andrey Kumanyaev's avatar
Andrey Kumanyaev committed
126
  validates :source_branch, presence: true
127
  validates :target_project, presence: true
Andrey Kumanyaev's avatar
Andrey Kumanyaev committed
128
  validates :target_branch, presence: true
129
  validates :merge_user, presence: true, if: :merge_when_pipeline_succeeds?, unless: :importing?
130
131
  validate :validate_branches, unless: [:allow_broken, :importing?, :closed_without_fork?]
  validate :validate_fork, unless: :closed_without_fork?
132
  validate :validate_target_project, on: :create
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
133

134
135
136
  scope :by_source_or_target_branch, ->(branch_name) do
    where("source_branch = :branch OR target_branch = :branch", branch: branch_name)
  end
137
  scope :by_milestone, ->(milestone) { where(milestone_id: milestone) }
138
  scope :of_projects, ->(ids) { where(target_project_id: ids) }
139
  scope :from_project, ->(project) { where(source_project_id: project.id) }
140
141
  scope :merged, -> { with_state(:merged) }
  scope :closed_and_merged, -> { with_states(:closed, :merged) }
142
  scope :from_source_branches, ->(branches) { where(source_branch: branches) }
143
144
145
  scope :by_commit_sha, ->(sha) do
    where('EXISTS (?)', MergeRequestDiff.select(1).where('merge_requests.latest_merge_request_diff_id = merge_request_diffs.id').by_commit_sha(sha)).reorder(nil)
  end
146
147
  scope :join_project, -> { joins(:target_project) }
  scope :references_project, -> { references(:target_project) }
148
149
150
151
152
  scope :assigned, -> { where("assignee_id IS NOT NULL") }
  scope :unassigned, -> { where("assignee_id IS NULL") }
  scope :assigned_to, ->(u) { where(assignee_id: u.id)}

  participant :assignee
153

154
155
  after_save :keep_around_commit

156
157
158
159
  def self.reference_prefix
    '!'
  end

160
  def rebase_in_progress?
161
162
163
    strong_memoize(:rebase_in_progress) do
      # The source project can be deleted
      next false unless source_project
164

165
166
      source_project.repository.rebase_in_progress?(id)
    end
167
168
  end

169
170
171
  # Use this method whenever you need to make sure the head_pipeline is synced with the
  # branch head commit, for example checking if a merge request can be merged.
  # For more information check: https://gitlab.com/gitlab-org/gitlab-ce/issues/40004
172
  def actual_head_pipeline
173
    head_pipeline&.sha == diff_head_sha ? head_pipeline : nil
174
175
  end

176
177
178
179
  # Pattern used to extract `!123` merge request references from text
  #
  # This pattern supports cross-project references.
  def self.reference_pattern
180
    @reference_pattern ||= %r{
181
      (#{Project.reference_pattern})?
182
183
184
185
      #{Regexp.escape(reference_prefix)}(?<merge_request>\d+)
    }x
  end

186
  def self.link_reference_pattern
187
    @link_reference_pattern ||= super("merge_requests", /(?<merge_request>\d+)/)
188
189
  end

190
191
192
193
  def self.reference_valid?(reference)
    reference.to_i > 0 && reference.to_i <= Gitlab::Database::MAX_INT_VALUE
  end

194
195
196
197
  def self.project_foreign_key
    'target_project_id'
  end

198
199
200
201
202
203
204
205
206
207
208
  # Returns all the merge requests from an ActiveRecord:Relation.
  #
  # This method uses a UNION as it usually operates on the result of
  # ProjectsFinder#execute. PostgreSQL in particular doesn't always like queries
  # using multiple sub-queries especially when combined with an OR statement.
  # UNIONs on the other hand perform much better in these cases.
  #
  # relation - An ActiveRecord::Relation that returns a list of Projects.
  #
  # Returns an ActiveRecord::Relation.
  def self.in_projects(relation)
209
210
211
212
    # unscoping unnecessary conditions that'll be applied
    # when executing `where("merge_requests.id IN (#{union.to_sql})")`
    source = unscoped.where(source_project_id: relation).select(:id)
    target = unscoped.where(target_project_id: relation).select(:id)
213
214
    union  = Gitlab::SQL::Union.new([source, target])

215
    where("merge_requests.id IN (#{union.to_sql})") # rubocop:disable GitlabSecurity/SqlInjection
216
217
  end

218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
  # This is used after project import, to reset the IDs to the correct
  # values. It is not intended to be called without having already scoped the
  # relation.
  def self.set_latest_merge_request_diff_ids!
    update = '
      latest_merge_request_diff_id = (
        SELECT MAX(id)
        FROM merge_request_diffs
        WHERE merge_requests.id = merge_request_diffs.merge_request_id
      )'.squish

    self.each_batch do |batch|
      batch.update_all(update)
    end
  end

Thomas Balthazar's avatar
Thomas Balthazar committed
234
235
236
237
238
239
240
241
242
243
244
245
246
247
  WIP_REGEX = /\A\s*(\[WIP\]\s*|WIP:\s*|WIP\s+)+\s*/i.freeze

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

  def self.wipless_title(title)
    title.sub(WIP_REGEX, "")
  end

  def self.wip_title(title)
    work_in_progress?(title) ? title : "WIP: #{title}"
  end

248
249
250
251
252
253
  # Verifies if title has changed not taking into account WIP prefix
  # for merge requests.
  def wipless_title_changed(old_title)
    self.class.wipless_title(old_title) != self.wipless_title
  end

254
  def hook_attrs
255
    Gitlab::HookData::MergeRequestBuilder.new(self).build
256
257
  end

258
259
260
261
262
263
264
265
  # Returns a Hash of attributes to be used for Twitter card metadata
  def card_attributes
    {
      'Author'   => author.try(:name),
      'Assignee' => assignee.try(:name)
    }
  end

266
  # These method are needed for compatibility with issues to not mess view and other code
267
268
269
270
  def assignees
    Array(assignee)
  end

271
272
273
274
275
276
277
278
  def assignee_ids
    Array(assignee_id)
  end

  def assignee_ids=(ids)
    write_attribute(:assignee_id, ids.last)
  end

279
280
281
282
  def assignee_or_author?(user)
    author_id == user.id || assignee_id == user.id
  end

283
  # `from` argument can be a Namespace or Project.
284
  def to_reference(from = nil, full: false)
285
286
    reference = "#{self.class.reference_prefix}#{iid}"

287
    "#{project.to_reference(from, full: full)}#{reference}"
288
289
  end

290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
  def commits
    if persisted?
      merge_request_diff.commits
    elsif compare_commits
      compare_commits.reverse
    else
      []
    end
  end

  def commits_count
    if persisted?
      merge_request_diff.commits_count
    elsif compare_commits
      compare_commits.size
    else
      0
    end
  end

  def commit_shas
    if persisted?
      merge_request_diff.commit_shas
    elsif compare_commits
314
      compare_commits.to_a.reverse.map(&:sha)
315
    else
316
      Array(diff_head_sha)
317
318
319
    end
  end

320
321
322
  # Calls `MergeWorker` to proceed with the merge process and
  # updates `merge_jid` with the MergeWorker#jid.
  # This helps tracking enqueued and ongoing merge jobs.
323
  def merge_async(user_id, params)
324
325
326
327
    jid = MergeWorker.perform_async(id, user_id, params)
    update_column(:merge_jid, jid)
  end

328
329
  def first_commit
    merge_request_diff ? merge_request_diff.first_commit : compare_commits.first
330
  end
331

332
  def raw_diffs(*args)
333
    merge_request_diff ? merge_request_diff.raw_diffs(*args) : compare.raw_diffs(*args)
334
335
  end

336
  def diffs(diff_options = {})
337
    if compare
338
      # When saving MR diffs, `expanded` is implicitly added (because we need
339
340
      # to save the entire contents to the DB), so add that here for
      # consistency.
341
      compare.diffs(diff_options.merge(expanded: true))
342
    else
343
      merge_request_diff.diffs(diff_options)
344
    end
345
346
  end

347
  def diff_size
348
349
    # Calling `merge_request_diff.diffs.real_size` will also perform
    # highlighting, which we don't need here.
350
    merge_request_diff&.real_size || diffs.real_size
351
352
  end

353
  def diff_base_commit
354
    if persisted?
355
      merge_request_diff.base_commit
356
357
    else
      branch_merge_base_commit
358
359
360
361
362
363
364
365
    end
  end

  def diff_start_commit
    if persisted?
      merge_request_diff.start_commit
    else
      target_branch_head
366
367
368
    end
  end

369
370
371
372
373
374
375
376
377
  def diff_head_commit
    if persisted?
      merge_request_diff.head_commit
    else
      source_branch_head
    end
  end

  def diff_start_sha
378
379
380
381
382
    if persisted?
      merge_request_diff.start_commit_sha
    else
      target_branch_head.try(:sha)
    end
383
384
385
  end

  def diff_base_sha
386
387
388
389
390
    if persisted?
      merge_request_diff.base_commit_sha
    else
      branch_merge_base_commit.try(:sha)
    end
391
392
393
  end

  def diff_head_sha
394
395
396
397
398
    if persisted?
      merge_request_diff.head_commit_sha
    else
      source_branch_head.try(:sha)
    end
399
400
401
402
403
404
405
406
  end

  # When importing a pull request from GitHub, the old and new branches may no
  # longer actually exist by those names, but we need to recreate the merge
  # request diff with the right source and target shas.
  # We use these attributes to force these to the intended values.
  attr_writer :target_branch_sha, :source_branch_sha

407
408
409
410
411
412
413
414
415
416
417
418
419
420
  def source_branch_ref
    return @source_branch_sha if @source_branch_sha
    return unless source_branch

    Gitlab::Git::BRANCH_REF_PREFIX + source_branch
  end

  def target_branch_ref
    return @target_branch_sha if @target_branch_sha
    return unless target_branch

    Gitlab::Git::BRANCH_REF_PREFIX + target_branch
  end

421
  def source_branch_head
422
423
424
425
426
    strong_memoize(:source_branch_head) do
      if source_project && source_branch_ref
        source_project.repository.commit(source_branch_ref)
      end
    end
427
428
429
  end

  def target_branch_head
430
431
432
    strong_memoize(:target_branch_head) do
      target_project.repository.commit(target_branch_ref)
    end
433
434
  end

435
436
437
438
439
440
441
442
443
  def branch_merge_base_commit
    start_sha = target_branch_sha
    head_sha  = source_branch_sha

    if start_sha && head_sha
      target_project.merge_base_commit(start_sha, head_sha)
    end
  end

444
  def target_branch_sha
445
    @target_branch_sha || target_branch_head.try(:sha)
446
447
448
  end

  def source_branch_sha
449
    @source_branch_sha || source_branch_head.try(:sha)
450
451
  end

452
  def diff_refs
453
    if persisted?
454
      merge_request_diff.diff_refs
455
    else
456
457
458
459
460
      Gitlab::Diff::DiffRefs.new(
        base_sha:  diff_base_sha,
        start_sha: diff_start_sha,
        head_sha:  diff_head_sha
      )
461
    end
462
463
  end

464
465
466
467
  def branch_merge_base_sha
    branch_merge_base_commit.try(:sha)
  end

468
  def validate_branches
469
    if target_project == source_project && target_branch == source_branch
470
      errors.add :branch_conflict, "You can not use same project/branch for source and target"
471
    end
472

473
    if opened?
474
      similar_mrs = self.target_project.merge_requests.where(source_branch: source_branch, target_branch: target_branch, source_project_id: source_project.try(:id)).opened
475
476
      similar_mrs = similar_mrs.where('id not in (?)', self.id) if self.id
      if similar_mrs.any?
477
        errors.add :validate_branches,
Gabriel Mazetto's avatar
Gabriel Mazetto committed
478
                   "Cannot Create: This merge request already exists: #{similar_mrs.pluck(:title)}"
479
      end
480
    end
481
482
  end

483
484
485
486
487
488
  def validate_target_project
    return true if target_project.merge_requests_enabled?

    errors.add :base, 'Target project has disabled merge requests'
  end

489
  def validate_fork
490
    return true unless target_project && source_project
491
    return true if target_project == source_project
492
    return true unless source_project_missing?
493

494
    errors.add :validate_fork,
495
               'Source project is not a fork of the target project'
496
497
  end

498
  def merge_ongoing?
499
500
    # While the MergeRequest is locked, it should present itself as 'merge ongoing'.
    # The unlocking process is handled by StuckMergeJobsWorker scheduled in Cron.
501
502
503
    return true if locked?

    !!merge_jid && !merged? && Gitlab::SidekiqStatus.running?(merge_jid)
504
505
  end

506
  def closed_without_fork?
507
    closed? && source_project_missing?
508
509
  end

510
  def source_project_missing?
511
512
513
    return false unless for_fork?
    return true unless source_project

514
    !source_project.in_fork_network_of?(target_project)
515
516
  end

517
  def reopenable?
518
    closed? && !source_project_missing? && source_branch_exists?
Katarzyna Kobierska's avatar
Katarzyna Kobierska committed
519
520
  end

521
522
  def ensure_merge_request_diff
    merge_request_diff || create_merge_request_diff
523
524
  end

525
  def create_merge_request_diff
526
    fetch_ref!
527

528
529
530
531
532
    # n+1: https://gitlab.com/gitlab-org/gitlab-ce/issues/37435
    Gitlab::GitalyClient.allow_n_plus_1_calls do
      merge_request_diffs.create
      reload_merge_request_diff
    end
533
534
535
536
537
538
  end

  def reload_merge_request_diff
    merge_request_diff(true)
  end

539
540
  def merge_request_diff_for(diff_refs_or_sha)
    @merge_request_diffs_by_diff_refs_or_sha ||= Hash.new do |h, diff_refs_or_sha|
541
      diffs = merge_request_diffs.viewable
542
543
544
545
546
547
      h[diff_refs_or_sha] =
        if diff_refs_or_sha.is_a?(Gitlab::Diff::DiffRefs)
          diffs.find_by_diff_refs(diff_refs_or_sha)
        else
          diffs.find_by(head_commit_sha: diff_refs_or_sha)
        end
Douwe Maan's avatar
Douwe Maan committed
548
549
    end

550
    @merge_request_diffs_by_diff_refs_or_sha[diff_refs_or_sha]
551
552
  end

553
554
555
556
557
558
559
560
561
562
563
  def version_params_for(diff_refs)
    if diff = merge_request_diff_for(diff_refs)
      { diff_id: diff.id }
    elsif diff = merge_request_diff_for(diff_refs.head_sha)
      {
        diff_id: diff.id,
        start_sha: diff_refs.start_sha
      }
    end
  end

564
565
566
567
568
569
570
  def clear_memoized_shas
    @target_branch_sha = @source_branch_sha = nil

    clear_memoization(:source_branch_head)
    clear_memoization(:target_branch_head)
  end

571
  def reload_diff_if_branch_changed
572
573
    if (source_branch_changed? || target_branch_changed?) &&
        (source_branch_head && target_branch_head)
574
      reload_diff
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
575
576
577
    end
  end

578
  def reload_diff(current_user = nil)
579
580
    return unless open?

581
    old_diff_refs = self.diff_refs
582
583
584
    new_diff = create_merge_request_diff

    MergeRequests::MergeRequestDiffCacheService.new.execute(self, new_diff)
585

586
587
    new_diff_refs = self.diff_refs

588
    update_diff_discussion_positions(
589
      old_diff_refs: old_diff_refs,
590
591
      new_diff_refs: new_diff_refs,
      current_user: current_user
592
    )
593
594
  end

595
  def check_if_can_be_merged
Toon Claes's avatar
Toon Claes committed
596
    return unless unchecked? && Gitlab::Database.read_write?
597

598
    can_be_merged =
599
      !broken? && project.repository.can_be_merged?(diff_head_sha, target_branch)
600
601

    if can_be_merged
602
603
604
605
      mark_as_mergeable
    else
      mark_as_unmergeable
    end
606
607
  end

Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
608
  def merge_event
609
    @merge_event ||= target_project.events.where(target_id: self.id, target_type: "MergeRequest", action: Event::MERGED).last
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
610
611
  end

612
  def closed_event
613
    @closed_event ||= target_project.events.where(target_id: self.id, target_type: "MergeRequest", action: Event::CLOSED).last
614
615
  end

616
  def work_in_progress?
Thomas Balthazar's avatar
Thomas Balthazar committed
617
    self.class.work_in_progress?(title)
618
619
620
  end

  def wipless_title
Thomas Balthazar's avatar
Thomas Balthazar committed
621
622
623
624
625
    self.class.wipless_title(self.title)
  end

  def wip_title
    self.class.wip_title(self.title)
626
627
  end

628
629
  def mergeable?(skip_ci_check: false)
    return false unless mergeable_state?(skip_ci_check: skip_ci_check)
630
631
632

    check_if_can_be_merged

633
    can_be_merged? && !should_be_rebased?
634
635
  end

636
  def mergeable_state?(skip_ci_check: false, skip_discussions_check: false)
637
638
639
    return false unless open?
    return false if work_in_progress?
    return false if broken?
640
    return false unless skip_ci_check || mergeable_ci_state?
641
    return false unless skip_discussions_check || mergeable_discussions_state?
642
643

    true
644
645
  end

646
647
648
649
650
651
652
653
  def ff_merge_possible?
    project.repository.ancestor?(target_branch_sha, diff_head_sha)
  end

  def should_be_rebased?
    project.ff_merge_must_be_possible? && !ff_merge_possible?
  end

654
  def can_cancel_merge_when_pipeline_succeeds?(current_user)
655
    can_be_merged_by?(current_user) || self.author == current_user
656
657
  end

658
  def can_remove_source_branch?(current_user)
659
    !ProtectedBranch.protected?(source_project, source_branch) &&
660
      !source_project.root_ref?(source_branch) &&
http://jneen.net/'s avatar
http://jneen.net/ committed
661
      Ability.allowed?(current_user, :push_code, source_project) &&
662
      diff_head_sha == source_branch_head.try(:sha)
663
664
  end

665
  def should_remove_source_branch?
666
    Gitlab::Utils.to_boolean(merge_params['should_remove_source_branch'])
667
668
669
  end

  def force_remove_source_branch?
670
    Gitlab::Utils.to_boolean(merge_params['force_remove_source_branch'])
671
672
673
674
675
676
  end

  def remove_source_branch?
    should_remove_source_branch? || force_remove_source_branch?
  end

677
  def related_notes
678
679
    # Fetch comments only from last 100 commits
    commits_for_notes_limit = 100
680
    commit_ids = commit_shas.take(commits_for_notes_limit)
681

682
683
684
    commit_notes = Note
      .except(:order)
      .where(project_id: [source_project_id, target_project_id])
685
      .for_commit_id(commit_ids)
686
687
688
689
690
691
692
693
694
695

    # We're using a UNION ALL here since this results in better performance
    # compared to using OR statements. We're using UNION ALL since the queries
    # used won't produce any duplicates (e.g. a note for a commit can't also be
    # a note for an MR).
    union = Gitlab::SQL::Union
      .new([notes, commit_notes], remove_duplicates: false)
      .to_sql

    Note.from("(#{union}) #{Note.table_name}")
696
      .includes(:noteable)
697
  end
698

699
  alias_method :discussion_notes, :related_notes
700

701
702
703
  def mergeable_discussions_state?
    return true unless project.only_allow_merge_if_all_discussions_are_resolved?

704
    !discussions_to_be_resolved?
705
706
  end

707
708
709
710
  def for_fork?
    target_project != source_project
  end

711
712
713
714
  def project
    target_project
  end

715
716
717
718
  # If the merge request closes any issues, save this information in the
  # `MergeRequestsClosingIssues` model. This is a performance optimization.
  # Calculating this information for a number of merge requests requires
  # running `ReferenceExtractor` on each of them separately.
719
  # This optimization does not apply to issues from external sources.
720
  def cache_merge_request_closes_issues!(current_user)
721
    return unless project.issues_enabled?
722

723
    transaction do
724
      self.merge_requests_closing_issues.delete_all
725

726
      closes_issues(current_user).each do |issue|
727
728
        next if issue.is_a?(ExternalIssue)

729
        self.merge_requests_closing_issues.create!(issue: issue)
730
731
732
733
      end
    end
  end

734
  # Return the set of issues that will be closed if this merge request is accepted.
735
  def closes_issues(current_user = self.author)
736
    if target_branch == project.default_branch
737
      messages = [title, description]
738
      messages.concat(commits.map(&:safe_message)) if merge_request_diff
739

740
741
      Gitlab::ClosingIssueExtractor.new(project, current_user)
        .closed_by_message(messages.join("\n"))
742
743
744
745
746
    else
      []
    end
  end

747
  def issues_mentioned_but_not_closing(current_user)
748
    return [] unless target_branch == project.default_branch
749

750
    ext = Gitlab::ReferenceExtractor.new(project, current_user)
751
    ext.analyze("#{title}\n#{description}")
752

753
    ext.issues - closes_issues(current_user)
754
755
  end

756
757
  def target_project_path
    if target_project
758
      target_project.full_path
759
760
761
762
763
764
765
    else
      "(removed)"
    end
  end

  def source_project_path
    if source_project
766
      source_project.full_path
767
768
769
770
771
    else
      "(removed)"
    end
  end

772
773
  def source_project_namespace
    if source_project && source_project.namespace
774
      source_project.namespace.full_path
775
776
777
778
779
    else
      "(removed)"
    end
  end

780
781
  def target_project_namespace
    if target_project && target_project.namespace
782
      target_project.namespace.full_path
783
784
785
786
787
    else
      "(removed)"
    end
  end

788
789
790
  def source_branch_exists?
    return false unless self.source_project

791
    self.source_project.repository.branch_exists?(self.source_branch)
792
793
794
795
796
  end

  def target_branch_exists?
    return false unless self.target_project

797
    self.target_project.repository.branch_exists?(self.target_branch)
798
799
  end

800
  def merge_commit_message(include_description: false)
801
802
803
804
    closes_issues_references = closes_issues.map do |issue|
      issue.to_reference(target_project)
    end

805
806
807
808
    message = [
      "Merge branch '#{source_branch}' into '#{target_branch}'",
      title
    ]
809

810
    if !include_description && closes_issues_references.present?
811
      message << "Closes #{closes_issues_references.to_sentence}"
812
    end
813

814
    message << "#{description}" if include_description && description.present?
815
    message << "See merge request #{to_reference(full: true)}"
816

817
    message.join("\n\n")
818
  end
819

820
821
  def reset_merge_when_pipeline_succeeds
    return unless merge_when_pipeline_succeeds?
822

823
    self.merge_when_pipeline_succeeds = false
824
    self.merge_user = nil
825
826
827
828
    if merge_params
      merge_params.delete('should_remove_source_branch')
      merge_params.delete('commit_message')
    end
829
830
831
832

    self.save
  end

833
  # Return array of possible target branches
Steven Burgart's avatar
Steven Burgart committed
834
  # depends on target project of MR
835
836
837
838
839
840
841
842
843
  def target_branches
    if target_project.nil?
      []
    else
      target_project.repository.branch_names
    end
  end

  # Return array of possible source branches
Steven Burgart's avatar
Steven Burgart committed
844
  # depends on source project of MR
845
846
847
848
849
850
851
  def source_branches
    if source_project.nil?
      []
    else
      source_project.repository.branch_names
    end
  end
852

853
  def has_ci?
854
    return false if has_no_commits?
855

856
    !!(head_pipeline_id || all_pipelines.any? || source_project&.ci_service)
857
858
859
860
861
  end

  def branch_missing?
    !source_branch_exists? || !target_branch_exists?
  end
862

863
  def broken?
864
    has_no_commits? || branch_missing? || cannot_be_merged?
865
866
  end

867
  def can_be_merged_by?(user)
868
    access = ::Gitlab::UserAccess.new(user, project: project)
869
    access.can_update_branch?(target_branch)
870
871
872
873
874
  end

  def can_be_merged_via_command_line_by?(user)
    access = ::Gitlab::UserAccess.new(user, project: project)
    access.can_push_to_branch?(target_branch)
875
876
  end

877
  def mergeable_ci_state?
878
    return true unless project.only_allow_merge_if_pipeline_succeeds?
879
    return true unless head_pipeline
880

881
    actual_head_pipeline&.success? || actual_head_pipeline&.skipped?
882
883
  end

Douwe Maan's avatar
Douwe Maan committed
884
  def environments_for(current_user)
885
    return [] unless diff_head_commit
886

Douwe Maan's avatar
Douwe Maan committed
887
888
889
    @environments ||= Hash.new do |h, current_user|
      envs = EnvironmentsFinder.new(target_project, current_user,
        ref: target_branch, commit: diff_head_commit, with_tags: true).execute
890

Douwe Maan's avatar
Douwe Maan committed
891
892
893
894
      if source_project
        envs.concat EnvironmentsFinder.new(source_project, current_user,
          ref: source_branch, commit: diff_head_commit).execute
      end
895

Douwe Maan's avatar
Douwe Maan committed
896
      h[current_user] = envs.uniq
897
    end
Douwe Maan's avatar
Douwe Maan committed
898
899

    @environments[current_user]
900
901
  end

902
903
904
905
906
907
908
909
910
  def state_human_name
    if merged?
      "Merged"
    elsif closed?
      "Closed"
    else
      "Open"
    end
  end
911

912
913
  def state_icon_name
    if merged?
Eric Eastwood's avatar
Eric Eastwood committed
914
      "git-merge"
915
    elsif closed?
Eric Eastwood's avatar
Eric Eastwood committed
916
      "close"
917
    else
Eric Eastwood's avatar
Eric Eastwood committed
918
      "issue-open-m"
919
920
921
    end
  end

922
923
  def fetch_ref!
    target_project.repository.fetch_source_branch!(source_project.repository, source_branch, ref_path)
924
925
  end

926
  def ref_path
927
    "refs/#{Repository::REF_MERGE_REQUEST}/#{iid}/head"
928
929
  end

930
931
932
933
934
  def in_locked_state
    begin
      lock_mr
      yield
    ensure
935
      unlock_mr
936
937
    end
  end
938

939
940
941
  def diverged_commits_count
    cache = Rails.cache.read(:"merge_request_#{id}_diverged_commits")

942
    if cache.blank? || cache[:source_sha] != source_branch_sha || cache[:target_sha] != target_branch_sha
943
      cache = {
944
945
        source_sha: source_branch_sha,
        target_sha: target_branch_sha,
946
947
948
949
950
951
952
953
954
        diverged_commits_count: compute_diverged_commits_count
      }
      Rails.cache.write(:"merge_request_#{id}_diverged_commits", cache)
    end

    cache[:diverged_commits_count]
  end

  def compute_diverged_commits_count
955
    return 0 unless source_branch_sha && target_branch_sha
956

957
958
    target_project.repository
      .count_commits_between(source_branch_sha, target_branch_sha)
959
  end
960
  private :compute_diverged_commits_count
961
962
963
964
965

  def diverged_from_target_branch?
    diverged_commits_