File size: 1,271 Bytes
c857fe4 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
import os
import shutil
class SafeExecutor:
def __init__(self, paths_to_cleanup):
self.paths_to_cleanup = paths_to_cleanup
self.original_state = {}
def __enter__(self):
for path in self.paths_to_cleanup:
if os.path.exists(path):
self.original_state[path] = os.listdir(path)
else:
self.original_state[path] = None
def __exit__(self, exc_type, exc_value, traceback):
if exc_type is not None:
print("An error occurred, reverting changes...")
for path in self.paths_to_cleanup:
if self.original_state[path] is None:
if os.path.exists(path):
shutil.rmtree(path)
else:
current_files = os.listdir(path)
for file in current_files:
if file not in self.original_state[path]:
file_path = os.path.join(path, file)
if os.path.isfile(file_path):
os.remove(file_path)
else:
shutil.rmtree(file_path)
return False # Propagate the exception
return True
|