Read about our upcoming Code of Conduct on this issue

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

3
class MergeRequest < ApplicationRecord
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 TimeTrackable
11
12
  include ManualInverseAssociation
  include EachBatch
13
  include ThrottledTouch
14
  include Gitlab::Utils::StrongMemoize
Jan Provaznik's avatar
Jan Provaznik committed
15
  include LabelEventable
16
  include ReactiveCaching
17
  include FromUnion
18
  include DeprecatedAssignee
19
20
21
  include ShaAttribute

  sha_attribute :squash_commit_sha
22
23

  self.reactive_cache_key = ->(model) { [model.project.id, model.iid] }
24
25
  self.reactive_cache_refresh_interval = 10.minutes
  self.reactive_cache_lifetime = 10.minutes
26

27
28
  SORTING_PREFERENCE_FIELD = :merge_requests_sort

29
30
  prepend_if_ee('::EE::MergeRequest') # rubocop: disable Cop/InjectEnterpriseEditionModule

31
32
  belongs_to :target_project, class_name: "Project"
  belongs_to :source_project, class_name: "Project"
33
  belongs_to :merge_user, class_name: "User"
34

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

37
  has_many :merge_request_diffs
38

39
  has_one :merge_request_diff,
40
    -> { order('merge_request_diffs.id DESC') }, inverse_of: :merge_request
41

42
43
44
45
46
47
48
49
50
51
52
53
  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.
54
55
  def merge_request_diff
    fallback = latest_merge_request_diff unless association(:merge_request_diff).loaded?
56
57
58
59

    fallback || super
  end

60
61
  belongs_to :head_pipeline, foreign_key: "head_pipeline_id", class_name: "Ci::Pipeline"

62
  has_many :events, as: :target, dependent: :delete_all # rubocop:disable Cop/ActiveRecordDependent
63

64
65
66
  has_many :merge_requests_closing_issues,
    class_name: 'MergeRequestsClosingIssues',
    dependent: :delete_all # rubocop:disable Cop/ActiveRecordDependent
67

68
  has_many :cached_closes_issues, through: :merge_requests_closing_issues, source: :issue
69
  has_many :pipelines_for_merge_request, foreign_key: 'merge_request_id', class_name: 'Ci::Pipeline'
70
  has_many :suggestions, through: :notes
71
  has_many :unresolved_notes, -> { unresolved }, as: :noteable, class_name: 'Note'
72

73
  has_many :merge_request_assignees
74
  has_many :assignees, class_name: "User", through: :merge_request_assignees
75

76
77
78
79
80
81
82
83
  KNOWN_MERGE_PARAMS = [
    :auto_merge_strategy,
    :should_remove_source_branch,
    :force_remove_source_branch,
    :commit_message,
    :squash_commit_message,
    :sha
  ].freeze
84
  serialize :merge_params, Hash # rubocop:disable Cop/ActiveRecordSerialize
85

86
  after_create :ensure_merge_request_diff
87
  after_update :clear_memoized_shas
88
  after_update :reload_diff_if_branch_changed
89
  after_save :ensure_metrics
90
  after_commit :expire_etag_cache
91

Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
92
93
94
95
  # When this attribute is true some MR validation is ignored
  # It allows us to close or modify broken merge requests
  attr_accessor :allow_broken

96
97
  # Temporary fields to store compare vars
  # when creating new merge request
98
  attr_accessor :can_be_created, :compare_commits, :diff_options, :compare
99

100
101
102
103
104
105
106
  # Keep states definition to be evaluated before the state_machine block to avoid spec failures.
  # If this gets evaluated after, the `merged` and `locked` states which are overrided can be nil.
  def self.available_state_names
    super + [:merged, :locked]
  end

  state_machine :state_id, initial: :opened do
107
    event :close do
108
      transition [:opened] => :closed
109
110
    end

111
    event :mark_as_merged do
112
      transition [:opened, :locked] => :merged
