gitlab-org--gitlab-foss/lib/gitlab/import_export/uploads_manager.rb

96 lines
2.4 KiB
Ruby
Raw Normal View History

2018-07-10 09:40:39 +00:00
module Gitlab
module ImportExport
class UploadsManager
include Gitlab::ImportExport::CommandLineUtil
def initialize(project:, shared:, relative_export_path: 'uploads', from: nil)
@project = project
@shared = shared
@relative_export_path = relative_export_path
@from = from || default_uploads_path
end
2018-07-11 08:24:59 +00:00
def save
2018-07-11 09:36:59 +00:00
copy_files(@from, uploads_export_path) if File.directory?(@from)
2018-07-10 09:40:39 +00:00
2018-07-10 14:33:40 +00:00
if File.file?(@from) && @relative_export_path == 'avatar'
copy_files(@from, File.join(uploads_export_path, @project.avatar.filename))
end
2018-07-10 09:40:39 +00:00
copy_from_object_storage
2018-07-10 14:33:40 +00:00
true
rescue => e
@shared.error(e)
false
2018-07-10 09:40:39 +00:00
end
2018-07-11 08:24:59 +00:00
def restore
Dir["#{uploads_export_path}/**/*"].each do |upload|
next if File.directory?(upload)
2018-07-11 13:58:42 +00:00
add_upload(upload)
2018-07-11 12:52:48 +00:00
end
2018-07-11 13:58:42 +00:00
true
2018-07-11 08:24:59 +00:00
rescue => e
@shared.error(e)
false
end
2018-07-10 09:40:39 +00:00
private
2018-07-11 13:58:42 +00:00
def add_upload(upload)
secret, identifier = upload.split('/').last(2)
uploader_context = {
secret: secret,
identifier: identifier
}
UploadService.new(@project, File.open(upload, 'r'), FileUploader, uploader_context).execute
end
2018-07-10 09:40:39 +00:00
def copy_from_object_storage
return unless Gitlab::ImportExport.object_storage?
uploads.each do |upload_model|
next unless upload_model.file
2018-07-11 13:02:59 +00:00
next if upload_model.upload.local? # Already copied, using the old method
2018-07-10 09:40:39 +00:00
download_and_copy(upload_model)
end
end
def default_uploads_path
FileUploader.absolute_base_dir(@project)
end
def uploads_export_path
@uploads_export_path ||= File.join(@shared.export_path, @relative_export_path)
end
def uploads
@uploads ||= begin
if @relative_export_path == 'avatar'
[@project.avatar].compact
else
(@project.uploads - [@project.avatar&.upload]).map(&:build_uploader)
end
end
end
def download_and_copy(upload)
2018-07-10 14:33:40 +00:00
secret = upload.try(:secret) || ''
upload_path = File.join(uploads_export_path, secret, upload.filename)
2018-07-10 13:29:31 +00:00
2018-07-10 14:33:40 +00:00
mkdir_p(File.join(uploads_export_path, secret))
2018-07-10 09:40:39 +00:00
File.open(upload_path, 'w') do |file|
IO.copy_stream(URI.parse(upload.file.url).open, file)
end
end
end
end
end