debian-mirror-gitlab/lib/gitlab/gfm/uploads_rewriter.rb

56 lines
1.4 KiB
Ruby
Raw Normal View History

2019-02-15 15:39:39 +05:30
# frozen_string_literal: true
2017-08-17 22:00:37 +05:30
require 'fileutils'
2016-06-02 11:05:42 +05:30
module Gitlab
module Gfm
##
# Class that rewrites markdown links for uploads
#
# Using a pattern defined in `FileUploader` it copies files to a new
2019-02-15 15:39:39 +05:30
# project and rewrites all links to uploads in a given text.
2016-06-02 11:05:42 +05:30
#
#
class UploadsRewriter
def initialize(text, source_project, _current_user)
@text = text
@source_project = source_project
@pattern = FileUploader::MARKDOWN_PATTERN
end
2019-02-15 15:39:39 +05:30
def rewrite(target_parent)
2016-06-02 11:05:42 +05:30
return @text unless needs_rewrite?
@text.gsub(@pattern) do |markdown|
file = find_file(@source_project, $~[:secret], $~[:file])
2018-10-15 14:42:47 +05:30
break markdown unless file.try(:exists?)
2016-06-02 11:05:42 +05:30
2019-02-15 15:39:39 +05:30
klass = target_parent.is_a?(Namespace) ? NamespaceFileUploader : FileUploader
moved = klass.copy_to(file, target_parent)
2018-11-08 19:23:39 +05:30
moved.markdown_link
2016-06-02 11:05:42 +05:30
end
end
def needs_rewrite?
files.any?
end
def files
referenced_files = @text.scan(@pattern).map do
find_file(@source_project, $~[:secret], $~[:file])
end
referenced_files.compact.select(&:exists?)
end
private
def find_file(project, secret, file)
2018-03-17 18:26:18 +05:30
uploader = FileUploader.new(project, secret: secret)
2016-06-02 11:05:42 +05:30
uploader.retrieve_from_store!(file)
2018-11-08 19:23:39 +05:30
uploader
2017-08-17 22:00:37 +05:30
end
2016-06-02 11:05:42 +05:30
end
end
end