brintos

brintos / llvm-project-archived public Read only

0
0
Text · 1.3 KiB · 28bcff7 Raw
48 lines · python
1# DExTer : Debugging Experience Tester2# ~~~~~~   ~         ~~         ~   ~~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-exception7"""Create/set a temporary working directory for some operations."""8 9import os10import shutil11import tempfile12import time13 14from dex.utils.Exceptions import Error15 16 17class WorkingDirectory(object):18    def __init__(self, context, *args, **kwargs):19        self.context = context20        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 self30 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            return36 37        for _ in range(100):38            try:39                shutil.rmtree(self.path)40                return41            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=True46        )47        return48