-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfs_ops.py
More file actions
357 lines (321 loc) · 13.9 KB
/
fs_ops.py
File metadata and controls
357 lines (321 loc) · 13.9 KB
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
from __future__ import annotations
import csv
import logging
import os
import shutil
from datetime import datetime
from pathlib import Path
from typing import Any, Callable
from models_core import RenameMove, UndoPlan
def touch_destination_now(path: Path) -> None:
os.utime(path, None)
def build_moves(
records: list[Any],
source_folder: Path,
target_folder: Path,
archive_folder: Path | None,
stamp: str,
) -> list[RenameMove]:
moves: list[RenameMove] = []
same_folder = source_folder.resolve() == target_folder.resolve()
for index, record in enumerate(records, start=1):
record_target_folder = getattr(record, "output_folder", None)
destination_folder = record_target_folder if isinstance(record_target_folder, Path) else target_folder
destination = destination_folder / record.filename
if record.path.parent.resolve() == destination.parent.resolve() and record.path.name == destination.name:
continue
if same_folder:
temp = source_folder / f"__tmp_rename_{stamp}_{index:04d}{record.path.suffix.lower()}"
moves.append(RenameMove(record.path, temp, destination, record, "rename"))
else:
moves.append(RenameMove(record.path, None, destination, record, "copy"))
if archive_folder is not None:
archive_path = getattr(record, "archive_source_path", None)
if not isinstance(archive_path, Path):
archive_path = archive_folder / record.path.name
moves.append(RenameMove(record.path, None, archive_path, record, "move"))
return moves
def validate_move_collisions(moves: list[RenameMove]) -> list[str]:
errors: list[str] = []
source_paths = {move.source.resolve() for move in moves}
seen_destinations: set[str] = set()
for move in moves:
if move.operation != "delete":
destination_key = str(move.destination.resolve()).lower()
if destination_key in seen_destinations:
errors.append(f"duplicate-destination:{move.destination.name}")
continue
seen_destinations.add(destination_key)
if move.destination.exists() and (move.operation != "rename" or move.destination.resolve() not in source_paths):
errors.append(f"destination-exists:{move.destination.name}")
if move.temp is not None and move.temp.exists() and move.temp.resolve() not in source_paths:
errors.append(f"temp-exists:{move.temp.name}")
return errors
def rollback_moves(moves: list[RenameMove], stage2_done: list[RenameMove]) -> None:
for move in reversed(stage2_done):
if move.destination.exists():
os.replace(move.destination, move.source)
moved_to_stage2 = {move.destination for move in stage2_done}
for move in moves:
if move.destination in moved_to_stage2:
continue
if move.temp is not None and move.temp.exists():
os.replace(move.temp, move.source)
def rollback_executed_chunks(chunks: list[list[RenameMove]]) -> None:
for chunk in reversed(chunks):
if not chunk:
continue
operation = chunk[0].operation
if operation == "copy":
for move in reversed(chunk):
if move.destination.exists():
move.destination.unlink()
continue
if operation == "move":
for move in reversed(chunk):
if move.destination.exists():
move.source.parent.mkdir(parents=True, exist_ok=True)
shutil.move(str(move.destination), str(move.source))
continue
if operation == "delete":
for move in reversed(chunk):
if move.temp is not None and move.temp.exists():
move.source.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(move.temp, move.source)
move.temp.unlink()
continue
if operation == "rename":
for move in reversed(chunk):
if move.destination.exists():
os.replace(move.destination, move.source)
def execute_moves(moves: list[RenameMove]) -> list[str]:
if not moves:
return []
operations = {move.operation for move in moves}
if len(operations) > 1:
completed_chunks: list[list[RenameMove]] = []
rename_like = [move for move in moves if move.operation == "rename"]
copy_like = [move for move in moves if move.operation == "copy"]
move_like = [move for move in moves if move.operation == "move"]
delete_like = [move for move in moves if move.operation == "delete"]
for chunk in (rename_like, copy_like, move_like, delete_like):
if not chunk:
continue
errors = execute_moves(chunk)
if errors:
rollback_executed_chunks(completed_chunks)
return errors
completed_chunks.append(chunk)
return []
operation = next(iter(operations))
if operation == "move":
validation_errors = validate_move_collisions(moves)
if validation_errors:
return validation_errors
moved: list[RenameMove] = []
try:
for move in moves:
move.destination.parent.mkdir(parents=True, exist_ok=True)
shutil.move(str(move.source), str(move.destination))
moved.append(move)
except Exception as exc:
for item in reversed(moved):
if item.destination.exists():
shutil.move(str(item.destination), str(item.source))
return [f"move:{move.source.name}: {exc}"]
return []
if operation == "copy":
validation_errors = validate_move_collisions(moves)
if validation_errors:
return validation_errors
created: list[Path] = []
try:
for move in moves:
move.destination.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(move.source, move.destination)
touch_destination_now(move.destination)
created.append(move.destination)
except Exception as exc:
for path in reversed(created):
if path.exists():
path.unlink()
return [f"copy:{move.source.name}: {exc}"]
return []
if operation == "delete":
validation_errors = validate_move_collisions(moves)
if validation_errors:
return validation_errors
backed_up: list[RenameMove] = []
deleted: list[RenameMove] = []
try:
for move in moves:
if move.temp is None:
return [f"delete-temp-missing:{move.source.name}"]
move.temp.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(move.source, move.temp)
backed_up.append(move)
except Exception as exc:
for item in reversed(backed_up):
if item.temp is not None and item.temp.exists():
item.temp.unlink()
return [f"delete-backup:{move.source.name}: {exc}"]
try:
for move in moves:
if move.source.exists():
move.source.unlink()
deleted.append(move)
except Exception as exc:
for item in reversed(deleted):
if item.temp is not None and item.temp.exists():
shutil.copy2(item.temp, item.source)
for item in reversed(backed_up):
if item.temp is not None and item.temp.exists():
item.temp.unlink()
return [f"delete:{move.source.name}: {exc}"]
cleanup_errors: list[str] = []
for move in reversed(backed_up):
if move.temp is None or not move.temp.exists():
continue
try:
move.temp.unlink()
except Exception as exc:
cleanup_errors.append(f"delete-cleanup:{move.temp.name}: {exc}")
if cleanup_errors:
return cleanup_errors
return []
errors: list[str] = []
stage1_done: list[RenameMove] = []
stage2_done: list[RenameMove] = []
validation_errors = validate_move_collisions(moves)
if validation_errors:
return validation_errors
try:
for move in moves:
os.replace(move.source, move.temp)
stage1_done.append(move)
except Exception as exc:
errors.append(f"stage1:{move.source.name}: {exc}")
for item in reversed(stage1_done):
if item.temp.exists():
os.replace(item.temp, item.source)
return errors
try:
for move in moves:
os.replace(move.temp, move.destination)
touch_destination_now(move.destination)
stage2_done.append(move)
except Exception as exc:
errors.append(f"stage2:{move.source.name}: {exc}")
rollback_moves(moves, stage2_done)
return errors
return errors
def build_undo_plan(report_path: Path, folder_hint: Path | None = None) -> UndoPlan:
folder = folder_hint if folder_hint and folder_hint.exists() else report_path.parent
moves: list[RenameMove] = []
stamp = datetime.now().strftime("%Y%m%d_%H%M%S")
total_rows = 0
with report_path.open("r", newline="", encoding="utf-8-sig") as handle:
reader = csv.DictReader(handle, delimiter=";")
required = {"source_name", "target_name", "mode", "execution_status"}
if not required.issubset(set(reader.fieldnames or [])):
missing = ", ".join(sorted(required - set(reader.fieldnames or [])))
raise ValueError(f"Brak kolumn w logu: {missing}")
for index, row in enumerate(reader, start=1):
total_rows += 1
if (row.get("mode") or "").strip().lower() != "apply":
continue
execution_status = (row.get("execution_status") or "").strip().lower()
source_name = row.get("source_name") or ""
target_name = row.get("target_name") or ""
if not source_name or not target_name or source_name == target_name:
continue
source_folder = Path(row.get("source_folder") or folder)
target_folder = Path(row.get("target_folder") or folder)
operation = (row.get("operation") or "rename").strip().lower()
if operation == "copy":
expected_status = "copied"
elif operation == "move":
expected_status = "moved"
elif operation == "copy+archive":
expected_status = "copied+archived"
else:
expected_status = "renamed"
if execution_status != expected_status:
continue
current = target_folder / target_name
destination = source_folder / source_name
suffix = destination.suffix.lower() or current.suffix.lower() or ".tmp"
if operation == "copy":
temp = target_folder / f"__tmp_undo_delete_{stamp}_{index:04d}{suffix}"
moves.append(RenameMove(current, temp, destination, None, "delete"))
elif operation == "copy+archive":
archive_source_name = row.get("archive_source_name") or ""
archive_source_folder = row.get("archive_source_folder") or ""
if archive_source_name and archive_source_folder:
archived_current = Path(archive_source_folder) / archive_source_name
moves.append(RenameMove(archived_current, None, destination, None, "move"))
temp = target_folder / f"__tmp_undo_delete_{stamp}_{index:04d}{suffix}"
moves.append(RenameMove(current, temp, destination, None, "delete"))
else:
temp = target_folder / f"__tmp_undo_{stamp}_{index:04d}{suffix}"
moves.append(RenameMove(current, temp, destination, None, "rename"))
return UndoPlan(folder=folder, moves=moves, total_rows=total_rows)
def execute_undo(
report_path: Path,
folder_hint: Path | None = None,
*,
log_error: Callable[[str], None],
emit_lines: Callable[[list[str], int], None],
) -> int:
try:
plan = build_undo_plan(report_path, folder_hint)
except Exception as exc:
log_error(f"Nie mozna odczytac logu undo: {exc}")
return 2
if not plan.moves:
emit_lines(
[
f"UNDO_REPORT={report_path}",
f"UNDO_FOLDER={plan.folder}",
"UNDO_MOVES=0",
"UNDO_ERRORS=0",
],
logging.INFO,
)
return 0
missing = [move.source.name for move in plan.moves if not move.source.exists()]
if missing:
emit_lines(
[
f"UNDO_REPORT={report_path}",
f"UNDO_FOLDER={plan.folder}",
f"UNDO_MOVES={len(plan.moves)}",
f"UNDO_ERRORS={len(missing)}",
"---ERRORS---",
],
logging.INFO,
)
emit_lines([f"missing-current-file:{name}" for name in missing[:20]], logging.ERROR)
return 1
errors = execute_moves(plan.moves)
completed = len(plan.moves) if not errors else 0
deleted = sum(1 for move in plan.moves if move.operation == "delete") if not errors else 0
renamed = sum(1 for move in plan.moves if move.operation == "rename") if not errors else 0
emit_lines(
[
f"UNDO_REPORT={report_path}",
f"UNDO_FOLDER={plan.folder}",
f"UNDO_TOTAL_ROWS={plan.total_rows}",
f"UNDO_MOVES={len(plan.moves)}",
f"UNDO_DONE={completed}",
f"UNDO_RENAMED={renamed}",
f"UNDO_DELETED={deleted}",
f"UNDO_ERRORS={len(errors)}",
],
logging.INFO,
)
if errors:
emit_lines(["---ERRORS---"], logging.INFO)
emit_lines(errors[:20], logging.ERROR)
return 1
return 0