summaryrefslogtreecommitdiff
path: root/lib/gitlab/config/entry/configurable.rb
blob: 6667a5d3d33713aeb91ce21fadbbc8eb84450303 (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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# frozen_string_literal: true

module Gitlab
  module Config
    module Entry
      ##
      # This mixin is responsible for adding DSL, which purpose is to
      # simplifly process of adding child nodes.
      #
      # This can be used only if parent node is a configuration entry that
      # holds a hash as a configuration value, for example:
      #
      # job:
      #   script: ...
      #   artifacts: ...
      #
      module Configurable
        extend ActiveSupport::Concern

        included do
          include Validatable

          validations do
            validates :config, type: Hash, unless: :skip_config_hash_validation?
          end
        end

        # rubocop: disable CodeReuse/ActiveRecord
        def compose!(deps = nil)
          return unless valid?

          self.class.nodes.each do |key, factory|
            # If we override the config type validation
            # we can end with different config types like String
            next unless config.is_a?(Hash)

            factory
              .value(config[key])
              .with(key: key, parent: self)

            entries[key] = factory.create!
          end

          yield if block_given?

          entries.each_value do |entry|
            entry.compose!(deps)
          end
        end
        # rubocop: enable CodeReuse/ActiveRecord

        def skip_config_hash_validation?
          false
        end

        class_methods do
          def nodes
            Hash[(@nodes || {}).map { |key, factory| [key, factory.dup] }]
          end

          private

          # rubocop: disable CodeReuse/ActiveRecord
          def entry(key, entry, metadata)
            factory = ::Gitlab::Config::Entry::Factory.new(entry)
              .with(description: metadata[:description])
              .with(default: metadata[:default])

            (@nodes ||= {}).merge!(key.to_sym => factory)
          end
          # rubocop: enable CodeReuse/ActiveRecord

          def helpers(*nodes)
            nodes.each do |symbol|
              define_method("#{symbol}_defined?") do
                entries[symbol]&.specified?
              end

              define_method("#{symbol}_value") do
                return unless entries[symbol] && entries[symbol].valid?

                entries[symbol].value
              end
            end
          end
        end
      end
    end
  end
end