summaryrefslogtreecommitdiff
path: root/lib/gitlab/ci/config/edge_stages_injector.rb
blob: 64ff9f951e4390a18d8306b114c6922a332e8dc2 (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
# frozen_string_literal: true

module Gitlab
  module Ci
    class Config
      class EdgeStagesInjector
        PRE_PIPELINE = '.pre'
        POST_PIPELINE = '.post'
        EDGES = [PRE_PIPELINE, POST_PIPELINE].freeze

        def self.wrap_stages(stages)
          stages = stages.to_a - EDGES
          stages.unshift PRE_PIPELINE
          stages.push POST_PIPELINE

          stages
        end

        def initialize(config)
          @config = config.to_h.deep_dup
        end

        def to_hash
          if config.key?(:stages)
            process(:stages)
          elsif config.key?(:types)
            process(:types)
          else
            config
          end
        end

        private

        attr_reader :config

        delegate :wrap_stages, to: :class

        def process(keyword)
          stages = extract_stages(keyword)
          return config if stages.empty?

          stages = wrap_stages(stages)
          config[keyword] = stages
          config
        end

        def extract_stages(keyword)
          stages = config[keyword]
          return [] unless stages.is_a?(Array)

          stages
        end
      end
    end
  end
end