| 1 |
# DExTer : Debugging Experience Tester |
| 2 |
# ~~~~~~ ~ ~~ ~ ~~ |
| 3 |
# |
| 4 |
# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 5 |
# See https://llvm.org/LICENSE.txt for license information. |
| 6 |
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 7 |
"""Create/set a temporary working directory for some operations.""" |
| 8 |
|
| 9 |
import os |
| 10 |
import shutil |
| 11 |
import tempfile |
| 12 |
import time |
| 13 |
|
| 14 |
from dex.utils.Exceptions import Error |
| 15 |
|
| 16 |
|
| 17 |
class WorkingDirectory(object): |
| 18 |
def __init__(self, context, *args, **kwargs): |
| 19 |
self.context = context |
| 20 |
self.orig_cwd = os.getcwd() |
| 21 |
|
| 22 |
dir_ = kwargs.get("dir", None) |
| 23 |
if dir_ and not os.path.isdir(dir_): |
| 24 |
os.makedirs(dir_, exist_ok=True) |
| 25 |
self.path = tempfile.mkdtemp(*args, **kwargs) |
| 26 |
|
| 27 |
def __enter__(self): |
| 28 |
os.chdir(self.path) |
| 29 |
return self |
| 30 |
|
| 31 |
def __exit__(self, *args): |
| 32 |
os.chdir(self.orig_cwd) |
| 33 |
if self.context.options.save_temps: |
| 34 |
self.context.o.blue('"{}" left in place [--save-temps]\n'.format(self.path)) |
| 35 |
return |
| 36 |
|
| 37 |
for _ in range(100): |
| 38 |
try: |
| 39 |
shutil.rmtree(self.path) |
| 40 |
return |
| 41 |
except OSError: |
| 42 |
time.sleep(0.1) |
| 43 |
|
| 44 |
self.context.logger.warning( |
| 45 |
f'"{self.path}" left in place (couldn\'t delete)', enable_prefix=True |
| 46 |
) |
| 47 |
return |