1# frozen_string_literal: true
2
3module Gitlab
4  module Ci
5    module Variables
6      module Helpers
7        class << self
8          def merge_variables(current_vars, new_vars)
9            current_vars = transform_from_yaml_variables(current_vars)
10            new_vars = transform_from_yaml_variables(new_vars)
11
12            transform_to_yaml_variables(
13              current_vars.merge(new_vars)
14            )
15          end
16
17          def transform_to_yaml_variables(vars)
18            vars.to_h.map do |key, value|
19              { key: key.to_s, value: value, public: true }
20            end
21          end
22
23          def transform_from_yaml_variables(vars)
24            return vars.stringify_keys if vars.is_a?(Hash)
25
26            vars.to_a.to_h { |var| [var[:key].to_s, var[:value]] }
27          end
28
29          def inherit_yaml_variables(from:, to:, inheritance:)
30            merge_variables(apply_inheritance(from, inheritance), to)
31          end
32
33          private
34
35          def apply_inheritance(variables, inheritance)
36            case inheritance
37            when true then variables
38            when false then {}
39            when Array then variables.select { |var| inheritance.include?(var[:key]) }
40            end
41          end
42        end
43      end
44    end
45  end
46end
47