Read about our upcoming Code of Conduct on this issue

merge_request.rb 34.7 KB
Newer Older
1
2
# frozen_string_literal: true

Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
3
class MergeRequest < ActiveRecord::Base
4
  include AtomicInternalId
Shinya Maeda's avatar
Shinya Maeda committed
5
  include IidRoutes
6
  include Issuable
7
  include Noteable
8
  include Referable
9
  include Presentable
10
  include IgnorableColumn
11
  include TimeTrackable
12
13
  include ManualInverseAssociation
  include EachBatch
14
  include ThrottledTouch
15
  include Gitlab::Utils::StrongMemoize
Jan Provaznik's avatar
Jan Provaznik committed
16
  include LabelEventable
17
  include ReactiveCaching
18
  include FromUnion
19
20

  self.reactive_cache_key = ->(model) { [model.project.id, model.iid] }
21
22
  self.reactive_cache_refresh_interval = 10.minutes
  self.reactive_cache_lifetime = 10.minutes
23

24
  ignore_column :locked_at,
25
26
                :ref_fetched,
                :deleted_at
27

28
29
  belongs_to :target_project, class_name: "Project"
  belongs_to :source_project, class_name: "Project"
30
  belongs_to :merge_user, class_name: "User"
31

32
33
  has_internal_id :iid, scope: :target_project, init: ->(s) { s&.target_project&.merge_requests&.maximum(:iid) }

34
  has_many :merge_request_diffs
35

36
  has_one :merge_request_diff,
37
    -> { order('merge_request_diffs.id DESC') }, inverse_of: :merge_request
38

39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
  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

57
58
  belongs_to :head_pipeline, foreign_key: "head_pipeline_id", class_name: "Ci::Pipeline"

59
  has_many :events, as: :target, dependent: :destroy # rubocop:disable Cop/ActiveRecordDependent
60

61
62
63
  has_many :merge_requests_closing_issues,
    class_name: 'MergeRequestsClosingIssues',
    dependent: :delete_all # rubocop:disable Cop/ActiveRecordDependent
64

65
  has_many :cached_closes_issues, through: :merge_requests_closing_issues, source: :issue
Shinya Maeda's avatar
Shinya Maeda committed
66
  has_many :merge_request_pipelines, foreign_key: 'merge_request_id', class_name: 'Ci::Pipeline'
67

68
69
  belongs_to :assignee, class_name: "User"

70
  serialize :merge_params, Hash # rubocop:disable Cop/ActiveRecordSerialize
71

72
  after_create :ensure_merge_request_diff, unless: :importing?
73
  after_update :clear_memoized_shas
74
  after_update :reload_diff_if_branch_changed
75
  after_save :ensure_metrics
76

Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
77
78
79
80
  # When this attribute is true some MR validation is ignored
  # It allows us to close or modify broken merge requests
  attr_accessor :allow_broken

81
82
  # Temporary fields to store compare vars
  # when creating new merge request
83
  attr_accessor :can_be_created, :compare_commits, :diff_options, :compare
84

Andrew8xx8's avatar
Andrew8xx8 committed
85
  state_machine :state, initial: :opened do
86
    event :close do
87
      transition [:opened] => :closed
88
89
    end

90
    event :mark_as_merged do
91
      transition [:opened, :locked] => :merged
92
93
94
    end

    event :reopen do
95
      transition closed: :opened
96
97
    end

98
    event :lock_mr do
99
      transition [:opened] => :locked
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
100
101
    end

102
    event :unlock_mr do
103
      transition locked: :opened
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
104
105
    end

106
107
108
109
110
111
112
113
    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

114
115
116
    state :opened
    state :closed
    state :merged
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
117
    state :locked
118
119
  end

120
121
  state_machine :merge_status, initial: :unchecked do
    event :mark_as_unchecked do
122
123
      transition [:can_be_merged, :unchecked] => :unchecked
      transition [:cannot_be_merged, :cannot_be_merged_recheck] => :cannot_be_merged_recheck
124
125
126
    end

    event :mark_as_mergeable do