113
114
115
    end

    event :reopen do
116
      transition closed: :opened
117
118
    end

119
    event :lock_mr do
120
      transition [:opened] => :locked
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
121
122
    end

123
    event :unlock_mr do
124
      transition locked: :opened
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
125
126
    end

127
128
    before_transition any => :opened do |merge_request|
      merge_request.merge_jid = nil
129
    end
130

131
    after_transition any => :opened do |merge_request|
132
133
134
135
136
      merge_request.run_after_commit do
        UpdateHeadPipelineForMergeRequestWorker.perform_async(merge_request.id)
      end
    end

137
138
139
140
141
142
143
144
145
146
147
    state :opened, value: MergeRequest.available_states[:opened]
    state :closed, value: MergeRequest.available_states[:closed]
    state :merged, value: MergeRequest.available_states[:merged]
    state :locked, value: MergeRequest.available_states[:locked]
  end

  # Alias to state machine .with_state_id method
  # This needs to be defined after the state machine block to avoid errors
  class << self
    alias_method :with_state, :with_state_id
    alias_method :with_states, :with_state_ids
148
149
  end

150
151
  state_machine :merge_status, initial: :unchecked do
    event :mark_as_unchecked do
152
153
      transition [:can_be_merged, :unchecked] => :unchecked
      transition [:cannot_be_merged, :cannot_be_merged_recheck] => :cannot_be_merged_recheck
154
155
156
    end

    event :mark_as_mergeable do
157
      transition [:unchecked, :cannot_be_merged_recheck] => :can_be_merged
158
159
160
    end

    event :mark_as_unmergeable do
161
      transition [:unchecked, :cannot_be_merged_recheck] => :cannot_be_merged
162
163
    end

164
    state :unchecked
165
    state :cannot_be_merged_recheck
166
167
    state :can_be_merged
    state :cannot_be_merged
168
169

    around_transition do |merge_request, transition, block|
170
      Gitlab::Timeless.timeless(merge_request, &block)
171
    end
172

173
    # rubocop: disable CodeReuse/ServiceClass
174
    after_transition unchecked: :cannot_be_merged do |merge_request, transition|
175
176
177
      if merge_request.notify_conflict?
        NotificationService.new.merge_request_unmergeable(merge_request)
        TodoService.new.merge_request_became_unmergeable(merge_request)
178
      end
179
    end
180
    # rubocop: enable CodeReuse/ServiceClass
181

182
183
184
    def check_state?(merge_status)
      [:unchecked, :cannot_be_merged_recheck].include?(merge_status.to_sym)
    end
185
  end
186

187
  validates :source_project, presence: true, unless: [:allow_broken, :importing?, :closed_without_fork?]
Andrey Kumanyaev's avatar
Andrey Kumanyaev committed
188
  validates :source_branch, presence: true
189
  validates :target_project, presence: true
Andrey Kumanyaev's avatar
Andrey Kumanyaev committed
190
  validates :target_branch, presence: true
Shinya Maeda's avatar
Shinya Maeda committed
191
  validates :merge_user, presence: true, if: :auto_merge_enabled?, unless: :importing?
192
193
  validate :validate_branches, unless: [:allow_broken, :importing?, :closed_without_fork?]
  validate :validate_fork, unless: :closed_without_fork?
194
  validate :validate_target_project, on: :create
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
195

196
197
198
  scope :by_source_or_target_branch, ->(branch_name) do
    where("source_branch = :branch OR target_branch = :branch", branch: branch_name)
  end
199
  scope :by_milestone, ->(milestone) { where(milestone_id: milestone) }
200
  scope :of_projects, ->(ids) { where(target_project_id: ids) }
201
  scope :from_project, ->(project) { where(source_project_id: project.id) }
202
203
  scope :merged, -> { with_state(:merged) }
  scope :closed_and_merged, -> { with_states(:closed, :merged) }
204
  scope :open_and_closed, -> { with_states(:opened, :closed) }
