Commit
·
c857fe4
1
Parent(s):
c3262a7
is keep the changes is anything went wrong
Browse files- safe_executor.py +33 -0
safe_executor.py
ADDED
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import shutil
|
3 |
+
|
4 |
+
class SafeExecutor:
|
5 |
+
def __init__(self, paths_to_cleanup):
|
6 |
+
self.paths_to_cleanup = paths_to_cleanup
|
7 |
+
self.original_state = {}
|
8 |
+
|
9 |
+
def __enter__(self):
|
10 |
+
for path in self.paths_to_cleanup:
|
11 |
+
if os.path.exists(path):
|
12 |
+
self.original_state[path] = os.listdir(path)
|
13 |
+
else:
|
14 |
+
self.original_state[path] = None
|
15 |
+
|
16 |
+
def __exit__(self, exc_type, exc_value, traceback):
|
17 |
+
if exc_type is not None:
|
18 |
+
print("An error occurred, reverting changes...")
|
19 |
+
for path in self.paths_to_cleanup:
|
20 |
+
if self.original_state[path] is None:
|
21 |
+
if os.path.exists(path):
|
22 |
+
shutil.rmtree(path)
|
23 |
+
else:
|
24 |
+
current_files = os.listdir(path)
|
25 |
+
for file in current_files:
|
26 |
+
if file not in self.original_state[path]:
|
27 |
+
file_path = os.path.join(path, file)
|
28 |
+
if os.path.isfile(file_path):
|
29 |
+
os.remove(file_path)
|
30 |
+
else:
|
31 |
+
shutil.rmtree(file_path)
|
32 |
+
return False # Propagate the exception
|
33 |
+
return True
|