127
      transition [:unchecked, :cannot_be_merged_recheck] => :can_be_merged
128
129
130
    end

    event :mark_as_unmergeable do
131
      transition [:unchecked, :cannot_be_merged_recheck] => :cannot_be_merged
132
133
    end

134
    state :unchecked
135
    state :cannot_be_merged_recheck
136
137
    state :can_be_merged
    state :cannot_be_merged
138
139

    around_transition do |merge_request, transition, block|
140
      Gitlab::Timeless.timeless(merge_request, &block)
141
    end
142

143
    # rubocop: disable CodeReuse/ServiceClass
144
    after_transition unchecked: :cannot_be_merged do |merge_request, transition|
145
146
147
      if merge_request.notify_conflict?
        NotificationService.new.merge_request_unmergeable(merge_request)
        TodoService.new.merge_request_became_unmergeable(merge_request)
148
      end
149
    end
150
    # rubocop: enable CodeReuse/ServiceClass
151

152
153
154
    def check_state?(merge_status)
      [:unchecked, :cannot_be_merged_recheck].include?(merge_status.to_sym)
    end
155
  end
156

157
  validates :source_project, presence: true, unless: [:allow_broken, :importing?, :closed_without_fork?]
Andrey Kumanyaev's avatar
Andrey Kumanyaev committed
158
  validates :source_branch, presence: true
159
  validates :target_project, presence: true
Andrey Kumanyaev's avatar
Andrey Kumanyaev committed
160
  validates :target_branch, presence: true
161
  validates :merge_user, presence: true, if: :merge_when_pipeline_succeeds?, unless: :importing?
162
163
  validate :validate_branches, unless: [:allow_broken, :importing?, :closed_without_fork?]
  validate :validate_fork, unless: :closed_without_fork?
164
  validate :validate_target_project, on: :create
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
165

166
167
168
  scope :by_source_or_target_branch, ->(branch_name) do
    where("source_branch = :branch OR target_branch = :branch", branch: branch_name)
  end
169
  scope :by_milestone, ->(milestone) { where(milestone_id: milestone) }
170
  scope :of_projects, ->(ids) { where(target_project_id: ids) }
171
  scope :from_project, ->(project) { where(source_project_id: project.id) }
172
173
  scope :merged, -> { with_state(:merged) }
  scope :closed_and_merged, -> { with_states(:closed, :merged) }
174
  scope :from_source_branches, ->(branches) { where(source_branch: branches) }
175
176
177
  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
178
179
  scope :join_project, -> { joins(:target_project) }
  scope :references_project, -> { references(:target_project) }
180
181
182
183
184
  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
185

186
187
  after_save :keep_around_commit

188
189
190
191
  def self.reference_prefix
    '!'
  end

192
  def rebase_in_progress?
193
194
195
    strong_memoize(:rebase_in_progress) do
      # The source project can be deleted
      next false unless source_project
196

197
198
      source_project.repository.rebase_in_progress?(id)
    end
199
200
  end

201
202
203
  # 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
204
  def actual_head_pipeline
205
    head_pipeline&.sha == diff_head_sha ? head_pipeline : nil
206
207
  end

208
209
210
211
212
213
  def merge_pipeline
    return unless merged?

    target_project.pipeline_for(target_branch, merge_commit_sha)
  end

214
215
216
217
  # Pattern used to extract `!123` merge request references from text
  #
  # This pattern supports cross-project references.
  def self.reference_pattern
