summaryrefslogtreecommitdiff
path: root/app/validators/branch_filter_validator.rb
blob: 6a0899be850b6d75b3989a007b8143808c0de862 (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
# frozen_string_literal: true

# BranchFilterValidator
#
# Custom validator for branch names. Squishes whitespace and ignores empty
# string.  This only checks that a string is a valid git branch name. It does
# not check whether a branch already exists.
#
# Example:
#
#   class Webhook < ActiveRecord::Base
#     validates :push_events_branch_filter, branch_name: true
#   end
#
class BranchFilterValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    value.squish! unless value.nil?

    if value.present?
      value_without_wildcards = value.tr('*', 'x')

      unless Gitlab::GitRefValidator.validate(value_without_wildcards)
        record.errors[attribute] << "is not a valid branch name"
      end

      unless value.length <= 4000
        record.errors[attribute] << "is longer than the allowed length of 4000 characters."
      end
    end
  end

  private

  def contains_wildcard?(value)
    value.include?('*')
  end
end