summaryrefslogtreecommitdiff
path: root/lib/gitlab/template/finders/global_template_finder.rb
blob: 2dd4b7a4092391667dd309731697462d5c2d260d (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
# frozen_string_literal: true

# Searches and reads file present on GitLab installation directory
module Gitlab
  module Template
    module Finders
      class GlobalTemplateFinder < BaseTemplateFinder
        def initialize(base_dir, extension, categories = {})
          @categories = categories
          @extension  = extension
          super(base_dir)
        end

        def read(path)
          File.read(path)
        end

        def find(key)
          file_name = "#{key}#{@extension}"

          # The key is untrusted input, so ensure we can't be directed outside
          # of base_dir
          Gitlab::Utils.check_path_traversal!(file_name)

          directory = select_directory(file_name)
          directory ? File.join(category_directory(directory), file_name) : nil
        end

        def list_files_for(dir)
          dir = "#{dir}/" unless dir.end_with?('/')
          Dir.glob(File.join(dir, "*#{@extension}")).select { |f| f =~ self.class.filter_regex(@extension) }
        end

        private

        def select_directory(file_name)
          @categories.keys.find do |category|
            File.exist?(File.join(category_directory(category), file_name))
          end
        end
      end
    end
  end
end