2017-01-22 06:21:03 +01:00
|
|
|
import os
|
|
|
|
import shutil
|
2017-01-24 09:25:52 +01:00
|
|
|
import sys
|
2017-01-22 06:21:03 +01:00
|
|
|
|
|
|
|
from elodie import constants
|
|
|
|
|
2017-01-22 09:19:44 +01:00
|
|
|
|
2017-01-24 09:25:52 +01:00
|
|
|
def _decode(string, encoding=sys.getfilesystemencoding()):
|
2017-01-08 23:43:01 +01:00
|
|
|
"""Return a utf8 encoded unicode string.
|
|
|
|
|
|
|
|
Python2 and Python3 differ in how they handle strings.
|
|
|
|
So we do a few checks to see if the string is ascii or unicode.
|
|
|
|
Then we decode it if needed.
|
|
|
|
"""
|
2016-12-26 17:20:12 +01:00
|
|
|
if hasattr(string, 'decode'):
|
2017-01-08 23:43:01 +01:00
|
|
|
# If the string is already unicode we return it.
|
|
|
|
try:
|
|
|
|
if isinstance(string, unicode):
|
|
|
|
return string
|
|
|
|
except NameError:
|
|
|
|
pass
|
|
|
|
|
2016-12-26 17:20:12 +01:00
|
|
|
return string.decode(encoding)
|
|
|
|
|
|
|
|
return string
|
|
|
|
|
2017-01-22 09:19:44 +01:00
|
|
|
|
2017-01-22 06:21:03 +01:00
|
|
|
def _copyfile(src, dst):
|
2017-03-30 16:13:34 +02:00
|
|
|
# shutil.copy seems slow, changing to streaming according to
|
|
|
|
# http://stackoverflow.com/questions/22078621/python-how-to-copy-files-fast # noqa
|
|
|
|
# Python 3 hangs using open/write method so we proceed with shutil.copy
|
|
|
|
# and only perform the optimized write for Python 2.
|
2017-01-22 06:21:03 +01:00
|
|
|
if (constants.python_version == 3):
|
2017-03-30 16:13:34 +02:00
|
|
|
# Do not use copy2(), it will have an issue when copying to a
|
|
|
|
# network/mounted drive.
|
|
|
|
# Using copy and manual set_date_from_filename gets the job done.
|
|
|
|
# The calling function is responsible for setting the time.
|
2017-01-22 06:21:03 +01:00
|
|
|
shutil.copy(src, dst)
|
|
|
|
return
|
|
|
|
|
|
|
|
try:
|
|
|
|
O_BINARY = os.O_BINARY
|
|
|
|
except:
|
|
|
|
O_BINARY = 0
|
2016-12-26 17:20:12 +01:00
|
|
|
|
2017-01-22 06:21:03 +01:00
|
|
|
READ_FLAGS = os.O_RDONLY | O_BINARY
|
|
|
|
WRITE_FLAGS = os.O_WRONLY | os.O_CREAT | os.O_TRUNC | O_BINARY
|
|
|
|
TEN_MEGABYTES = 10485760
|
|
|
|
BUFFER_SIZE = min(TEN_MEGABYTES, os.path.getsize(src))
|
2017-01-22 09:19:44 +01:00
|
|
|
|
2017-01-22 06:21:03 +01:00
|
|
|
try:
|
|
|
|
fin = os.open(src, READ_FLAGS)
|
|
|
|
stat = os.fstat(fin)
|
|
|
|
fout = os.open(dst, WRITE_FLAGS, stat.st_mode)
|
|
|
|
for x in iter(lambda: os.read(fin, BUFFER_SIZE), ""):
|
|
|
|
os.write(fout, x)
|
|
|
|
finally:
|
2017-01-22 09:19:44 +01:00
|
|
|
try:
|
|
|
|
os.close(fin)
|
|
|
|
except:
|
|
|
|
pass
|
|
|
|
try:
|
|
|
|
os.close(fout)
|
|
|
|
except:
|
|
|
|
pass
|