2024-05-03 03:04:43 +00:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
module StorageManager
|
|
|
|
class Local
|
2024-05-06 07:47:53 +00:00
|
|
|
DEFAULT_PERMISSIONS = 0o644
|
2024-05-03 03:04:43 +00:00
|
|
|
attr_reader :base_url, :base_path
|
|
|
|
|
|
|
|
def initialize(base_url:, base_path:)
|
|
|
|
@base_url = base_url
|
|
|
|
@base_path = base_path
|
|
|
|
end
|
|
|
|
|
|
|
|
def delete(path)
|
|
|
|
return unless exists?(path)
|
2024-05-06 07:47:53 +00:00
|
|
|
File.delete("#{base_path}#{path}")
|
2024-05-03 03:04:43 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def exists?(path)
|
2024-05-06 07:47:53 +00:00
|
|
|
File.exist?("#{base_path}#{path}")
|
2024-05-03 03:04:43 +00:00
|
|
|
end
|
|
|
|
|
2024-10-13 06:04:55 +00:00
|
|
|
def get(path, &)
|
|
|
|
File.open("#{base_path}#{path}", "r", binmode: true, &)
|
2024-05-03 03:04:43 +00:00
|
|
|
end
|
|
|
|
|
2024-05-06 07:47:53 +00:00
|
|
|
def put(path, io)
|
|
|
|
temp = "#{base_path}#{path}-#{SecureRandom.uuid}.tmp"
|
|
|
|
|
|
|
|
FileUtils.mkdir_p(File.dirname(temp))
|
|
|
|
io.rewind
|
|
|
|
bytes_copied = IO.copy_stream(io, temp)
|
|
|
|
raise("store failed: #{bytes_copied}/#{io.size} bytes copied") if bytes_copied != io.size
|
|
|
|
|
|
|
|
FileUtils.chmod(DEFAULT_PERMISSIONS, temp)
|
|
|
|
File.rename(temp, "#{base_path}#{path}")
|
|
|
|
rescue StandardError => e
|
|
|
|
FileUtils.rm_f(temp)
|
|
|
|
raise(e)
|
|
|
|
ensure
|
|
|
|
FileUtils.rm_f(temp) if temp
|
2024-05-03 03:04:43 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def upload(path, body)
|
|
|
|
put(path, body)
|
2024-05-06 07:47:53 +00:00
|
|
|
"#{base_url}#{path}"
|
2024-05-03 03:04:43 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def url_for(entry)
|
2024-05-06 07:47:53 +00:00
|
|
|
"#{base_url}#{entry.path}"
|
2024-05-03 03:04:43 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|