summaryrefslogtreecommitdiff
path: root/lib/gitlab/ci/variables/collection.rb
blob: 2f5987f28469a52a38a8c10612fffacebd72b968 (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
module Gitlab
  module Ci
    module Variables
      class Collection
        include Enumerable

        Variable = Struct.new(:key, :value, :public, :file)

        def initialize(variables = [])
          @variables = []

          variables.each { |variable| append(variable) }
        end

        def append(resource)
          @variables.append(fabricate(resource))
        end

        def each
          @variables.each { |variable| yield variable }
        end

        def +(other)
          self.class.new.tap do |collection|
            self.each { |variable| collection.append(variable) }
            other.each { |variable| collection.append(variable) }
          end
        end

        ##
        # If `file: true` has been provided we expose it, otherwise we
        # don't expose `file` attribute at all (stems from what the runner
        # expects).
        #
        def to_runner_variables
          self.map do |variable|
            variable.to_h.reject do |component, value|
              component == :file && value == false
            end
          end
        end

        private

        def fabricate(resource)
          case resource
          when Hash
            Collection::Variable.new(resource.fetch(:key),
                                     resource.fetch(:value),
                                     resource.fetch(:public, false),
                                     resource.fetch(:file, false))
          when ::Ci::Variable
            Variable.new(resource.key, resource.value, false, false)
          when Collection::Variable
            resource.dup
          else
            raise ArgumentError, 'Unknown CI/CD variable resource!'
          end
        end
      end
    end
  end
end