| Total Complexity | 10 |
| Total Lines | 55 |
| Duplicated Lines | 0 % |
| Changes | 0 | ||
| 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 | |||
| 57 |