|
| 1 | +import os |
| 2 | +import platform |
| 3 | +import shutil |
| 4 | +import stat |
| 5 | +import sys |
| 6 | +import tempfile |
| 7 | +import time |
| 8 | +import warnings |
| 9 | +from pathlib import Path |
| 10 | +from threading import Thread |
| 11 | + |
| 12 | + |
| 13 | +class TempDirWarning(UserWarning): |
| 14 | + pass |
| 15 | + |
| 16 | + |
| 17 | +# Python's built-in temporary directory functions are lacking |
| 18 | +# In short, they don't handle removal well, and there's lots of API changes over recent versions. |
| 19 | +# Here we have our own class to deal with it. |
| 20 | +class TempDirectory: |
| 21 | + def __init__(self, path=None, sneak=False): |
| 22 | + self._with_onexc = bool(sys.version_info[:3] >= (3, 12)) |
| 23 | + args = {} |
| 24 | + |
| 25 | + if path: |
| 26 | + args = dict(dir=path) |
| 27 | + elif sneak: |
| 28 | + args = dict(prefix=".choreographer-", dir=Path.home()) |
| 29 | + |
| 30 | + if platform.system() != "Windows": |
| 31 | + self.temp_dir = tempfile.TemporaryDirectory(**args) |
| 32 | + else: # is windows |
| 33 | + vinfo = sys.version_info[:3] |
| 34 | + if vinfo >= (3, 12): |
| 35 | + self.temp_dir = tempfile.TemporaryDirectory( |
| 36 | + delete=False, |
| 37 | + ignore_cleanup_errors=True, |
| 38 | + **args, |
| 39 | + ) |
| 40 | + elif vinfo >= (3, 10): |
| 41 | + self.temp_dir = tempfile.TemporaryDirectory( |
| 42 | + ignore_cleanup_errors=True, |
| 43 | + **args, |
| 44 | + ) |
| 45 | + else: |
| 46 | + self.temp_dir = tempfile.TemporaryDirectory(**args) |
| 47 | + |
| 48 | + self.path = self.temp_dir.name |
| 49 | + self.exists = True |
| 50 | + if self.debug: |
| 51 | + print(f"TEMP DIR NAME: {self._temp_dir_name}", file=sys.stderr) |
| 52 | + |
| 53 | + def delete_manually(self, check_only=False): |
| 54 | + if not os.path.exists(self.path): |
| 55 | + self.exists = False |
| 56 | + if self.debug: |
| 57 | + print( |
| 58 | + "No retry delete manual necessary, path doesn't exist", |
| 59 | + file=sys.stderr, |
| 60 | + ) |
| 61 | + return 0, 0, [] |
| 62 | + n_dirs = 0 |
| 63 | + n_files = 0 |
| 64 | + errors = [] |
| 65 | + for root, dirs, files in os.walk(self.path, topdown=False): |
| 66 | + n_dirs += len(dirs) |
| 67 | + n_files += len(files) |
| 68 | + if not check_only: |
| 69 | + for f in files: |
| 70 | + fp = os.path.join(root, f) |
| 71 | + if self.debug: |
| 72 | + print(f"Removing file: {fp}", file=sys.stderr) |
| 73 | + try: |
| 74 | + os.chmod(fp, stat.S_IWUSR) |
| 75 | + os.remove(fp) |
| 76 | + if self.debug: |
| 77 | + print("Success", file=sys.stderr) |
| 78 | + except BaseException as e: |
| 79 | + errors.append((fp, e)) |
| 80 | + for d in dirs: |
| 81 | + fp = os.path.join(root, d) |
| 82 | + if self.debug: |
| 83 | + print(f"Removing dir: {fp}", file=sys.stderr) |
| 84 | + try: |
| 85 | + os.chmod(fp, stat.S_IWUSR) |
| 86 | + os.rmdir(fp) |
| 87 | + if self.debug: |
| 88 | + print("Success", file=sys.stderr) |
| 89 | + except BaseException as e: |
| 90 | + errors.append((fp, e)) |
| 91 | + |
| 92 | + # clean up directory |
| 93 | + if not check_only: |
| 94 | + try: |
| 95 | + os.chmod(self.path, stat.S_IWUSR) |
| 96 | + os.rmdir(self.path) |
| 97 | + except BaseException as e: |
| 98 | + errors.append((self.path, e)) |
| 99 | + |
| 100 | + if check_only: |
| 101 | + if n_dirs or n_files: |
| 102 | + self.exists = True |
| 103 | + else: |
| 104 | + self.exists = False |
| 105 | + elif errors: |
| 106 | + warnings.warn( |
| 107 | + f"The temporary directory could not be deleted, execution will continue. errors: {errors}", |
| 108 | + TempDirWarning, |
| 109 | + ) |
| 110 | + self.exists = True |
| 111 | + else: |
| 112 | + self.exists = False |
| 113 | + |
| 114 | + return n_dirs, n_files, errors |
| 115 | + |
| 116 | + def clean(self): |
| 117 | + try: |
| 118 | + # no faith in this python implementation, always fails with windows |
| 119 | + # very unstable recently as well, lots new arguments in tempfile package |
| 120 | + self.temp_dir.cleanup() |
| 121 | + self.exists = False |
| 122 | + return |
| 123 | + except BaseException as e: |
| 124 | + if self.debug: |
| 125 | + print( |
| 126 | + f"First tempdir deletion failed: TempDirWarning: {str(e)}", |
| 127 | + file=sys.stderr, |
| 128 | + ) |
| 129 | + |
| 130 | + def remove_readonly(func, path, excinfo): |
| 131 | + try: |
| 132 | + os.chmod(path, stat.S_IWUSR) |
| 133 | + func(path) |
| 134 | + except FileNotFoundError: |
| 135 | + pass |
| 136 | + |
| 137 | + try: |
| 138 | + if self._with_onexc: |
| 139 | + shutil.rmtree(self.path, onexc=remove_readonly) |
| 140 | + else: |
| 141 | + shutil.rmtree(self.path, onerror=remove_readonly) |
| 142 | + self.exists = False |
| 143 | + del self.temp_dir |
| 144 | + return |
| 145 | + except FileNotFoundError: |
| 146 | + pass # it worked! |
| 147 | + except BaseException as e: |
| 148 | + if self.debug: |
| 149 | + print( |
| 150 | + f"Second tmpdir deletion failed (shutil.rmtree): {str(e)}", |
| 151 | + file=sys.stderr, |
| 152 | + ) |
| 153 | + self.delete_manually(check_only=True) |
| 154 | + if not self.exists: |
| 155 | + return |
| 156 | + |
| 157 | + def extra_clean(): |
| 158 | + time.sleep(3) |
| 159 | + self.delete_manually() |
| 160 | + |
| 161 | + t = Thread(target=extra_clean) |
| 162 | + t.run() |
| 163 | + if self.debug: |
| 164 | + print( |
| 165 | + f"Tempfile still exists?: {bool(os.path.exists(str(self.path)))}", |
| 166 | + file=sys.stderr, |
| 167 | + ) |
0 commit comments