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