base.rb 2.6 KB
Newer Older
1 2
# frozen_string_literal: true

3 4
module Gitlab
  module Ci
5 6 7 8
    class Config
      module External
        module File
          class Base
9 10
            include Gitlab::Utils::StrongMemoize

11
            attr_reader :location, :params, :context, :errors
12

13
            YAML_WHITELIST_EXTENSION = /.+\.(yml|yaml)$/i.freeze
14

15
            Context = Struct.new(:project, :sha, :user, :expandset)
16 17 18 19

            def initialize(params, context)
              @params = params
              @context = context
20 21
              @errors = []

22
              validate!
23 24
            end

25 26 27 28
            def matching?
              location.present?
            end

29
            def invalid_extension?
30
              location.nil? || !::File.basename(location).match?(YAML_WHITELIST_EXTENSION)
31
            end
32

33
            def valid?
34 35 36 37 38
              errors.none?
            end

            def error_message
              errors.first
39
            end
40

41
            def content
42
              raise NotImplementedError, 'subclass must implement fetching raw content'
43
            end
44

45
            def to_hash
46
              expanded_content_hash
47 48 49 50
            end

            protected

51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
            def expanded_content_hash
              return unless content_hash

              strong_memoize(:expanded_content_yaml) do
                expand_includes(content_hash)
              end
            end

            def content_hash
              strong_memoize(:content_yaml) do
                Gitlab::Config::Loader::Yaml.new(content).load!
              end
            rescue Gitlab::Config::Loader::FormatError
              nil
            end

67 68 69 70 71 72
            def validate!
              validate_location!
              validate_content! if errors.none?
              validate_hash! if errors.none?
            end

73 74 75 76 77 78 79
            def validate_location!
              if invalid_extension?
                errors.push("Included file `#{location}` does not have YAML extension!")
              end
            end

            def validate_content!
80
              if content.blank?
81 82 83 84 85
                errors.push("Included file `#{location}` is empty or does not exist!")
              end
            end

            def validate_hash!
86
              if to_hash.blank?
87 88
                errors.push("Included file `#{location}` does not have valid YAML syntax!")
              end
89
            end
90 91 92 93 94 95 96 97

            def expand_includes(hash)
              External::Processor.new(hash, **expand_context).perform
            end

            def expand_context
              { project: nil, sha: nil, user: nil, expandset: context.expandset }
            end
98 99 100 101 102 103
          end
        end
      end
    end
  end
end