Helper object to manage temp directory during testing. Automatically removes the directory when it went out of scope.
| 37 | |
| 38 | |
| 39 | class TempDirectory: |
| 40 | """Helper object to manage temp directory during testing. |
| 41 | |
| 42 | Automatically removes the directory when it went out of scope. |
| 43 | """ |
| 44 | |
| 45 | # When True, all TempDirectory are *NOT* deleted and instead live inside a predicable directory |
| 46 | # tree. |
| 47 | _KEEP_FOR_DEBUG = False |
| 48 | |
| 49 | # In debug mode, each tempdir is named after the sequence |
| 50 | _NUM_TEMPDIR_CREATED = 0 |
| 51 | _NUM_TEMPDIR_CREATED_LOCK = threading.Lock() |
| 52 | |
| 53 | @classmethod |
| 54 | def _increment_num_tempdir_created(cls): |
| 55 | with cls._NUM_TEMPDIR_CREATED_LOCK: |
| 56 | to_return = cls._NUM_TEMPDIR_CREATED |
| 57 | cls._NUM_TEMPDIR_CREATED += 1 |
| 58 | |
| 59 | return to_return |
| 60 | |
| 61 | _DEBUG_PARENT_DIR = None |
| 62 | |
| 63 | @classmethod |
| 64 | def _get_debug_parent_dir(cls): |
| 65 | if cls._DEBUG_PARENT_DIR is None: |
| 66 | all_parents = f"{tempfile.gettempdir()}/tvm-debug-mode-tempdirs" |
| 67 | if not os.path.isdir(all_parents): |
| 68 | os.makedirs(all_parents) |
| 69 | cls._DEBUG_PARENT_DIR = tempfile.mkdtemp( |
| 70 | prefix=datetime.datetime.now().strftime("%Y-%m-%dT%H-%M-%S___"), dir=all_parents |
| 71 | ) |
| 72 | return cls._DEBUG_PARENT_DIR |
| 73 | |
| 74 | TEMPDIRS = set() |
| 75 | |
| 76 | @classmethod |
| 77 | def remove_tempdirs(cls): |
| 78 | temp_dirs = getattr(cls, "TEMPDIRS", None) |
| 79 | if temp_dirs is None: |
| 80 | return |
| 81 | |
| 82 | for path in temp_dirs: |
| 83 | shutil.rmtree(path, ignore_errors=True) |
| 84 | |
| 85 | cls.TEMPDIRS = None |
| 86 | |
| 87 | @classmethod |
| 88 | @contextlib.contextmanager |
| 89 | def set_keep_for_debug(cls, set_to=True): |
| 90 | """Keep temporary directories past program exit for debugging.""" |
| 91 | old_keep_for_debug = cls._KEEP_FOR_DEBUG |
| 92 | try: |
| 93 | cls._KEEP_FOR_DEBUG = set_to |
| 94 | yield |
| 95 | finally: |
| 96 | cls._KEEP_FOR_DEBUG = old_keep_for_debug |
no outgoing calls
no test coverage detected
searching dependent graphs…