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

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

        def initialize(entry)
          @entry = entry
          @metadata = {}
          @attributes = { default: entry.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 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, @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, default)
          end
        end

        def fabricate(entry, value = nil)
          entry.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