218
    @reference_pattern ||= %r{
219
      (#{Project.reference_pattern})?
220
221
222
223
      #{Regexp.escape(reference_prefix)}(?<merge_request>\d+)
    }x
  end

224
  def self.link_reference_pattern
225
    @link_reference_pattern ||= super("merge_requests", /(?<merge_request>\d+)/)
226
227
  end

228
229
230
231
  def self.reference_valid?(reference)
    reference.to_i > 0 && reference.to_i <= Gitlab::Database::MAX_INT_VALUE
  end

232
233
234
235
  def self.project_foreign_key
    'target_project_id'
  end

236
237
238
239
240
241
242
243
244
245
246
  # 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)
247
248
    # unscoping unnecessary conditions that'll be applied
    # when executing `where("merge_requests.id IN (#{union.to_sql})")`
249
250
    source = unscoped.where(source_project_id: relation)
    target = unscoped.where(target_project_id: relation)
251

252
    from_union([source, target])
253
254
  end

255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
  # 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

271
  WIP_REGEX = /\A*(\[WIP\]\s*|WIP:\s*|WIP\s+)+\s*/i.freeze
Thomas Balthazar's avatar
Thomas Balthazar committed
272
273
274
275
276
277
278
279
280
281
282
283
284

  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

285
286
287
288
289
290
  # 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

291
  def hook_attrs
292
    Gitlab::HookData::MergeRequestBuilder.new(self).build
293
294
  end

295
296
297
298
299
300
301
302
  # Returns a Hash of attributes to be used for Twitter card metadata
  def card_attributes
    {
      'Author'   => author.try(:name),
      'Assignee' => assignee.try(:name)
    }
  end

303
  # These method are needed for compatibility with issues to not mess view and other code
304
305
306
307
  def assignees
    Array(assignee)
  end

308
309
310
311
312
313
314
315
  def assignee_ids
    Array(assignee_id)
  end

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

316
317
318
319
  def assignee_or_author?(user)
    author_id == user.id || assignee_id == user.id
  end

320
  # `from` argument can be a Namespace or Project.
321
  def to_reference(from = nil, full: false)
322
323
    reference = "#{self.class.reference_prefix}#{iid}"

324
    "#{project.to_reference(from, full: full)}#{reference}"
325
326
  end

327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
  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
351
      compare_commits.to_a.reverse.map(&:sha)
352
    else
353
      Array(diff_head_sha)
354
355
356
    end
  end

357
358
359
360
361
362
363
364
365
  # Returns true if there are commits that match at least one commit SHA.
  def includes_any_commits?(shas)
    if persisted?
      merge_request_diff.commits_by_shas(shas).exists?
    else
      (commit_shas & shas).present?
    end
  end

366
367
368
  # Calls `MergeWorker` to proceed with the merge process and
  # updates `merge_jid` with the MergeWorker#jid.
  # This helps tracking enqueued and ongoing merge jobs.
369
  def merge_async(user_id, params)
370
    jid = MergeWorker.perform_async(id, user_id, params.to_h)
371
372
373
    update_column(:merge_jid, jid)
  end

lulalala's avatar
lulalala committed
374
375
376
377
378
379
380
381
382
383
  def merge_participants
    participants = [author]

    if merge_when_pipeline_succeeds? && !participants.include?(merge_user)
      participants << merge_user
    end

    participants
  end

384
385
  def first_commit
    merge_request_diff ? merge_request_diff.first_commit : compare_commits.first
386
  end
387

388
  def raw_diffs(*args)
389
    merge_request_diff ? merge_request_diff.raw_diffs(*args) : compare.raw_diffs(*args)
390
391
  end

392
  def diffs(diff_options = {})
393
    if compare
394
      # When saving MR diffs, `expanded` is implicitly added (because we need
395
396
      # to save the entire contents to the DB), so add that here for
      # consistency.
397
      compare.diffs(diff_options.merge(expanded: true))
398
    else
399
      merge_request_diff.diffs(diff_options)
400
    end
401
402
  end

403
404
405
406
  def non_latest_diffs
    merge_request_diffs.where.not(id: merge_request_diff.id)
  end

407
  def diff_size
408
409
    # Calling `merge_request_diff.diffs.real_size` will also perform
    # highlighting, which we don't need here.
410
    merge_request_diff&.real_size || diffs.real_size
411
412
  end

413
414
415
416
417
418
419
420
421
422
423
424
  def modified_paths(past_merge_request_diff: nil)
    diffs = if past_merge_request_diff
              past_merge_request_diff
            elsif compare
              compare
            else
              self.merge_request_diff
            end

    diffs.modified_paths
  end

425
  def diff_base_commit
426
    if persisted?
427
      merge_request_diff.base_commit
428
429
    else
      branch_merge_base_commit
430
431
432
433
434
435
436
437
    end
  end

  def diff_start_commit
    if persisted?
      merge_request_diff.start_commit
    else
      target_branch_head
438
439
440
    end
  end

441
442
443
444
445
446
447
448
449
  def diff_head_commit
    if persisted?
      merge_request_diff.head_commit
    else
      source_branch_head
    end
  end

  def diff_start_sha
450
451
452
453
454
    if persisted?
      merge_request_diff.start_commit_sha
    else
      target_branch_head.try(:sha)
    end
455
456
457
  end

  def diff_base_sha
458
459
460
461
462
    if persisted?
      merge_request_diff.base_commit_sha
    else
      branch_merge_base_commit.try(:sha)
    end
463
464
465
  end

  def diff_head_sha
466
467
468
469
470
    if persisted?
      merge_request_diff.head_commit_sha
    else
      source_branch_head.try(:sha)
    end
471
472
473
474
475
476
477
478
  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

479
480
481
482
483
484
485
486
487
488
489
490
491
492
  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

493
  def source_branch_head
494
495
496
497
498
    strong_memoize(:source_branch_head) do
      if source_project && source_branch_ref
        source_project.repository.commit(source_branch_ref)
      end
    end
499
500
501
  end

  def target_branch_head
502
503
504
    strong_memoize(:target_branch_head) do
      target_project.repository.commit(target_branch_ref)
    end
505
506
  end

507
508
509
510
511
512
513
514
515
  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

516
  def target_branch_sha
517
    @target_branch_sha || target_branch_head.try(:sha)
518
519
520
  end

  def source_branch_sha
521
    @source_branch_sha || source_branch_head.try(:sha)
522
523
  end

524
  def diff_refs
525
    if persisted?
526
      merge_request_diff.diff_refs
527
    else
528
529
530
531
532
      Gitlab::Diff::DiffRefs.new(
        base_sha:  diff_base_sha,
        start_sha: diff_start_sha,
        head_sha:  diff_head_sha
      )
533
    end
534
535
  end

536
537
538
539
  def branch_merge_base_sha
    branch_merge_base_commit.try(:sha)
  end

540
  def validate_branches
541
    if target_project == source_project && target_branch == source_branch
542
      errors.add :branch_conflict, "You can not use same project/branch for source and target"
543
    end
544

545
    if opened?
546
      similar_mrs = self.target_project.merge_requests.where(source_branch: source_branch, target_branch: target_branch, source_project_id: source_project.try(:id)).opened
547
548
      similar_mrs = similar_mrs.where('id not in (?)', self.id) if self.id
      if similar_mrs.any?
549
        errors.add :validate_branches,
Gabriel Mazetto's avatar
Gabriel Mazetto committed
550
                   "Cannot Create: This merge request already exists: #{similar_mrs.pluck(:title)}"
551
      end
552
    end
553
554
  end

555
556
557
558
559
560
  def validate_target_project
    return true if target_project.merge_requests_enabled?

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

561
  def validate_fork
562
    return true unless target_project && source_project
563
    return true if target_project == source_project
564
    return true unless source_project_missing?
565

566
    errors.add :validate_fork,
567
               'Source project is not a fork of the target project'
568
569
  end

570
  def merge_ongoing?
571
572
    # While the MergeRequest is locked, it should present itself as 'merge ongoing'.
    # The unlocking process is handled by StuckMergeJobsWorker scheduled in Cron.
573
574
575
    return true if locked?

    !!merge_jid && !merged? && Gitlab::SidekiqStatus.running?(merge_jid)
576
577
  end

578
  def closed_without_fork?
579
    closed? && source_project_missing?
580
581
  end

582
  def source_project_missing?
583
584
585
    return false unless for_fork?
    return true unless source_project

586
    !source_project.in_fork_network_of?(target_project)
587
588
  end

589
  def reopenable?
590
    closed? && !source_project_missing? && source_branch_exists?
Katarzyna Kobierska's avatar
Katarzyna Kobierska committed
591
592
  end

593
594
  def ensure_merge_request_diff
    merge_request_diff || create_merge_request_diff
595
596
  end

597
  def create_merge_request_diff
598
    fetch_ref!
599

600
601
602
603
604
    # 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
605
606
607
608
609
610
  end

  def reload_merge_request_diff
    merge_request_diff(true)
  end

611
612
613
614
  def viewable_diffs
    @viewable_diffs ||= merge_request_diffs.viewable.to_a
  end

615
  def merge_request_diff_for(diff_refs_or_sha)
616
617
618
619
620
621
622
623
624
625
    matcher =
      if diff_refs_or_sha.is_a?(Gitlab::Diff::DiffRefs)
        {
          'start_commit_sha' => diff_refs_or_sha.start_sha,
          'head_commit_sha' => diff_refs_or_sha.head_sha,
          'base_commit_sha' => diff_refs_or_sha.base_sha
        }
      else
        { 'head_commit_sha' => diff_refs_or_sha }
      end
Douwe Maan's avatar
Douwe Maan committed
626

627
628
629
    viewable_diffs.find do |diff|
      diff.attributes.slice(*matcher.keys) == matcher
    end
630
631
  end

632
633
634
635
636
637
638
639
640
641
642
  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

643
644
645
646
647
648
649
  def clear_memoized_shas
    @target_branch_sha = @source_branch_sha = nil

    clear_memoization(:source_branch_head)
    clear_memoization(:target_branch_head)
  end

650
  def reload_diff_if_branch_changed
651
652
    if (source_branch_changed? || target_branch_changed?) &&
        (source_branch_head && target_branch_head)
653
      reload_diff
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
654
655
656
    end
  end

657
  # rubocop: disable CodeReuse/ServiceClass
658
  def reload_diff(current_user = nil)
659
660
    return unless open?

661
    MergeRequests::ReloadDiffsService.new(self, current_user).execute
662
  end
663
  # rubocop: enable CodeReuse/ServiceClass
664

665
  def check_if_can_be_merged
666
    return unless self.class.state_machines[:merge_status].check_state?(merge_status) && Gitlab::Database.read_write?
667

668
    can_be_merged =
669
      !broken? && project.repository.can_be_merged?(diff_head_sha, target_branch)
670
671

    if can_be_merged
672
673
674
675
      mark_as_mergeable
    else
      mark_as_unmergeable
    end
676
677
  end

Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
678
  def merge_event
679
    @merge_event ||= target_project.events.where(target_id: self.id, target_type: "MergeRequest", action: Event::MERGED).last
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
680
681
  end

682
  def closed_event
683
    @closed_event ||= target_project.events.where(target_id: self.id, target_type: "MergeRequest", action: Event::CLOSED).last
684
685
  end

686
  def work_in_progress?
Thomas Balthazar's avatar
Thomas Balthazar committed
687
    self.class.work_in_progress?(title)
688
689
690
  end

  def wipless_title
Thomas Balthazar's avatar
Thomas Balthazar committed
691
692
693
694
695
    self.class.wipless_title(self.title)
  end

  def wip_title
    self.class.wip_title(self.title)
696
697
  end

698
699
  def mergeable?(skip_ci_check: false)
    return false unless mergeable_state?(skip_ci_check: skip_ci_check)
700
701
702

    check_if_can_be_merged

703
    can_be_merged? && !should_be_rebased?
704
705
  end

706
  def mergeable_state?(skip_ci_check: false, skip_discussions_check: false)
707
708
709
    return false unless open?
    return false if work_in_progress?
    return false if broken?
710
    return false unless skip_ci_check || mergeable_ci_state?
711
    return false unless skip_discussions_check || mergeable_discussions_state?
712
713

    true
714
715
  end

716
717
718
719
720
721
722
723
  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

724
  def can_cancel_merge_when_pipeline_succeeds?(current_user)
725
    can_be_merged_by?(current_user) || self.author == current_user
726
727
  end

728
  def can_remove_source_branch?(current_user)
729
    !ProtectedBranch.protected?(source_project, source_branch) &&
730
      !source_project.root_ref?(source_branch) &&
http://jneen.net/'s avatar
http://jneen.net/ committed
731
      Ability.allowed?(current_user, :push_code, source_project) &&
732
      diff_head_sha == source_branch_head.try(:sha)
733
734
  end

735
  def should_remove_source_branch?
736
    Gitlab::Utils.to_boolean(merge_params['should_remove_source_branch'])
737
738
739
  end

  def force_remove_source_branch?
740
    Gitlab::Utils.to_boolean(merge_params['force_remove_source_branch'])
741
742
743
744
745
746
  end

  def remove_source_branch?
    should_remove_source_branch? || force_remove_source_branch?
  end

747
  def notify_conflict?
748
749
750
751
752
753
754
755
    (opened? || locked?) &&
      has_commits? &&
      !branch_missing? &&
      !project.repository.can_be_merged?(diff_head_sha, target_branch)
  rescue Gitlab::Git::CommandError
    # Checking mergeability can trigger exception, e.g. non-utf8
    # We ignore this type of errors.
    false
756
757
  end

758
  def related_notes
759
760
    # Fetch comments only from last 100 commits
    commits_for_notes_limit = 100
761
    commit_ids = commit_shas.take(commits_for_notes_limit)
762

763
764
765
    commit_notes = Note
      .except(:order)
      .where(project_id: [source_project_id, target_project_id])
766
      .for_commit_id(commit_ids)
767
768
769
770
771

    # 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).
772
773
    Note
      .from_union([notes, commit_notes], remove_duplicates: false)
774
      .includes(:noteable)
775
  end
776

777
  alias_method :discussion_notes, :related_notes
778

779
780
781
  def mergeable_discussions_state?
    return true unless project.only_allow_merge_if_all_discussions_are_resolved?

782
    !discussions_to_be_resolved?
783
784
  end

785
786
787
788
  def for_fork?
    target_project != source_project
  end

789
790
791
792
  def project
    target_project
  end

793
794
795
796
  # 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.
797
  # This optimization does not apply to issues from external sources.
798
  def cache_merge_request_closes_issues!(current_user = self.author)
799
    return unless project.issues_enabled?
800
    return if closed? || merged?
801

802
    transaction do
803
      self.merge_requests_closing_issues.delete_all
804

805
      closes_issues(current_user).each do |issue|
806
807
        next if issue.is_a?(ExternalIssue)

808
        self.merge_requests_closing_issues.create!(issue: issue)
809
810
811
812
      end
    end
  end

813
814
815
816
817
818
819
820
821
822
823
824
  def visible_closing_issues_for(current_user = self.author)
    strong_memoize(:visible_closing_issues_for) do
      if self.target_project.has_external_issue_tracker?
        closes_issues(current_user)
      else
        cached_closes_issues.select do |issue|
          Ability.allowed?(current_user, :read_issue, issue)
        end
      end
    end
  end

825
  # Return the set of issues that will be closed if this merge request is accepted.
826
  def closes_issues(current_user = self.author)
827
    if target_branch == project.default_branch
828
      messages = [title, description]
829
      messages.concat(commits.map(&:safe_message)) if merge_request_diff
830

831
832
      Gitlab::ClosingIssueExtractor.new(project, current_user)
        .closed_by_message(messages.join("\n"))
833
834
835
836
837
    else
      []
    end
  end

838
  def issues_mentioned_but_not_closing(current_user)
839
    return [] unless target_branch == project.default_branch
840

841
    ext = Gitlab::ReferenceExtractor.new(project, current_user)
842
    ext.analyze("#{title}\n#{description}")
843

844
    ext.issues - visible_closing_issues_for(current_user)
845
846
  end

847
848
  def target_project_path
    if target_project
849
      target_project.full_path
850
851
852
853
854
855
856
    else
      "(removed)"
    end
  end

  def source_project_path
    if source_project
857
      source_project.full_path
858
859
860
861
862
    else
      "(removed)"
    end
  end

863
864
  def source_project_namespace
    if source_project && source_project.namespace
865
      source_project.namespace.full_path
866
867
868
869
870
    else
      "(removed)"
    end
  end

871
872
  def target_project_namespace
    if target_project && target_project.namespace
873
      target_project.namespace.full_path
874
875
876
877
878
    else
      "(removed)"
    end
  end

879
880
881
  def source_branch_exists?
    return false unless self.source_project

882
    self.source_project.repository.branch_exists?(self.source_branch)
883
884
885
886
887
  end

  def target_branch_exists?
    return false unless self.target_project

888
    self.target_project.repository.branch_exists?(self.target_branch)
889
890
  end

891
  def merge_commit_message(include_description: false)
892
    closes_issues_references = visible_closing_issues_for.map do |issue|
893
894
895
      issue.to_reference(target_project)
    end

896
897
898
899
    message = [
      "Merge branch '#{source_branch}' into '#{target_branch}'",
      title
    ]
900

901
    if !include_description && closes_issues_references.present?
902
      message << "Closes #{closes_issues_references.to_sentence}"
903
    end
904

905
    message << "#{description}" if include_description && description.present?
906
    message << "See merge request #{to_reference(full: true)}"
907

908
    message.join("\n\n")
909
  end
910

911
912
  def reset_merge_when_pipeline_succeeds
    return unless merge_when_pipeline_succeeds?
913

914
    self.merge_when_pipeline_succeeds = false
915
    self.merge_user = nil
916
917
918
919
    if merge_params
      merge_params.delete('should_remove_source_branch')
      merge_params.delete('commit_message')
    end
920
921
922
923

    self.save
  end

924
  # Return array of possible target branches
Steven Burgart's avatar
Steven Burgart committed
925
  # depends on target project of MR
926
927
928
929
930
931
932
933
934
  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
935
  # depends on source project of MR
936
937
938
939
940
941
942
  def source_branches
    if source_project.nil?
      []
    else
      source_project.repository.branch_names
    end
  end
943

944
  def has_ci?
945
    return false if has_no_commits?
946

947
    !!(head_pipeline_id || all_pipelines.any? || source_project&.ci_service)
948
949
950
951
952
  end

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

954
  def broken?
955
    has_no_commits? || branch_missing? || cannot_be_merged?
956
957
  end

958
  def can_be_merged_by?(user)
959
    access = ::Gitlab::UserAccess.new(user, project: project)
960
    access.can_update_branch?(target_branch)
961
962
963
964
965
  end

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

968
  def mergeable_ci_state?
969
    return true unless project.only_allow_merge_if_pipeline_succeeds?
970

971
    actual_head_pipeline&.success? || actual_head_pipeline&.skipped?
972
973
  end

Douwe Maan's avatar
Douwe Maan committed
974
  def environments_for(current_user)
975
    return [] unless diff_head_commit
976

Douwe Maan's avatar
Douwe Maan committed
977
978
979
    @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
980

Douwe Maan's avatar
Douwe Maan committed
981
982
983
984
      if source_project
        envs.concat EnvironmentsFinder.new(source_project, current_user,
          ref: source_branch, commit: diff_head_commit).execute
      end
985

Douwe Maan's avatar
Douwe Maan committed
986
      h[current_user] = envs.uniq
987
    end
Douwe Maan's avatar
Douwe Maan committed
988
989

    @environments[current_user]
990
991
  end

992
993
994
995
996
997
998
999
1000
  def state_human_name
    if merged?
      "Merged"
    elsif closed?
      "Closed"
    else
      "Open"
    end
  end
1001

1002
1003
  def state_icon_name
    if merged?
Eric Eastwood's avatar
Eric Eastwood committed
1004
      "git-merge"
1005
    elsif closed?
Eric Eastwood's avatar
Eric Eastwood committed
1006
      "close"