BigW Consortium Gitlab

merge_request.rb 25.9 KB
Newer Older
1
class MergeRequest < ActiveRecord::Base
2
  include InternalId
3
  include Issuable
4
  include Noteable
5
  include Referable
6
  include Sortable
7
  include IgnorableColumn
James Lopez committed
8
  include CreatedAtFilterable
9

10
  ignore_column :locked_at
11

12 13
  belongs_to :target_project, class_name: "Project"
  belongs_to :source_project, class_name: "Project"
14
  belongs_to :merge_user, class_name: "User"
15

16
  has_many :merge_request_diffs
17
  has_one :merge_request_diff,
18
    -> { order('merge_request_diffs.id DESC') }, inverse_of: :merge_request
19

20 21
  belongs_to :head_pipeline, foreign_key: "head_pipeline_id", class_name: "Ci::Pipeline"

22
  has_many :events, as: :target, dependent: :destroy # rubocop:disable Cop/ActiveRecordDependent
23

24 25 26
  has_many :merge_requests_closing_issues,
    class_name: 'MergeRequestsClosingIssues',
    dependent: :delete_all # rubocop:disable Cop/ActiveRecordDependent
27

28 29
  belongs_to :assignee, class_name: "User"

30
  serialize :merge_params, Hash # rubocop:disable Cop/ActiveRecordSerialize
31

32 33
  after_create :ensure_merge_request_diff, unless: :importing?
  after_update :reload_diff_if_branch_changed
34
  after_commit :update_project_counter_caches, on: :destroy
35

36 37 38 39
  # When this attribute is true some MR validation is ignored
  # It allows us to close or modify broken merge requests
  attr_accessor :allow_broken

40 41
  # Temporary fields to store compare vars
  # when creating new merge request
42
  attr_accessor :can_be_created, :compare_commits, :diff_options, :compare
43

Andrew8xx8 committed
44
  state_machine :state, initial: :opened do
45
    event :close do
46
      transition [:opened] => :closed
47 48
    end

49
    event :mark_as_merged do
50
      transition [:opened, :locked] => :merged
51 52 53
    end

    event :reopen do
54
      transition closed: :opened
55 56
    end

57
    event :lock_mr do
58
      transition [:opened] => :locked
59 60
    end

61
    event :unlock_mr do
62
      transition locked: :opened
63 64
    end

65 66 67
    state :opened
    state :closed
    state :merged
68
    state :locked
69 70
  end

71 72 73 74 75 76
  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
77
      transition [:unchecked, :cannot_be_merged] => :can_be_merged
78 79 80
    end

    event :mark_as_unmergeable do
81
      transition [:unchecked, :can_be_merged] => :cannot_be_merged
82 83
    end

84
    state :unchecked
85 86
    state :can_be_merged
    state :cannot_be_merged
87 88

    around_transition do |merge_request, transition, block|
89
      Gitlab::Timeless.timeless(merge_request, &block)
90
    end
91
  end
92

93
  validates :source_project, presence: true, unless: [:allow_broken, :importing?, :closed_without_fork?]
Andrey Kumanyaev committed
94
  validates :source_branch, presence: true
95
  validates :target_project, presence: true
Andrey Kumanyaev committed
96
  validates :target_branch, presence: true
97
  validates :merge_user, presence: true, if: :merge_when_pipeline_succeeds?, unless: :importing?
98 99
  validate :validate_branches, unless: [:allow_broken, :importing?, :closed_without_fork?]
  validate :validate_fork, unless: :closed_without_fork?
100
  validate :validate_target_project, on: :create
101

102 103 104
  scope :by_source_or_target_branch, ->(branch_name) do
    where("source_branch = :branch OR target_branch = :branch", branch: branch_name)
  end
105
  scope :by_milestone, ->(milestone) { where(milestone_id: milestone) }
106
  scope :of_projects, ->(ids) { where(target_project_id: ids) }
107
  scope :from_project, ->(project) { where(source_project_id: project.id) }
108 109
  scope :merged, -> { with_state(:merged) }
  scope :closed_and_merged, -> { with_states(:closed, :merged) }
110
  scope :from_source_branches, ->(branches) { where(source_branch: branches) }
111

112 113
  scope :join_project, -> { joins(:target_project) }
  scope :references_project, -> { references(:target_project) }
114 115 116 117 118
  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
119

120 121
  after_save :keep_around_commit

122 123 124 125
  def self.reference_prefix
    '!'
  end

