Passed
Push — master ( e41ba7...8dafba )
by Konstantin
01:57
created

ocrd_utils.os.pushd_popd()   B

Complexity

Conditions 7

Size

Total Lines 20
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 17
dl 0
loc 20
rs 8
c 0
b 0
f 0
cc 7
nop 2
1
"""
2
Operating system functions.
3
"""
4
__all__ = [
5
    'abspath',
6
    'pushd_popd',
7
    'unzip_file_to_dir',
8
]
9
10
from tempfile import TemporaryDirectory
11
import contextlib
12
from os import getcwd, chdir
13
import os.path
14
15
from zipfile import ZipFile
16
17
def abspath(url):
18
    """
19
    Get a full path to a file or file URL
20
21
    See os.abspath
22
    """
23
    if url.startswith('file://'):
24
        url = url[len('file://'):]
25
    return os.path.abspath(url)
26
27
@contextlib.contextmanager
28
def pushd_popd(newcwd=None, tempdir=False):
29
    if newcwd and tempdir:
30
        raise Exception("pushd_popd can accept either newcwd or tempdir, not both")
31
    try:
32
        oldcwd = getcwd()
33
    except FileNotFoundError as e:  # pylint: disable=unused-variable
34
        # This happens when a directory is deleted before the context is exited
35
        oldcwd = '/tmp'
36
    try:
37
        if tempdir:
38
            with TemporaryDirectory() as tempcwd:
39
                chdir(tempcwd)
40
                yield tempcwd
41
        else:
42
            if newcwd:
43
                chdir(newcwd)
44
            yield newcwd
45
    finally:
46
        chdir(oldcwd)
47
48
def unzip_file_to_dir(path_to_zip, output_directory):
49
    """
50
    Extract a ZIP archive to a directory
51
    """
52
    z = ZipFile(path_to_zip, 'r')
53
    z.extractall(output_directory)
54
    z.close()
55
56
57