debian-mirror-gitlab/lib/gitlab/template/base_template.rb

89 lines
2.6 KiB
Ruby
Raw Normal View History

2016-06-22 15:30:34 +05:30
module Gitlab
module Template
class BaseTemplate
2016-09-13 17:45:13 +05:30
def initialize(path, project = nil)
2016-06-22 15:30:34 +05:30
@path = path
2016-09-13 17:45:13 +05:30
@finder = self.class.finder(project)
2016-06-22 15:30:34 +05:30
end
def name
File.basename(@path, self.class.extension)
end
def content
2016-09-13 17:45:13 +05:30
@finder.read(@path)
end
def to_json
{ name: name, content: content }
2016-06-22 15:30:34 +05:30
end
class << self
2016-09-13 17:45:13 +05:30
def all(project = nil)
if categories.any?
categories.keys.flat_map { |cat| by_category(cat, project) }
else
by_category("", project)
end
2016-06-22 15:30:34 +05:30
end
2016-09-13 17:45:13 +05:30
def find(key, project = nil)
path = self.finder(project).find(key)
path.present? ? new(path, project) : nil
2016-06-22 15:30:34 +05:30
end
2016-09-13 17:45:13 +05:30
# Set categories as sub directories
# Example: { "category_name_1" => "directory_path_1", "category_name_2" => "directory_name_2" }
# Default is no category with all files in base dir of each class
2016-06-22 15:30:34 +05:30
def categories
2016-09-13 17:45:13 +05:30
{}
2016-06-22 15:30:34 +05:30
end
def extension
raise NotImplementedError
end
def base_dir
raise NotImplementedError
end
2016-09-13 17:45:13 +05:30
# Defines which strategy will be used to get templates files
# RepoTemplateFinder - Finds templates on project repository, templates are filtered perproject
# GlobalTemplateFinder - Finds templates on gitlab installation source, templates can be used in all projects
def finder(project = nil)
raise NotImplementedError
2016-06-22 15:30:34 +05:30
end
2016-09-13 17:45:13 +05:30
def by_category(category, project = nil)
directory = category_directory(category)
files = finder(project).list_files_for(directory)
files.map { |f| new(f, project) }
2016-06-22 15:30:34 +05:30
end
2016-09-13 17:45:13 +05:30
def category_directory(category)
return base_dir unless category.present?
2016-06-22 15:30:34 +05:30
2016-09-13 17:45:13 +05:30
File.join(base_dir, categories[category])
2016-06-22 15:30:34 +05:30
end
2016-09-13 17:45:13 +05:30
# If template is organized by category it returns { category_name: [{ name: template_name }, { name: template2_name }] }
# If no category is present returns [{ name: template_name }, { name: template2_name}]
def dropdown_names(project = nil)
return [] if project && !project.repository.exists?
2016-06-22 15:30:34 +05:30
2016-09-13 17:45:13 +05:30
if categories.any?
categories.keys.map do |category|
files = self.by_category(category, project)
[category, files.map { |t| { name: t.name } }]
end.to_h
else
files = self.all(project)
files.map { |t| { name: t.name } }
end
2016-06-22 15:30:34 +05:30
end
end
end
end
end