summaryrefslogtreecommitdiff
path: root/lib/gitlab/ci/variables/collection/item.rb
blob: 833aa75adb5beb548630ced4b0d4c1eb1c8f880d (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
# frozen_string_literal: true

module Gitlab
  module Ci
    module Variables
      class Collection
        class Item
          def initialize(key:, value:, public: true, file: false, masked: false)
            raise ArgumentError, "`#{key}` must be of type String or nil value, while it was: #{value.class}" unless
              value.is_a?(String) || value.nil?

            @variable = {
              key: key, value: value, public: public, file: file, masked: masked
            }
          end

          def [](key)
            @variable.fetch(key)
          end

          def ==(other)
            to_runner_variable == self.class.fabricate(other).to_runner_variable
          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).
          #
          # If the `variable_masking` feature is enabled we expose the `masked`
          # attribute, otherwise it's not exposed.
          #
          def to_runner_variable
            @variable.reject do |hash_key, hash_value|
              (hash_key == :file && hash_value == false) ||
                (hash_key == :masked && !Feature.enabled?(:variable_masking))
            end
          end

          def self.fabricate(resource)
            case resource
            when Hash
              self.new(resource.symbolize_keys)
            when ::HasVariable
              self.new(resource.to_runner_variable)
            when self
              resource.dup
            else
              raise ArgumentError, "Unknown `#{resource.class}` variable resource!"
            end
          end
        end
      end
    end
  end
end