push_options.rb 2.2 KB
Newer Older
1 2 3 4 5 6
# frozen_string_literal: true

module Gitlab
  class PushOptions
    VALID_OPTIONS = HashWithIndifferentAccess.new({
      merge_request: {
7 8
        keys: [
          :create,
9
          :description,
10
          :label,
11 12
          :merge_when_pipeline_succeeds,
          :remove_source_branch,
13
          :target,
14 15
          :title,
          :unlabel
16
        ]
17 18 19 20 21 22
      },
      ci: {
        keys: [:skip]
      }
    }).freeze

23 24 25 26 27
    MULTI_VALUE_OPTIONS = [
      %w[merge_request label],
      %w[merge_request unlabel]
    ].freeze

28 29 30 31
    NAMESPACE_ALIASES = HashWithIndifferentAccess.new({
      mr: :merge_request
    }).freeze

S
Stan Hu 已提交
32
    OPTION_MATCHER = /(?<namespace>[^\.]+)\.(?<key>[^=]+)=?(?<value>.*)/.freeze
33 34 35 36 37 38 39 40 41 42 43

    attr_reader :options

    def initialize(options = [])
      @options = parse_options(options)
    end

    def get(*args)
      options.dig(*args)
    end

44 45 46 47 48
    # Allow #to_json serialization
    def as_json(*_args)
      options
    end

49 50 51 52 53 54 55 56 57 58
    private

    def parse_options(raw_options)
      options = HashWithIndifferentAccess.new

      Array.wrap(raw_options).each do |option|
        namespace, key, value = parse_option(option)

        next if [namespace, key].any?(&:nil?)

59
        store_option_info(options, namespace, key, value)
60 61 62 63 64
      end

      options
    end

65 66 67 68 69 70 71 72 73 74 75
    def store_option_info(options, namespace, key, value)
      options[namespace] ||= HashWithIndifferentAccess.new

      if option_multi_value?(namespace, key)
        options[namespace][key] ||= HashWithIndifferentAccess.new(0)
        options[namespace][key][value] += 1
      else
        options[namespace][key] = value
      end
    end

76 77 78 79
    def option_multi_value?(namespace, key)
      MULTI_VALUE_OPTIONS.any? { |arr| arr == [namespace, key] }
    end

80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
    def parse_option(option)
      parts = OPTION_MATCHER.match(option)
      return unless parts

      namespace, key, value = parts.values_at(:namespace, :key, :value).map(&:strip)
      namespace = NAMESPACE_ALIASES[namespace] if NAMESPACE_ALIASES[namespace]
      value = value.presence || true

      return unless valid_option?(namespace, key)

      [namespace, key, value]
    end

    def valid_option?(namespace, key)
      keys = VALID_OPTIONS.dig(namespace, :keys)
      keys && keys.include?(key.to_sym)
    end
  end
end