205
  scope :from_source_branches, ->(branches) { where(source_branch: branches) }
206
207
208
  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
209
210
211
  scope :by_merge_commit_sha, -> (sha) do
    where(merge_commit_sha: sha)
  end
212
213
  scope :join_project, -> { joins(:target_project) }
  scope :references_project, -> { references(:target_project) }
214
  scope :with_api_entity_associations, -> {
215
    preload(:assignees, :author, :unresolved_notes, :labels, :milestone, :timelogs,
216
217
218
219
220
            latest_merge_request_diff: [:merge_request_diff_commits],
            metrics: [:latest_closed_by, :merged_by],
            target_project: [:route, { namespace: :route }],
            source_project: [:route, { namespace: :route }])
  }
221
222
223
224
225
  scope :by_target_branch_wildcard, ->(wildcard_branch_name) do
    where("target_branch LIKE ?", ApplicationRecord.sanitize_sql_like(wildcard_branch_name).tr('*', '%'))
  end
  scope :by_target_branch, ->(branch_name) { where(target_branch: branch_name) }
  scope :preload_source_project, -> { preload(:source_project) }
226

227
228
  scope :with_auto_merge_enabled, -> do
    with_state(:opened).where(auto_merge_enabled: true)
229
230
  end

231
232
  after_save :keep_around_commit

233
234
  alias_attribute :project, :target_project
  alias_attribute :project_id, :target_project_id
235
236
237
238
239
240

  # Currently, `merge_when_pipeline_succeeds` column is used as a flag
  # to check if _any_ auto merge strategy is activated on the merge request.
  # Today, we have multiple strategies and MWPS is one of them.
  # we'd eventually rename the column for avoiding confusions, but in the mean time
  # please use `auto_merge_enabled` alias instead of `merge_when_pipeline_succeeds`.
Shinya Maeda's avatar
Shinya Maeda committed
241
  alias_attribute :auto_merge_enabled, :merge_when_pipeline_succeeds
242
  alias_method :issuing_parent, :target_project
243

244
245
246
247
  RebaseLockTimeout = Class.new(StandardError)

  REBASE_LOCK_MESSAGE = _("Failed to enqueue the rebase operation, possibly due to a long-lived transaction. Try again later.")

248
249
250
251
  def self.reference_prefix
    '!'
  end

252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
  # Returns the top 100 target branches
  #
  # The returned value is a Array containing branch names
  # sort by updated_at of merge request:
  #
  #     ['master', 'develop', 'production']
  #
  # limit - The maximum number of target branch to return.
  def self.recent_target_branches(limit: 100)
    group(:target_branch)
      .select(:target_branch)
      .reorder('MAX(merge_requests.updated_at) DESC')
      .limit(limit)
      .pluck(:target_branch)
  end

268
  def rebase_in_progress?
269
    rebase_jid.present? && Gitlab::SidekiqStatus.running?(rebase_jid)
270
271
  end

272
273
  # 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.
274
  # For more information check: https://gitlab.com/gitlab-org/gitlab-foss/issues/40004
275
  def actual_head_pipeline
276
    head_pipeline&.matches_sha_or_source_sha?(diff_head_sha) ? head_pipeline : nil
277
278
  end

279
280
281
282
283
284
  def merge_pipeline
    return unless merged?

    target_project.pipeline_for(target_branch, merge_commit_sha)
  end

285
286
287
288
  # Pattern used to extract `!123` merge request references from text
  #
  # This pattern supports cross-project references.
  def self.reference_pattern
