2016-08-18 10:31:44 -04:00
|
|
|
require 'fileutils'
|
|
|
|
|
2016-03-24 07:28:43 -04:00
|
|
|
module Gitlab
|
|
|
|
module Gfm
|
|
|
|
##
|
|
|
|
# Class that rewrites markdown links for uploads
|
|
|
|
#
|
2016-03-29 07:21:57 -04:00
|
|
|
# Using a pattern defined in `FileUploader` it copies files to a new
|
|
|
|
# project and rewrites all links to uploads in in a given text.
|
|
|
|
#
|
2016-03-24 07:28:43 -04:00
|
|
|
#
|
|
|
|
class UploadsRewriter
|
|
|
|
def initialize(text, source_project, _current_user)
|
|
|
|
@text = text
|
|
|
|
@source_project = source_project
|
|
|
|
@pattern = FileUploader::MARKDOWN_PATTERN
|
|
|
|
end
|
|
|
|
|
|
|
|
def rewrite(target_project)
|
2016-03-30 04:42:39 -04:00
|
|
|
return @text unless needs_rewrite?
|
2016-03-24 07:28:43 -04:00
|
|
|
|
2016-03-29 07:21:57 -04:00
|
|
|
@text.gsub(@pattern) do |markdown|
|
|
|
|
file = find_file(@source_project, $~[:secret], $~[:file])
|
2018-04-18 05:19:40 -04:00
|
|
|
break markdown unless file.try(:exists?)
|
2016-03-24 07:28:43 -04:00
|
|
|
|
2016-03-30 06:11:27 -04:00
|
|
|
new_uploader = FileUploader.new(target_project)
|
2016-08-18 10:31:44 -04:00
|
|
|
with_link_in_tmp_dir(file.file) do |open_tmp_file|
|
|
|
|
new_uploader.store!(open_tmp_file)
|
|
|
|
end
|
2018-01-29 12:57:34 -05:00
|
|
|
new_uploader.markdown_link
|
2016-03-24 07:28:43 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2016-03-29 07:21:57 -04:00
|
|
|
def needs_rewrite?
|
|
|
|
files.any?
|
2016-03-24 07:28:43 -04:00
|
|
|
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-01-29 16:06:17 -05:00
|
|
|
uploader = FileUploader.new(project, secret: secret)
|
2016-03-24 07:28:43 -04:00
|
|
|
uploader.retrieve_from_store!(file)
|
|
|
|
uploader.file
|
|
|
|
end
|
2016-08-18 10:31:44 -04:00
|
|
|
|
|
|
|
# Because the uploaders use 'move_to_store' we must have a temporary
|
|
|
|
# file that is allowed to be (re)moved.
|
|
|
|
def with_link_in_tmp_dir(file)
|
|
|
|
dir = Dir.mktmpdir('UploadsRewriter', File.dirname(file))
|
|
|
|
# The filename matters to Carrierwave so we make sure to preserve it
|
|
|
|
tmp_file = File.join(dir, File.basename(file))
|
|
|
|
File.link(file, tmp_file)
|
|
|
|
# Open the file to placate Carrierwave
|
|
|
|
File.open(tmp_file) { |open_file| yield open_file }
|
|
|
|
ensure
|
|
|
|
FileUtils.rm_rf(dir)
|
|
|
|
end
|
2016-03-24 07:28:43 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|