Completed
Push18b5c1...4a7df2
passed — Build
created

_copyfile()   C

↳ Parent: Project

Complexity

Conditions 7

Duplication

Lines 0
Ratio 0 %

Size

Total Lines 27

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 7
c 1
b 0
f 0
dl 0
loc 27
rs 5.5
1
import os
2
import shutil
3
4
from elodie import constants
5
6
def _decode(string, encoding='utf8'):
7
    """Return a utf8 encoded unicode string.
8
9
    Python2 and Python3 differ in how they handle strings.
10
    So we do a few checks to see if the string is ascii or unicode.
11
    Then we decode it if needed.
12
    """
13
    if hasattr(string, 'decode'):
14
        # If the string is already unicode we return it.
15
        try:
16
            if isinstance(string, unicode):
17
                return string
18
        except NameError:
19
            pass
20
21
        return string.decode(encoding)
22
23
    return string
24
25
def _copyfile(src, dst):
26
    # Python 3 hangs using open/write method
27
    if (constants.python_version == 3):
28
        shutil.copy(src, dst)
29
        return
30
31
    try:
32
        O_BINARY = os.O_BINARY
33
    except:
34
        O_BINARY = 0
35
36
    READ_FLAGS = os.O_RDONLY | O_BINARY
37
    WRITE_FLAGS = os.O_WRONLY | os.O_CREAT | os.O_TRUNC | O_BINARY
38
    TEN_MEGABYTES = 10485760
39
    BUFFER_SIZE = min(TEN_MEGABYTES, os.path.getsize(src))
40
        
41
    try:
42
        fin = os.open(src, READ_FLAGS)
43
        stat = os.fstat(fin)
44
        fout = os.open(dst, WRITE_FLAGS, stat.st_mode)
45
        for x in iter(lambda: os.read(fin, BUFFER_SIZE), ""):
46
            os.write(fout, x)
47
    finally:
48
        try: os.close(fin)
49
        except: pass
50
        try: os.close(fout)
51
        except: pass
52