2018-11-18 11:00:15 +05:30
# frozen_string_literal: true
2018-03-17 18:26:18 +05:30
module Projects
module HashedStorage
AttachmentMigrationError = Class . new ( StandardError )
class MigrateAttachmentsService < BaseService
2018-11-18 11:00:15 +05:30
attr_reader :logger , :old_disk_path , :new_disk_path
2018-03-17 18:26:18 +05:30
2018-11-18 11:00:15 +05:30
def initialize ( project , old_disk_path , logger : nil )
2018-03-17 18:26:18 +05:30
@project = project
@logger = logger || Rails . logger
2018-11-18 11:00:15 +05:30
@old_disk_path = old_disk_path
@new_disk_path = project . disk_path
2018-03-17 18:26:18 +05:30
end
def execute
origin = FileUploader . absolute_base_dir ( project )
2018-11-18 11:00:15 +05:30
# It's possible that old_disk_path does not match project.disk_path. For example, that happens when we rename a project
origin . sub! ( / #{ Regexp . escape ( project . full_path ) } \ z / , old_disk_path )
2018-03-17 18:26:18 +05:30
project . storage_version = :: Project :: HASHED_STORAGE_FEATURES [ :attachments ]
target = FileUploader . absolute_base_dir ( project )
result = move_folder! ( origin , target )
project . save!
if result && block_given?
yield
end
result
end
private
2018-11-18 11:00:15 +05:30
def move_folder! ( old_disk_path , new_disk_path )
unless File . directory? ( old_disk_path )
logger . info ( " Skipped attachments migration from ' #{ old_disk_path } ' to ' #{ new_disk_path } ', source path doesn't exist or is not a directory (PROJECT_ID= #{ project . id } ) " )
2018-03-17 18:26:18 +05:30
return
end
2018-11-18 11:00:15 +05:30
if File . exist? ( new_disk_path )
logger . error ( " Cannot migrate attachments from ' #{ old_disk_path } ' to ' #{ new_disk_path } ', target path already exist (PROJECT_ID= #{ project . id } ) " )
raise AttachmentMigrationError , " Target path ' #{ new_disk_path } ' already exist "
2018-03-17 18:26:18 +05:30
end
# Create hashed storage base path folder
2018-11-18 11:00:15 +05:30
FileUtils . mkdir_p ( File . dirname ( new_disk_path ) )
2018-03-17 18:26:18 +05:30
2018-11-18 11:00:15 +05:30
FileUtils . mv ( old_disk_path , new_disk_path )
logger . info ( " Migrated project attachments from ' #{ old_disk_path } ' to ' #{ new_disk_path } ' (PROJECT_ID= #{ project . id } ) " )
2018-03-17 18:26:18 +05:30
true
end
end
end
end