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

module Gitlab
  module Ci
    module Variables
      class Collection
        class Sort
          include TSort
          include Gitlab::Utils::StrongMemoize

          def initialize(collection)
            raise(ArgumentError, "A Gitlab::Ci::Variables::Collection object was expected") unless
              collection.is_a?(Collection)

            @collection = collection
          end

          def valid?
            errors.nil?
          end

          # errors sorts an array of variables, ignoring unknown variable references,
          # and returning an error string if a circular variable reference is found
          def errors
            strong_memoize(:errors) do
              # Check for cyclic dependencies and build error message in that case
              cyclic_vars = each_strongly_connected_component.filter_map do |component|
                component.map { |v| v[:key] }.inspect if component.size > 1
              end

              "circular variable reference detected: #{cyclic_vars.join(', ')}" if cyclic_vars.any?
            end
          end

          private

          def tsort_each_node(&block)
            @collection.each(&block)
          end

          def tsort_each_child(var_item, &block)
            depends_on = var_item.depends_on
            return unless depends_on

            depends_on.filter_map { |var_ref_name| @collection[var_ref_name] }.each(&block)
          end
        end
      end
    end
  end
end