289
    @reference_pattern ||= %r{
290
      (#{Project.reference_pattern})?
291
292
293
294
      #{Regexp.escape(reference_prefix)}(?<merge_request>\d+)
    }x
  end

295
  def self.link_reference_pattern
296
    @link_reference_pattern ||= super("merge_requests", /(?<merge_request>\d+)/)
297
298
  end

299
300
301
302
  def self.reference_valid?(reference)
    reference.to_i > 0 && reference.to_i <= Gitlab::Database::MAX_INT_VALUE
  end

303
304
305
306
  def self.project_foreign_key
    'target_project_id'
  end

307
308
309
310
311
312
313
314
315
316
317
  # 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)
318
319
    # unscoping unnecessary conditions that'll be applied
    # when executing `where("merge_requests.id IN (#{union.to_sql})")`
320
321
    source = unscoped.where(source_project_id: relation)
    target = unscoped.where(target_project_id: relation)
322

323
    from_union([source, target])
324
325
  end

326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
  # 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

342
  WIP_REGEX = /\A*(\[WIP\]\s*|WIP:\s*|WIP\s+)+\s*/i.freeze
Thomas Balthazar's avatar
Thomas Balthazar committed
343
344
345
346
347
348
349
350
351
352
353
354
355

  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

356
357
  def committers
    @committers ||= commits.committers
358
359
  end

360
361
362
363
364
365
  # 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

366
  def hook_attrs
367
    Gitlab::HookData::MergeRequestBuilder.new(self).build
368
369
  end

370
  # `from` argument can be a Namespace or Project.
371
  def to_reference(from = nil, full: false)
372
373
    reference = "#{self.class.reference_prefix}#{iid}"

374
    "#{project.to_reference(from, full: full)}#{reference}"
375
376
  end

377
  def commits
378
379
380
381
382
383
384
385
386
    return merge_request_diff.commits if persisted?

    commits_arr = if compare_commits
                    compare_commits.reverse
                  else
                    []
                  end

    CommitCollection.new(source_project, commits_arr, source_branch)
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
  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
403
      compare_commits.to_a.reverse.map(&:sha)
404
    else
405
      Array(diff_head_sha)
406
407
408
    end
  end

409
410
411
412
413
414
415
416
417
  # 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

418
  def supports_suggestion?
419
    true
420
421
  end

422
423
424
  # Calls `MergeWorker` to proceed with the merge process and
  # updates `merge_jid` with the MergeWorker#jid.
  # This helps tracking enqueued and ongoing merge jobs.
425
  def merge_async(user_id, params)
426
    jid = MergeWorker.perform_async(id, user_id, params.to_h)
427
    update_column(:merge_jid, jid)
428
429
430
431

    # merge_ongoing? depends on merge_jid
    # expire etag cache since the attribute is changed without triggering callbacks
    expire_etag_cache
432
433
  end

434
435
436
  # Set off a rebase asynchronously, atomically updating the `rebase_jid` of
  # the MR so that the status of the operation can be tracked.
  def rebase_async(user_id)
437
    with_rebase_lock do
438
439
440
441
442
443
444
445
446
447
448
449
      raise ActiveRecord::StaleObjectError if !open? || rebase_in_progress?

      # Although there is a race between setting rebase_jid here and clearing it
      # in the RebaseWorker, it can't do any harm since we check both that the
      # attribute is set *and* that the sidekiq job is still running. So a JID
      # for a completed RebaseWorker is equivalent to a nil JID.
      jid = Sidekiq::Worker.skipping_transaction_check do
        RebaseWorker.perform_async(id, user_id)
      end

      update_column(:rebase_jid, jid)
    end
450
451
452
453

    # rebase_in_progress? depends on rebase_jid
    # expire etag cache since the attribute is changed without triggering callbacks
    expire_etag_cache
454
455
  end

lulalala's avatar
lulalala committed
456
457
458
  def merge_participants
    participants = [author]

Shinya Maeda's avatar
Shinya Maeda committed
459
    if auto_merge_enabled? && !participants.include?(merge_user)
lulalala's avatar
lulalala committed
460
461
462
463
464
465
      participants << merge_user
    end

    participants
  end

466
467
  def first_commit
    merge_request_diff ? merge_request_diff.first_commit : compare_commits.first
468
  end
469

470
  def raw_diffs(*args)
471
    merge_request_diff ? merge_request_diff.raw_diffs(*args) : compare.raw_diffs(*args)
472
473
  end

474
  def diffs(diff_options = {})
475
    if compare
476
      # When saving MR diffs, `expanded` is implicitly added (because we need
477
478
      # to save the entire contents to the DB), so add that here for
      # consistency.
479
      compare.diffs(diff_options.merge(expanded: true))
480
    else
481
      merge_request_diff.diffs(diff_options)
482
    end
483
484
  end

485
486
487
488
  def non_latest_diffs
    merge_request_diffs.where.not(id: merge_request_diff.id)
  end

489
490
491
492
493
494
495
496
497
  # Overwritten in EE
  def note_positions_for_paths(paths, _user = nil)
    positions = notes.new_diff_notes.joins(:note_diff_file)
      .where('note_diff_files.old_path IN (?) OR note_diff_files.new_path IN (?)', paths, paths)
      .positions

    Gitlab::Diff::PositionCollection.new(positions, diff_head_sha)
  end

498
499
500
501
502
503
  def preloads_discussion_diff_highlighting?
    true
  end

  def discussions_diffs
    strong_memoize(:discussions_diffs) do
504
505
506
507
508
      note_diff_files = NoteDiffFile
        .joins(:diff_note)
        .merge(notes.or(commit_notes))
        .includes(diff_note: :project)

509
510
511
512
      Gitlab::DiscussionsDiff::FileCollection.new(note_diff_files.to_a)
    end
  end

513
  def diff_size
514
515
    # Calling `merge_request_diff.diffs.real_size` will also perform
    # highlighting, which we don't need here.
516
    merge_request_diff&.real_size || diffs.real_size
517
518
  end

519
520
521
522
523
524
525
526
527
528
529
530
  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

531
  def diff_base_commit
532
    if persisted?
533
      merge_request_diff.base_commit
534
535
    else
      branch_merge_base_commit
536
537
538
539
540
541
542
543
    end
  end

  def diff_start_commit
    if persisted?
      merge_request_diff.start_commit
    else
      target_branch_head
544
545
546
    end
  end

547
548
549
550
551
552
553
554
555
  def diff_head_commit
    if persisted?
      merge_request_diff.head_commit
    else
      source_branch_head
    end
  end

  def diff_start_sha
556
557
558
559
560
    if persisted?
      merge_request_diff.start_commit_sha
    else
      target_branch_head.try(:sha)
    end
561
562
563
  end

  def diff_base_sha
564
565
566
567
568
    if persisted?
      merge_request_diff.base_commit_sha
    else
      branch_merge_base_commit.try(:sha)
    end
569
570
571
  end

  def diff_head_sha
572
573
574
575
576
    if persisted?
      merge_request_diff.head_commit_sha
    else
      source_branch_head.try(:sha)
    end
577
578
579
580
581
582
583
584
  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

585
586
587
588
589
590
591
592
593
594
595
596
597
598
  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

599
  def source_branch_head
600
601
602
603
604
    strong_memoize(:source_branch_head) do
      if source_project && source_branch_ref
        source_project.repository.commit(source_branch_ref)
      end
    end
605
606
607
  end

  def target_branch_head
608
609
610
    strong_memoize(:target_branch_head) do
      target_project.repository.commit(target_branch_ref)
    end
611
612
  end

613
614
615
616
617
618
619
620
621
  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

622
  def target_branch_sha
623
    @target_branch_sha || target_branch_head.try(:sha)
624
625
626
  end

  def source_branch_sha
627
    @source_branch_sha || source_branch_head.try(:sha)
628
629
  end

630
  def diff_refs
631
632
633
634
635
    if importing? || persisted?
      merge_request_diff.diff_refs
    else
      repository_diff_refs
    end
636
637
638
639
640
641
642
643
644
645
646
647
  end

  # Instead trying to fetch the
  # persisted diff_refs, this method goes
  # straight to the repository to get the
  # most recent data possible.
  def repository_diff_refs
    Gitlab::Diff::DiffRefs.new(
      base_sha:  branch_merge_base_sha,
      start_sha: target_branch_sha,
      head_sha:  source_branch_sha
    )
648
649
  end

650
651
652
653
  def branch_merge_base_sha
    branch_merge_base_commit.try(:sha)
  end

654
  def validate_branches
655
656
    return unless target_project && source_project

657
    if target_project == source_project && target_branch == source_branch
658
659
      errors.add :branch_conflict, "You can't use same project/branch for source and target"
      return
660
    end
661

Mark Chao's avatar
Mark Chao committed
662
663
    [:source_branch, :target_branch].each { |attr| validate_branch_name(attr) }

664
    if opened?
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
      similar_mrs = target_project
        .merge_requests
        .where(source_branch: source_branch, target_branch: target_branch)
        .where(source_project_id: source_project&.id)
        .opened

      similar_mrs = similar_mrs.where.not(id: id) if persisted?

      conflict = similar_mrs.first

      if conflict.present?
        errors.add(
          :validate_branches,
          "Another open merge request already exists for this source branch: #{conflict.to_reference}"
        )
680
      end
681
    end
682
683
  end

Mark Chao's avatar
Mark Chao committed
684
685
686
687
688
689
690
691
692
693
  def validate_branch_name(attr)
    return unless changes_include?(attr)

    branch = read_attribute(attr)

    return unless branch

    errors.add(attr) unless Gitlab::GitRefValidator.validate_merge_request_branch(branch)
  end

694
695
696
697
698
699
  def validate_target_project
    return true if target_project.merge_requests_enabled?

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

700
  def validate_fork
701
    return true unless target_project && source_project
702
    return true if target_project == source_project
703
    return true unless source_project_missing?
704

705
    errors.add :validate_fork,
706
               'Source project is not a fork of the target project'
707
708
  end

709
  def merge_ongoing?
710
711
    # While the MergeRequest is locked, it should present itself as 'merge ongoing'.
    # The unlocking process is handled by StuckMergeJobsWorker scheduled in Cron.
712
713
714
    return true if locked?

    !!merge_jid && !merged? && Gitlab::SidekiqStatus.running?(merge_jid)
715
716
  end

717
  def closed_without_fork?
718
    closed? && source_project_missing?
719
720
  end

721
  def source_project_missing?
722
723
724
    return false unless for_fork?
    return true unless source_project

725
    !source_project.in_fork_network_of?(target_project)
726
727
  end

728
  def reopenable?
729
    closed? && !source_project_missing? && source_branch_exists?
Katarzyna Kobierska's avatar
Katarzyna Kobierska committed
730
731
  end

732
733
  def ensure_merge_request_diff
    merge_request_diff || create_merge_request_diff
734
735
  end

736
  def create_merge_request_diff
737
    fetch_ref!
738

739
    # n+1: https://gitlab.com/gitlab-org/gitlab-foss/issues/37435
740
    Gitlab::GitalyClient.allow_n_plus_1_calls do
741
      merge_request_diffs.create!
742
743
      reload_merge_request_diff
    end
744
745
  end

746
747
748
749
  def viewable_diffs
    @viewable_diffs ||= merge_request_diffs.viewable.to_a
  end

750
  def merge_request_diff_for(diff_refs_or_sha)
751
752
753
754
755
756
757
758
759
760
    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
761

762
763
764
    viewable_diffs.find do |diff|
      diff.attributes.slice(*matcher.keys) == matcher
    end
765
766
  end

767
768
769
770
771
772
773
774
775
776
777
  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

778
779
780
781
782
783
784
  def clear_memoized_shas
    @target_branch_sha = @source_branch_sha = nil

    clear_memoization(:source_branch_head)
    clear_memoization(:target_branch_head)
  end

785
  def reload_diff_if_branch_changed
Jasper Maes's avatar
Jasper Maes committed
786
    if (saved_change_to_source_branch? || saved_change_to_target_branch?) &&
787
        (source_branch_head && target_branch_head)
788
      reload_diff
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
789
790
791
    end
  end

792
  # rubocop: disable CodeReuse/ServiceClass
793
  def reload_diff(current_user = nil)
794
795
    return unless open?

796
    MergeRequests::ReloadDiffsService.new(self, current_user).execute
797
  end
798

799
  def check_mergeability
800
801
    return if Feature.enabled?(:merge_requests_conditional_mergeability_check, default_enabled: true) && !recheck_merge_status?

802
    MergeRequests::MergeabilityCheckService.new(self).execute(retry_lease: false)
803
804
  end
  # rubocop: enable CodeReuse/ServiceClass
805

806
807
808
809
  # Returns boolean indicating the merge_status should be rechecked in order to
  # switch to either can_be_merged or cannot_be_merged.
  def recheck_merge_status?
    self.class.state_machines[:merge_status].check_state?(merge_status)
810
811
  end

Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
812
  def merge_event
813
    @merge_event ||= target_project.events.where(target_id: self.id, target_type: "MergeRequest", action: Event::MERGED).last
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
814
815
  end

816
  def closed_event
817
    @closed_event ||= target_project.events.where(target_id: self.id, target_type: "MergeRequest", action: Event::CLOSED).last
818
819
  end

820
  def work_in_progress?
Thomas Balthazar's avatar
Thomas Balthazar committed
821
    self.class.work_in_progress?(title)
822
823
824
  end

  def wipless_title
Thomas Balthazar's avatar
Thomas Balthazar committed
825
826
827
828
829
    self.class.wipless_title(self.title)
  end

  def wip_title
    self.class.wip_title(self.title)
830
831
  end

832
833
  def mergeable?(skip_ci_check: false)
    return false unless mergeable_state?(skip_ci_check: skip_ci_check)
834

835
    check_mergeability
836

837
    can_be_merged? && !should_be_rebased?
838
839
  end

840
  def mergeable_state?(skip_ci_check: false, skip_discussions_check: false)
841
842
843
    return false unless open?
    return false if work_in_progress?
    return false if broken?
844
    return false unless skip_ci_check || mergeable_ci_state?
845
    return false unless skip_discussions_check || mergeable_discussions_state?
846
847

    true
848
849
  end

850
851
852
853
854
855
856
857
  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

Shinya Maeda's avatar
Shinya Maeda committed
858
  def can_cancel_auto_merge?(current_user)
859
    can_be_merged_by?(current_user) || self.author == current_user
860
861
  end

862
  def can_remove_source_branch?(current_user)
863
    !ProtectedBranch.protected?(source_project, source_branch) &&
864
      !source_project.root_ref?(source_branch) &&
http://jneen.net/'s avatar
http://jneen.net/ committed
865
      Ability.allowed?(current_user, :push_code, source_project) &&
866
      diff_head_sha == source_branch_head.try(:sha)
867
868
  end

869
  def should_remove_source_branch?
870
    Gitlab::Utils.to_boolean(merge_params['should_remove_source_branch'])
871
872
873
  end

  def force_remove_source_branch?
874
    Gitlab::Utils.to_boolean(merge_params['force_remove_source_branch'])
875
876
  end

Shinya Maeda's avatar
Shinya Maeda committed
877
878
879
880
881
882
883
884
885
886
  def auto_merge_strategy
    return unless auto_merge_enabled?

    merge_params['auto_merge_strategy'] || AutoMergeService::STRATEGY_MERGE_WHEN_PIPELINE_SUCCEEDS
  end

  def auto_merge_strategy=(strategy)
    merge_params['auto_merge_strategy'] = strategy
  end

887
888
889
890
  def remove_source_branch?
    should_remove_source_branch? || force_remove_source_branch?
  end

891
  def notify_conflict?
892
893
894
895
896
897
898
899
    (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
900
901
  end

902
  def related_notes
903
904
905
906
    # 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).
907
908
    Note
      .from_union([notes, commit_notes], remove_duplicates: false)
909
      .includes(:noteable)
910
  end
911

912
  alias_method :discussion_notes, :related_notes
913

914
915
916
917
918
919
920
921
922
923
  def commit_notes
    # Fetch comments only from last 100 commits
    commit_ids = commit_shas.take(100)

    Note
      .user
      .where(project_id: [source_project_id, target_project_id])
      .for_commit_id(commit_ids)
  end

924
925
926
  def mergeable_discussions_state?
    return true unless project.only_allow_merge_if_all_discussions_are_resolved?

927
    unresolved_notes.none?(&:to_be_resolved?)
928
929
  end

930
931
932
933
  def for_fork?
    target_project != source_project
  end

934
935
936
937
  # 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.
938
  # This optimization does not apply to issues from external sources.
939
  def cache_merge_request_closes_issues!(current_user = self.author)
940
    return unless project.issues_enabled?
941
    return if closed? || merged?
942

943
    transaction do
944
      self.merge_requests_closing_issues.delete_all
945

946
      closes_issues(current_user).each do |issue|
947
948
        next if issue.is_a?(ExternalIssue)

949
        self.merge_requests_closing_issues.create!(issue: issue)
950
951
952
953
      end
    end
  end

954
955
956
957
958
959
960
961
962
963
964
965
  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

966
  # Return the set of issues that will be closed if this merge request is accepted.
967
  def closes_issues(current_user = self.author)
968
    if target_branch == project.default_branch
969
      messages = [title, description]
970
      messages.concat(commits.map(&:safe_message)) if merge_request_diff
971

972
973
      Gitlab::ClosingIssueExtractor.new(project, current_user)
        .closed_by_message(messages.join("\n"))
974
975
976
977
978
    else
      []
    end
  end

979
  def issues_mentioned_but_not_closing(current_user)
980
    return [] unless target_branch == project.default_branch
981

982
    ext = Gitlab::ReferenceExtractor.new(project, current_user)
983
    ext.analyze("#{title}\n#{description}")
984

985
    ext.issues - visible_closing_issues_for(current_user)
986
987
  end

988
989
  def target_project_path
    if target_project
990
      target_project.full_path
991
992
993
994
995
996
997
    else
      "(removed)"
    end
  end

  def source_project_path
    if source_project
998
      source_project.full_path
999
1000
1001
1002
1003
    else
      "(removed)"
    end
  end

1004
1005
  def source_project_namespace
    if source_project && source_project.namespace
1006
      source_project.namespace.full_path
1007
1008
1009
1010
1011
    else
      "(removed)"
    end
  end

1012
1013
  def target_project_namespace
    if target_project && target_project.namespace
1014
      target_project.namespace.full_path
1015
1016
1017
1018
1019
    else
      "(removed)"
    end
  end

1020
1021
1022
  def source_branch_exists?
    return false unless self.source_project

1023
    self.source_project.repository.branch_exists?(self.source_branch)
1024
1025
1026
1027
1028
  end

  def target_branch_exists?
    return false unless self.target_project

1029
    self.target_project.repository.branch_exists?(self.target_branch)
1030
1031
  end

1032
  def default_merge_commit_message(include_description: false)
1033
    closes_issues_references = visible_closing_issues_for.map do |issue|
1034
1035
1036
      issue.to_reference(target_project)
    end

1037
1038
1039
1040
    message = [
      "Merge branch '#{source_branch}' into '#{target_branch}'",
      title
    ]
1041

1042
    if !include_description && closes_issues_references.present?
1043
      message << "Closes #{closes_issues_references.to_sentence}"
1044
    end
1045

1046
    message << "#{description}" if include_description && description.present?
1047
    message << "See merge request #{to_reference(full: true)}"
1048

1049
    message.join("\n\n")
1050
  end
1051