BigW Consortium Gitlab

protected_ref.rb 1.43 KB
Newer Older
1 2 3 4 5
module ProtectedRef
  extend ActiveSupport::Concern

  included do
    belongs_to :project
6

7 8 9
    validates :name, presence: true
    validates :project, presence: true

10
    delegate :matching, :matches?, :wildcard?, to: :ref_matcher
11 12 13 14 15 16 17 18 19
  end

  def commit
    project.commit(self.name)
  end

  class_methods do
    def protected_ref_access_levels(*types)
      types.each do |type|
20
        has_many :"#{type}_access_levels", dependent: :destroy # rubocop:disable Cop/ActiveRecordDependent
21 22

        validates :"#{type}_access_levels", length: { is: 1, message: "are restricted to a single instance per #{self.model_name.human}." }
23

24 25 26 27 28
        accepts_nested_attributes_for :"#{type}_access_levels", allow_destroy: true
      end
    end

    def protected_ref_accessible_to?(ref, user, action:)
29
      access_levels_for_ref(ref, action: action).any? do |access_level|
30 31 32 33
        access_level.check_access(user)
      end
    end

34
    def developers_can?(action, ref)
35 36 37 38 39
      access_levels_for_ref(ref, action: action).any? do |access_level|
        access_level.access_level == Gitlab::Access::DEVELOPER
      end
    end

40
    def access_levels_for_ref(ref, action:)
41
      self.matching(ref).map(&:"#{action}_access_levels").flatten
42 43
    end

44
    def matching(ref_name, protected_refs: nil)
45 46 47 48 49 50 51 52 53 54
      ProtectedRefMatcher.matching(self, ref_name, protected_refs: protected_refs)
    end
  end

  private

  def ref_matcher
    @ref_matcher ||= ProtectedRefMatcher.new(self)
  end
end