summaryrefslogtreecommitdiff
path: root/lib/gitlab/config/entry/factory.rb
blob: f76c98f7cbf1d354102dada2f3d76585ec78368f (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
91
92
# frozen_string_literal: true

module Gitlab
  module Config
    module Entry
      ##
      # Factory class responsible for fabricating entry objects.
      #
      class Factory
        InvalidFactory = Class.new(StandardError)

        attr_reader :entry_class

        def initialize(entry_class)
          @entry_class = entry_class
          @metadata = {}
          @attributes = { default: entry_class.default }
        end

        def value(value)
          @value = value
          self
        end

        def metadata(metadata)
          @metadata.merge!(metadata.compact)
          self
        end

        def with(attributes)
          @attributes.merge!(attributes.compact)
          self
        end

        def description
          @attributes[:description]
        end

        def inherit
          @attributes[:inherit]
        end

        def inheritable?
          @attributes[:inherit]
        end

        def reserved?
          @attributes[:reserved]
        end

        def create!
          raise InvalidFactory unless defined?(@value)

          ##
          # We assume that unspecified entry is undefined.
          # See issue #18775.
          #
          if @value.nil?
            Entry::Unspecified.new(fabricate_unspecified)
          else
            fabricate(entry_class, @value)
          end
        end

        private

        def fabricate_unspecified
          ##
          # If entry has a default value we fabricate concrete node
          # with default value.
          #
          default = @attributes.fetch(:default)

          if default.nil?
            fabricate(Entry::Undefined)
          else
            fabricate(entry_class, default)
          end
        end

        def fabricate(entry_class, value = nil)
          entry_class.new(value, **@metadata) do |node|
            node.key = @attributes[:key]
            node.parent = @attributes[:parent]
            node.default = @attributes[:default]
            node.description = @attributes[:description]
          end
        end
      end
    end
  end
end