summaryrefslogtreecommitdiff
path: root/lib/gitlab/ci/config/normalizer/matrix_strategy.rb
blob: 312f98f850adc7eaf22facf02665cb41b1fb6a1c (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
# frozen_string_literal: true

module Gitlab
  module Ci
    class Config
      class Normalizer
        class MatrixStrategy
          class << self
            def applies_to?(config)
              config.is_a?(Hash) && config.key?(:matrix)
            end

            def build_from(job_name, initial_config)
              config = expand(initial_config[:matrix])
              total = config.size

              config.map.with_index do |vars, index|
                new(job_name, index.next, vars, total)
              end
            end

            # rubocop: disable CodeReuse/ActiveRecord
            def expand(config)
              config.flat_map do |config|
                values = config.values

                values[0]
                  .product(*values.from(1))
                  .map { |vals| config.keys.zip(vals).to_h }
              end
            end
            # rubocop: enable CodeReuse/ActiveRecord
          end

          def initialize(job_name, instance, variables, total)
            @job_name = job_name
            @instance = instance
            @variables = variables.to_h
            @total = total
          end

          def attributes
            {
              name: name,
              instance: instance,
              job_variables: variables,
              parallel: { total: total }
            }.compact
          end

          def name
            vars = variables
              .values
              .compact
              .join(', ')

            "#{job_name}: [#{vars}]"
          end

          private

          attr_reader :job_name, :instance, :variables, :total
        end
      end
    end
  end
end