repo_template_finder.rb 1.64 KB
Newer Older
1 2 3 4 5 6
# Searches and reads files present on each Gitlab project repository
module Gitlab
  module Template
    module Finders
      class RepoTemplateFinder < BaseTemplateFinder
        # Raised when file is not found
7
        FileNotFoundError = Class.new(StandardError)
8 9 10 11 12 13 14 15 16 17 18 19 20

        def initialize(project, base_dir, extension, categories = {})
          @categories     = categories
          @extension      = extension
          @repository     = project.repository
          @commit         = @repository.head_commit if @repository.exists?

          super(base_dir)
        end

        def read(path)
          blob = @repository.blob_at(@commit.id, path) if @commit
          raise FileNotFoundError if blob.nil?
21

22 23 24 25 26 27 28 29
          blob.data
        end

        def find(key)
          file_name = "#{key}#{@extension}"
          directory = select_directory(file_name)
          raise FileNotFoundError if directory.nil?

30
          File.join(category_directory(directory), file_name)
31 32 33 34 35 36 37 38 39
        end

        def list_files_for(dir)
          return [] unless @commit

          dir << '/' unless dir.end_with?('/')

          entries = @repository.tree(:head, dir).entries

40 41
          paths = entries.map(&:path)
          paths.select { |f| f =~ self.class.filter_regex(@extension) }
42 43 44 45 46 47 48 49
        end

        private

        def select_directory(file_name)
          return [] unless @commit

          # Insert root as directory
50
          directories = ["", *@categories.keys]
51 52

          directories.find do |category|
53
            path = File.join(category_directory(category), file_name)
54 55 56 57 58 59 60
            @repository.blob_at(@commit.id, path)
          end
        end
      end
    end
  end
end