summaryrefslogtreecommitdiff
path: root/app/services/auto_merge_service.rb
blob: 053c6d71fbbb0ae1725323d724b1435a27c88a38 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# frozen_string_literal: true

class AutoMergeService < BaseService
  STRATEGY_MERGE_WHEN_PIPELINE_SUCCEEDS = 'merge_when_pipeline_succeeds'
  STRATEGIES = [STRATEGY_MERGE_WHEN_PIPELINE_SUCCEEDS].freeze

  class << self
    def all_strategies
      STRATEGIES
    end

    def get_service_class(strategy)
      return unless all_strategies.include?(strategy)

      "::AutoMerge::#{strategy.camelize}Service".constantize
    end
  end

  def execute(merge_request, strategy)
    service = get_service_instance(strategy)

    return :failed unless service&.available_for?(merge_request)

    service.execute(merge_request)
  end

  def update(merge_request)
    return :failed unless merge_request.auto_merge_enabled?

    get_service_instance(merge_request.auto_merge_strategy).update(merge_request)
  end

  def process(merge_request)
    return unless merge_request.auto_merge_enabled?

    get_service_instance(merge_request.auto_merge_strategy).process(merge_request)
  end

  def cancel(merge_request)
    return error("Can't cancel the automatic merge", 406) unless merge_request.auto_merge_enabled?

    get_service_instance(merge_request.auto_merge_strategy).cancel(merge_request)
  end

  def abort(merge_request, reason)
    return error("Can't abort the automatic merge", 406) unless merge_request.auto_merge_enabled?

    get_service_instance(merge_request.auto_merge_strategy).abort(merge_request, reason)
  end

  def available_strategies(merge_request)
    self.class.all_strategies.select do |strategy|
      get_service_instance(strategy).available_for?(merge_request)
    end
  end

  private

  def get_service_instance(strategy)
    self.class.get_service_class(strategy)&.new(project, current_user, params)
  end
end