• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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
15from dex.utils.Warning import warn
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        for _ in range(100):
39            try:
40                shutil.rmtree(self.path)
41                return
42            except OSError:
43                time.sleep(0.1)
44
45        warn(self.context, '"{}" left in place (couldn\'t delete)\n'.format(self.path))
46        return
47