126 127 128 129
  # Pattern used to extract `!123` merge request references from text
  #
  # This pattern supports cross-project references.
  def self.reference_pattern
130
    @reference_pattern ||= %r{
131
      (#{Project.reference_pattern})?
132 133 134 135
      #{Regexp.escape(reference_prefix)}(?<merge_request>\d+)
    }x
  end

136
  def self.link_reference_pattern
137
    @link_reference_pattern ||= super("merge_requests", /(?<merge_request>\d+)/)
138 139
  end

140 141 142 143
  def self.reference_valid?(reference)
    reference.to_i > 0 && reference.to_i <= Gitlab::Database::MAX_INT_VALUE
  end

144 145 146 147
  def self.project_foreign_key
    'target_project_id'
  end

148 149 150 151 152 153 154 155 156 157 158
  # 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)
159 160 161 162
    # 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)
163 164
    union  = Gitlab::SQL::Union.new([source, target])

165
    where("merge_requests.id IN (#{union.to_sql})") # rubocop:disable GitlabSecurity/SqlInjection
166 167
  end

168 169 170 171 172 173 174 175 176 177 178 179 180 181
  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

182
  def hook_attrs
183
    Gitlab::HookData::MergeRequestBuilder.new(self).build
184 185
  end

186 187 188 189 190 191 192 193
  # Returns a Hash of attributes to be used for Twitter card metadata
  def card_attributes
    {
      'Author'   => author.try(:name),
      'Assignee' => assignee.try(:name)
    }
  end

194
  # These method are needed for compatibility with issues to not mess view and other code
195 196 197 198
  def assignees
    Array(assignee)
  end

199 200 201 202 203 204 205 206
  def assignee_ids
    Array(assignee_id)
  end

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

207 208 209 210
  def assignee_or_author?(user)
    author_id == user.id || assignee_id == user.id
  end

211
  # `from` argument can be a Namespace or Project.
212
  def to_reference(from = nil, full: false)
213 214
    reference = "#{self.class.reference_prefix}#{iid}"

215
    "#{project.to_reference(from, full: full)}#{reference}"
216 217
  end

218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
  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
      compare_commits.reverse.map(&:sha)
    else
      []
    end
  end

248 249 250
  # Calls `MergeWorker` to proceed with the merge process and
  # updates `merge_jid` with the MergeWorker#jid.
  # This helps tracking enqueued and ongoing merge jobs.
251
  def merge_async(user_id, params)
252 253 254 255
    jid = MergeWorker.perform_async(id, user_id, params)
    update_column(:merge_jid, jid)
  end

256 257
  def first_commit
    merge_request_diff ? merge_request_diff.first_commit : compare_commits.first
258
  end
259

260
  def raw_diffs(*args)
261
    merge_request_diff ? merge_request_diff.raw_diffs(*args) : compare.raw_diffs(*args)
262 263
  end

264
  def diffs(diff_options = {})
265
    if compare
266
      # When saving MR diffs, `expanded` is implicitly added (because we need
267 268
      # to save the entire contents to the DB), so add that here for
      # consistency.
269
      compare.diffs(diff_options.merge(expanded: true))
270
    else
271
      merge_request_diff.diffs(diff_options)
272
    end
273 274
  end

275
  def diff_size
276 277
    # Calling `merge_request_diff.diffs.real_size` will also perform
    # highlighting, which we don't need here.
278
    merge_request_diff&.real_size || diffs.real_size
279 280
  end

281
  def diff_base_commit
282
    if persisted?
283
      merge_request_diff.base_commit
284 285
    else
      branch_merge_base_commit
286 287 288 289 290 291 292 293
    end
  end

  def diff_start_commit
    if persisted?
      merge_request_diff.start_commit
    else
      target_branch_head
294 295 296
    end
  end

297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
  def diff_head_commit
    if persisted?
      merge_request_diff.head_commit
    else
      source_branch_head
    end
  end

  def diff_start_sha
    diff_start_commit.try(:sha)
  end

  def diff_base_sha
    diff_base_commit.try(:sha)
  end

  def diff_head_sha
    diff_head_commit.try(:sha)
  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

  def source_branch_head
324 325
    return unless source_project

326
    source_branch_ref = @source_branch_sha || source_branch
327
    source_project.repository.commit(source_branch_ref) if source_branch_ref
328 329 330 331
  end

  def target_branch_head
    target_branch_ref = @target_branch_sha || target_branch
332
    target_project.repository.commit(target_branch_ref) if target_branch_ref
333 334
  end

335 336 337 338 339 340 341 342 343
  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

344
  def target_branch_sha
345
    @target_branch_sha || target_branch_head.try(:sha)
346 347 348
  end

  def source_branch_sha
349
    @source_branch_sha || source_branch_head.try(:sha)
350 351
  end

352
  def diff_refs
353
    if persisted?
354
      merge_request_diff.diff_refs
355
    else
356 357 358 359 360
      Gitlab::Diff::DiffRefs.new(
        base_sha:  diff_base_sha,
        start_sha: diff_start_sha,
        head_sha:  diff_head_sha
      )
361
    end
362 363
  end

364 365 366 367
  def branch_merge_base_sha
    branch_merge_base_commit.try(:sha)
  end

368
  def validate_branches
369
    if target_project == source_project && target_branch == source_branch
370
      errors.add :branch_conflict, "You can not use same project/branch for source and target"
371
    end
372

373
    if opened?
374
      similar_mrs = self.target_project.merge_requests.where(source_branch: source_branch, target_branch: target_branch, source_project_id: source_project.try(:id)).opened
375 376
      similar_mrs = similar_mrs.where('id not in (?)', self.id) if self.id
      if similar_mrs.any?
377
        errors.add :validate_branches,
378
                   "Cannot Create: This merge request already exists: #{similar_mrs.pluck(:title)}"
379
      end
380
    end
381 382
  end

383 384 385 386 387 388
  def validate_target_project
    return true if target_project.merge_requests_enabled?

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

389
  def validate_fork
390
    return true unless target_project && source_project
391
    return true if target_project == source_project
392
    return true unless source_project_missing?
393

394
    errors.add :validate_fork,
395
               'Source project is not a fork of the target project'
396 397
  end

398
  def merge_ongoing?
399 400
    # While the MergeRequest is locked, it should present itself as 'merge ongoing'.
    # The unlocking process is handled by StuckMergeJobsWorker scheduled in Cron.
401 402 403
    return true if locked?

    !!merge_jid && !merged? && Gitlab::SidekiqStatus.running?(merge_jid)
404 405
  end

406
  def closed_without_fork?
407
    closed? && source_project_missing?
408 409
  end

410
  def source_project_missing?
411 412 413
    return false unless for_fork?
    return true unless source_project

414
    !source_project.in_fork_network_of?(target_project)
415 416
  end

417
  def reopenable?
418
    closed? && !source_project_missing? && source_branch_exists?
Katarzyna Kobierska committed
419 420
  end

421 422
  def ensure_merge_request_diff
    merge_request_diff || create_merge_request_diff
423 424
  end

425
  def create_merge_request_diff
426 427
    fetch_ref

428 429 430 431 432
    # 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
433 434 435 436 437 438
  end

  def reload_merge_request_diff
    merge_request_diff(true)
  end

439 440 441 442 443 444 445 446 447
  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|
      diffs = merge_request_diffs.viewable.select_without_diff
      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
448 449
    end

450
    @merge_request_diffs_by_diff_refs_or_sha[diff_refs_or_sha]
451 452
  end

453 454 455 456 457 458 459 460 461 462 463
  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

464
  def reload_diff_if_branch_changed
465 466
    if (source_branch_changed? || target_branch_changed?) &&
        (source_branch_head && target_branch_head)
467
      reload_diff
468 469 470
    end
  end

471
  def reload_diff(current_user = nil)
472 473
    return unless open?

474
    old_diff_refs = self.diff_refs
475

476
    create_merge_request_diff
477
    MergeRequests::MergeRequestDiffCacheService.new.execute(self)
478 479
    new_diff_refs = self.diff_refs

480
    update_diff_discussion_positions(
481
      old_diff_refs: old_diff_refs,
482 483
      new_diff_refs: new_diff_refs,
      current_user: current_user
484
    )
485 486
  end

487
  def check_if_can_be_merged
488
    return unless unchecked? && Gitlab::Database.read_write?
489

490
    can_be_merged =
491
      !broken? && project.repository.can_be_merged?(diff_head_sha, target_branch)
492 493

    if can_be_merged
494 495 496 497
      mark_as_mergeable
    else
      mark_as_unmergeable
    end
498 499
  end

500
  def merge_event
501
    @merge_event ||= target_project.events.where(target_id: self.id, target_type: "MergeRequest", action: Event::MERGED).last
502 503
  end

504
  def closed_event
505
    @closed_event ||= target_project.events.where(target_id: self.id, target_type: "MergeRequest", action: Event::CLOSED).last
506 507
  end

508
  def work_in_progress?
509
    self.class.work_in_progress?(title)
510 511 512
  end

  def wipless_title
513 514 515 516 517
    self.class.wipless_title(self.title)
  end

  def wip_title
    self.class.wip_title(self.title)
518 519
  end

520 521
  def mergeable?(skip_ci_check: false)
    return false unless mergeable_state?(skip_ci_check: skip_ci_check)
522 523 524 525

    check_if_can_be_merged

    can_be_merged?
526 527
  end

528
  def mergeable_state?(skip_ci_check: false)
529 530 531
    return false unless open?
    return false if work_in_progress?
    return false if broken?
532
    return false unless skip_ci_check || mergeable_ci_state?
533
    return false unless mergeable_discussions_state?
534 535

    true
536 537
  end

538 539 540 541 542 543 544 545
  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

546
  def can_cancel_merge_when_pipeline_succeeds?(current_user)
547
    can_be_merged_by?(current_user) || self.author == current_user
548 549
  end

550
  def can_remove_source_branch?(current_user)
551
    !ProtectedBranch.protected?(source_project, source_branch) &&
552
      !source_project.root_ref?(source_branch) &&
553
      Ability.allowed?(current_user, :push_code, source_project) &&
554
      diff_head_commit == source_branch_head
555 556
  end

557
  def should_remove_source_branch?
558
    Gitlab::Utils.to_boolean(merge_params['should_remove_source_branch'])
559 560 561
  end

  def force_remove_source_branch?
562
    Gitlab::Utils.to_boolean(merge_params['force_remove_source_branch'])
563 564 565 566 567 568
  end

  def remove_source_branch?
    should_remove_source_branch? || force_remove_source_branch?
  end

569
  def related_notes
570 571
    # Fetch comments only from last 100 commits
    commits_for_notes_limit = 100
572
    commit_ids = commit_shas.take(commits_for_notes_limit)
573

574 575 576 577 578 579 580 581 582 583 584 585 586 587
    commit_notes = Note
      .except(:order)
      .where(project_id: [source_project_id, target_project_id])
      .where(noteable_type: 'Commit', commit_id: commit_ids)

    # 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}")
588
  end
589

590
  alias_method :discussion_notes, :related_notes
591

592 593 594
  def mergeable_discussions_state?
    return true unless project.only_allow_merge_if_all_discussions_are_resolved?

595
    !discussions_to_be_resolved?
596 597
  end

598 599 600 601
  def for_fork?
    target_project != source_project
  end

602 603 604 605
  def project
    target_project
  end

606 607 608 609
  # 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.
610
  # This optimization does not apply to issues from external sources.
611
  def cache_merge_request_closes_issues!(current_user)
612
    return unless project.issues_enabled?
613

614
    transaction do
615
      self.merge_requests_closing_issues.delete_all
616

617
      closes_issues(current_user).each do |issue|
618 619
        next if issue.is_a?(ExternalIssue)

620
        self.merge_requests_closing_issues.create!(issue: issue)
621 622 623 624
      end
    end
  end

625
  # Return the set of issues that will be closed if this merge request is accepted.
626
  def closes_issues(current_user = self.author)
627
    if target_branch == project.default_branch
628
      messages = [title, description]
629
      messages.concat(commits.map(&:safe_message)) if merge_request_diff
630

631 632
      Gitlab::ClosingIssueExtractor.new(project, current_user)
        .closed_by_message(messages.join("\n"))
633 634 635 636 637
    else
      []
    end
  end

638
  def issues_mentioned_but_not_closing(current_user)
639
    return [] unless target_branch == project.default_branch
640

641
    ext = Gitlab::ReferenceExtractor.new(project, current_user)
642
    ext.analyze("#{title}\n#{description}")
643

644
    ext.issues - closes_issues(current_user)
645 646
  end

647 648
  def target_project_path
    if target_project
649
      target_project.full_path
650 651 652 653 654 655 656
    else
      "(removed)"
    end
  end

  def source_project_path
    if source_project
657
      source_project.full_path
658 659 660 661 662
    else
      "(removed)"
    end
  end

663 664
  def source_project_namespace
    if source_project && source_project.namespace
665
      source_project.namespace.full_path
666 667 668 669 670
    else
      "(removed)"
    end
  end

671 672
  def target_project_namespace
    if target_project && target_project.namespace
673
      target_project.namespace.full_path
674 675 676 677 678
    else
      "(removed)"
    end
  end

679 680 681
  def source_branch_exists?
    return false unless self.source_project

682
    self.source_project.repository.branch_exists?(self.source_branch)
683 684 685 686 687
  end

  def target_branch_exists?
    return false unless self.target_project

688
    self.target_project.repository.branch_exists?(self.target_branch)
689 690
  end

691
  def merge_commit_message(include_description: false)
692 693 694 695
    closes_issues_references = closes_issues.map do |issue|
      issue.to_reference(target_project)
    end

696 697 698 699
    message = [
      "Merge branch '#{source_branch}' into '#{target_branch}'",
      title
    ]
700

701
    if !include_description && closes_issues_references.present?
702
      message << "Closes #{closes_issues_references.to_sentence}"
703
    end
704
    message << "#{description}" if include_description && description.present?
705
    message << "See merge request #{to_reference(full: true)}"
706

707
    message.join("\n\n")
708
  end
709

710 711
  def reset_merge_when_pipeline_succeeds
    return unless merge_when_pipeline_succeeds?
712

713
    self.merge_when_pipeline_succeeds = false
714
    self.merge_user = nil
715 716 717 718
    if merge_params
      merge_params.delete('should_remove_source_branch')
      merge_params.delete('commit_message')
    end
719 720 721 722

    self.save
  end

723
  # Return array of possible target branches
Steven Burgart committed
724
  # depends on target project of MR
725 726 727 728 729 730 731 732 733
  def target_branches
    if target_project.nil?
      []
    else
      target_project.repository.branch_names
    end
  end

  # Return array of possible source branches
Steven Burgart committed
734
  # depends on source project of MR
735 736 737 738 739 740 741
  def source_branches
    if source_project.nil?
      []
    else
      source_project.repository.branch_names
    end
  end
742

743
  def has_ci?
744
    return false if has_no_commits?
745

746
    !!(head_pipeline_id || all_pipelines.any? || source_project&.ci_service)
747 748 749 750 751
  end

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

753
  def broken?
754
    has_no_commits? || branch_missing? || cannot_be_merged?
755 756
  end

757
  def can_be_merged_by?(user)
758 759 760 761 762 763 764
    access = ::Gitlab::UserAccess.new(user, project: project)
    access.can_push_to_branch?(target_branch) || access.can_merge_to_branch?(target_branch)
  end

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

767
  def mergeable_ci_state?
768
    return true unless project.only_allow_merge_if_pipeline_succeeds?
769

770
    !head_pipeline || head_pipeline.success? || head_pipeline.skipped?
771 772
  end

Douwe Maan committed
773
  def environments_for(current_user)
774
    return [] unless diff_head_commit
775

Douwe Maan committed
776 777 778
    @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
779

Douwe Maan committed
780 781 782 783
      if source_project
        envs.concat EnvironmentsFinder.new(source_project, current_user,
          ref: source_branch, commit: diff_head_commit).execute
      end
784

Douwe Maan committed
785
      h[current_user] = envs.uniq
786
    end
Douwe Maan committed
787 788

    @environments[current_user]
789 790
  end

791 792 793 794 795 796 797 798 799
  def state_human_name
    if merged?
      "Merged"
    elsif closed?
      "Closed"
    else
      "Open"
    end
  end
800

801 802 803 804 805 806 807 808 809 810
  def state_icon_name
    if merged?
      "check"
    elsif closed?
      "times"
    else
      "circle-o"
    end
  end

811
  def fetch_ref
812
    write_ref
813
    update_column(:ref_fetched, true)
814 815
  end

816
  def ref_path
817
    "refs/#{Repository::REF_MERGE_REQUEST}/#{iid}/head"
818 819
  end

820
  def ref_fetched?
821 822 823 824 825 826 827
    super ||
      begin
        computed_value = project.repository.ref_exists?(ref_path)
        update_column(:ref_fetched, true) if computed_value

        computed_value
      end
828 829 830
  end

  def ensure_ref_fetched
831
    fetch_ref unless ref_fetched?
832 833
  end

834 835 836 837 838
  def in_locked_state
    begin
      lock_mr
      yield
    ensure
839
      unlock_mr
840 841
    end
  end
842

843 844 845
  def diverged_commits_count
    cache = Rails.cache.read(:"merge_request_#{id}_diverged_commits")

846
    if cache.blank? || cache[:source_sha] != source_branch_sha || cache[:target_sha] != target_branch_sha
847
      cache = {
848 849
        source_sha: source_branch_sha,
        target_sha: target_branch_sha,
850 851 852 853 854 855 856 857 858
        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
859
    return 0 unless source_branch_sha && target_branch_sha
860

861
    Gitlab::Git::Commit.between(target_project.repository.raw_repository, source_branch_sha, target_branch_sha).size
862
  end
863
  private :compute_diverged_commits_count
864 865 866 867 868

  def diverged_from_target_branch?
    diverged_commits_count > 0
  end

869
  def all_pipelines
870
    return Ci::Pipeline.none unless source_project
871

872
    @all_pipelines ||= source_project.pipelines
873
      .where(sha: all_commit_shas, ref: source_branch)
874
      .order(id: :desc)
875
  end
876

877
  # Note that this could also return SHA from now dangling commits
878
  #
879
  def all_commit_shas
880
    if persisted?
881
      column_shas = MergeRequestDiffCommit.where(merge_request_diff: merge_request_diffs).limit(10_000).pluck('sha')
882 883 884
      serialised_shas = merge_request_diffs.where.not(st_commits: nil).flat_map(&:commit_shas)

      (column_shas + serialised_shas).uniq
885 886
    elsif compare_commits
      compare_commits.to_a.reverse.map(&:id)
887
    else
888
      [diff_head_sha]
889
    end
890 891
  end

892 893 894 895
  def merge_commit
    @merge_commit ||= project.commit(merge_commit_sha) if merge_commit_sha
  end

896
  def can_be_reverted?(current_user)
897
    merge_commit && !merge_commit.has_been_reverted?(current_user, self)
898
  end
899 900

  def can_be_cherry_picked?
901
    merge_commit.present?
902
  end
903

904
  def has_complete_diff_refs?
905
    diff_refs && diff_refs.complete?
906 907
  end

908
  def update_diff_discussion_positions(old_diff_refs:, new_diff_refs:, current_user: nil)
909
    return unless has_complete_diff_refs?
910 911
    return if new_diff_refs == old_diff_refs

912 913
    active_diff_discussions = self.notes.new_diff_notes.discussions.select do |discussion|
      discussion.active?(old_diff_refs)
914
    end
915
    return if active_diff_discussions.empty?
916

917
    paths = active_diff_discussions.flat_map { |n| n.diff_file.paths }.uniq
918

919
    service = Discussions::UpdateDiffPositionService.new(
920
      self.project,
921
      current_user,
922 923 924 925 926
      old_diff_refs: old_diff_refs,
      new_diff_refs: new_diff_refs,
      paths: paths
    )

927 928
    active_diff_discussions.each do |discussion|
      service.execute(discussion)
929
    end
930 931 932 933 934 935

    if project.resolve_outdated_diff_discussions?
      MergeRequests::ResolvedDiscussionNotificationService
        .new(project, current_user)
        .execute(self)
    end
936 937
  end

938 939 940
  def keep_around_commit
    project.repository.keep_around(self.merge_commit_sha)
  end
941

942
  def has_commits?
943
    merge_request_diff && commits_count > 0
944 945 946 947 948
  end

  def has_no_commits?
    !has_commits?
  end
949

950
  def mergeable_with_quick_action?(current_user, autocomplete_precheck: false, last_diff_sha: nil)
951 952 953 954 955 956 957 958 959 960
    return false unless can_be_merged_by?(current_user)

    return true if autocomplete_precheck

    return false unless mergeable?(skip_ci_check: true)
    return false if head_pipeline && !(head_pipeline.success? || head_pipeline.active?)
    return false if last_diff_sha != diff_head_sha

    true
  end
961

962 963 964 965
  def update_project_counter_caches?
    state_changed?
  end

966 967 968 969
  def update_project_counter_caches
    Projects::OpenMergeRequestsCountService.new(target_project).refresh_cache
  end

micael.bergeron committed
970
  def first_contribution?
971
    return false if project.team.max_member_access(author_id) > Gitlab::Access::GUEST
micael.bergeron committed
972

973 974 975
    project.merge_requests.merged.where(author_id: author_id).empty?
  end

976 977 978
  private

  def write_ref
979
    target_project.repository.fetch_source_branch(source_project.repository, source_branch, ref_path)
980
  end
981
end