summaryrefslogtreecommitdiff
path: root/app/models/protectable_dropdown.rb
blob: 855876f2ec905874346878af13c366ccc54c2d74 (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
# frozen_string_literal: true

class ProtectableDropdown
  REF_TYPES = %i[branches tags].freeze
  REF_NAME_METHODS = {
    branches: :branch_names,
    tags: :tag_names
  }.freeze

  def initialize(project, ref_type)
    raise ArgumentError, "invalid ref type `#{ref_type}`" unless ref_type.in?(REF_TYPES)

    @project = project
    @ref_type = ref_type
  end

  # Tags/branches which are yet to be individually protected
  def protectable_ref_names
    return [] if @project.empty_repo?

    @protectable_ref_names ||= ref_names - non_wildcard_protected_ref_names
  end

  def hash
    protectable_ref_names.map { |ref_name| { text: ref_name, id: ref_name, title: ref_name } }
  end

  private

  def ref_names
    @project.repository.public_send(ref_name_method) # rubocop:disable GitlabSecurity/PublicSend
  end

  def ref_name_method
    REF_NAME_METHODS[@ref_type]
  end

  def protections
    @project.public_send("protected_#{@ref_type}") # rubocop:disable GitlabSecurity/PublicSend
  end

  def non_wildcard_protected_ref_names
    protections.reject(&:wildcard?).map(&:name)
  end
end