diff options
author | Francisco Javier López <fjlopez@gitlab.com> | 2018-09-04 13:39:08 +0300 |
---|---|---|
committer | Douwe Maan <douwe@gitlab.com> | 2018-09-04 13:39:08 +0300 |
commit | f9475e299c6f6b363d5ea302f1295a3ea0bf9adb (patch) | |
tree | cec2910cfe3c0065a88e884a60a588c548c0cae9 /app/services/wikis | |
parent | 0689900c7a5ce368c780f1fce8f465685bbfa9d6 (diff) |
Uploads to wiki stored inside the wiki git repository
Diffstat (limited to 'app/services/wikis')
-rw-r--r-- | app/services/wikis/create_attachment_service.rb | 71 |
1 files changed, 71 insertions, 0 deletions
diff --git a/app/services/wikis/create_attachment_service.rb b/app/services/wikis/create_attachment_service.rb new file mode 100644 index 00000000000..30fe0e371a6 --- /dev/null +++ b/app/services/wikis/create_attachment_service.rb @@ -0,0 +1,71 @@ +# frozen_string_literal: true + +module Wikis + class CreateAttachmentService < Files::CreateService + ATTACHMENT_PATH = 'uploads'.freeze + MAX_FILENAME_LENGTH = 255 + + delegate :wiki, to: :project + delegate :repository, to: :wiki + + def initialize(*args) + super + + @file_name = truncate_file_name(params[:file_name]) + @file_path = File.join(ATTACHMENT_PATH, SecureRandom.hex, @file_name) if @file_name + @commit_message ||= "Upload attachment #{@file_name}" + @branch_name ||= wiki.default_branch + end + + def create_commit! + commit_result(create_transformed_commit(@file_content)) + end + + private + + def truncate_file_name(file_name) + return unless file_name.present? + return file_name if file_name.length <= MAX_FILENAME_LENGTH + + extension = File.extname(file_name) + truncate_at = MAX_FILENAME_LENGTH - extension.length - 1 + base_name = File.basename(file_name, extension)[0..truncate_at] + base_name + extension + end + + def validate! + validate_file_name! + validate_permissions! + end + + def validate_file_name! + raise_error('The file name cannot be empty') unless @file_name + end + + def validate_permissions! + unless can?(current_user, :create_wiki, project) + raise_error('You are not allowed to push to the wiki') + end + end + + def create_transformed_commit(content) + repository.create_file( + current_user, + @file_path, + content, + message: @commit_message, + branch_name: @branch_name, + author_email: @author_email, + author_name: @author_name) + end + + def commit_result(commit_id) + { + file_name: @file_name, + file_path: @file_path, + branch: @branch_name, + commit: commit_id + } + end + end +end |