Passed
Pull Request — master (#536)
by Konstantin
01:40
created

ocrd_utils.os   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 6
eloc 28
dl 0
loc 47
rs 10
c 0
b 0
f 0

3 Functions

Rating   Name   Duplication   Size   Complexity  
A pushd_popd() 0 13 3
A unzip_file_to_dir() 0 7 1
A abspath() 0 9 2
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