summaryrefslogtreecommitdiff
path: root/app/services/protected_branches/legacy_api_update_service.rb
blob: 65dc3297ae8bf75d067a6c4aa4f96584e7f35d06 (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
# frozen_string_literal: true

# The branches#protect API still uses the `developers_can_push` and `developers_can_merge`
# flags for backward compatibility, and so performs translation between that format and the
# internal data model (separate access levels). The translation code is non-trivial, and so
# lives in this service.
module ProtectedBranches
  class LegacyApiUpdateService < BaseService
    attr_reader :protected_branch, :developers_can_push, :developers_can_merge

    def execute(protected_branch)
      @protected_branch = protected_branch
      @developers_can_push = params.delete(:developers_can_push)
      @developers_can_merge = params.delete(:developers_can_merge)

      protected_branch.transaction do
        delete_redundant_access_levels

        case developers_can_push
        when true
          params[:push_access_levels_attributes] = [{ access_level: Gitlab::Access::DEVELOPER }]
        when false
          params[:push_access_levels_attributes] = [{ access_level: Gitlab::Access::MAINTAINER }]
        end

        case developers_can_merge
        when true
          params[:merge_access_levels_attributes] = [{ access_level: Gitlab::Access::DEVELOPER }]
        when false
          params[:merge_access_levels_attributes] = [{ access_level: Gitlab::Access::MAINTAINER }]
        end

        service = ProtectedBranches::UpdateService.new(project, current_user, params)
        service.execute(protected_branch)
      end
    end

    private

    def delete_redundant_access_levels
      unless developers_can_merge.nil?
        protected_branch.merge_access_levels.destroy_all # rubocop: disable DestroyAll
      end

      unless developers_can_push.nil?
        protected_branch.push_access_levels.destroy_all # rubocop: disable DestroyAll
      end
    end
  end
end

ProtectedBranches::LegacyApiUpdateService.prepend_if_ee('EE::ProtectedBranches::LegacyApiUpdateService')