Passed
Push — master ( 903ac6...71efa5 )
by Konstantin
02:59 queued 13s
created

ocrd_utils.os.pushd_popd()   A

Complexity

Conditions 3

Size

Total Lines 13
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

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