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