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
9import os
10import shutil
11import tempfile
12import time
13
14from dex.utils.Exceptions import Error
15
16
17class 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(
35                self.path))
36            return
37
38        exception = AssertionError('should never be raised')
39        for _ in range(100):
40            try:
41                shutil.rmtree(self.path)
42                return
43            except OSError as e:
44                exception = e
45                time.sleep(0.1)
46        raise Error(exception)
47