|
6 | 6 | import json |
7 | 7 | import os |
8 | 8 | import re |
| 9 | +import secrets |
9 | 10 | import sys |
10 | 11 | import tempfile |
11 | 12 | from dataclasses import dataclass, replace |
12 | 13 | from datetime import datetime |
13 | 14 | from importlib import resources |
14 | 15 | from pathlib import Path |
15 | | -from shutil import copytree, move, rmtree |
| 16 | +from shutil import copy2, copytree, move, rmtree |
16 | 17 | from typing import Any |
17 | 18 |
|
18 | 19 | from .bridge_client import PROTOCOL_VERSION, BridgeClient |
@@ -459,11 +460,50 @@ def plan_install(mods_dir: Path, now: datetime, *, state_dir: Path) -> InstallPl |
459 | 460 | def other_copy_backups(plan: InstallPlan) -> tuple[tuple[Path, Path], ...]: |
460 | 461 | """Runtime behavior and validation.""" |
461 | 462 | return tuple( |
462 | | - (path, _state_backups_dir(plan) / f"{path.name}.backup-{_stamp(plan)}") |
| 463 | + (path, _free_path(_state_backups_dir(plan) / f"{path.name}.backup-{_stamp(plan)}")) |
463 | 464 | for path in plan.other_copies |
464 | 465 | ) |
465 | 466 |
|
466 | 467 |
|
| 468 | +def _free_path(path: Path) -> Path: |
| 469 | + """Runtime behavior and validation.""" |
| 470 | + candidate, n = path, 2 |
| 471 | + while candidate.exists(): |
| 472 | + candidate = path.with_name(f"{path.name}-{n}") |
| 473 | + n += 1 |
| 474 | + return candidate |
| 475 | + |
| 476 | + |
| 477 | +def _can_remove(path: Path) -> bool: |
| 478 | + """Runtime behavior and validation.""" |
| 479 | + for folder in (path.parent, path): |
| 480 | + probe = folder / f".battlemap-mcp-probe-{secrets.token_hex(8)}" |
| 481 | + try: |
| 482 | + handle = os.open(probe, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) |
| 483 | + except OSError: |
| 484 | + return False |
| 485 | + os.close(handle) |
| 486 | + try: |
| 487 | + os.unlink(probe) |
| 488 | + except OSError: |
| 489 | + return False |
| 490 | + return True |
| 491 | + |
| 492 | + |
| 493 | +def _restore_changed(backup: Path, original: Path) -> None: |
| 494 | + """Runtime behavior and validation.""" |
| 495 | + for source in sorted(backup.rglob("*")): |
| 496 | + target = original / source.relative_to(backup) |
| 497 | + if source.is_dir(): |
| 498 | + target.mkdir(parents=True, exist_ok=True) |
| 499 | + elif not target.is_file() or ( |
| 500 | + hashlib.sha256(target.read_bytes()).digest() |
| 501 | + != hashlib.sha256(source.read_bytes()).digest() |
| 502 | + ): |
| 503 | + target.parent.mkdir(parents=True, exist_ok=True) |
| 504 | + copy2(source, target) |
| 505 | + |
| 506 | + |
467 | 507 | def _state_backups_dir(plan: InstallPlan) -> Path: |
468 | 508 | return plan.records_path.parent / "backups" / _destination_token(plan.destination) |
469 | 509 |
|
@@ -505,19 +545,23 @@ def apply_install( |
505 | 545 | + ", ".join(links) |
506 | 546 | + ". Remove the link itself by hand; the folder it points to is not affected." |
507 | 547 | ) |
508 | | - for _, backup in moved: |
509 | | - if backup.exists(): |
510 | | - raise InstallConflictError(f"Backup already exists: {backup}") |
| 548 | + protected = [str(original) for original, _ in moved if not _can_remove(original)] |
| 549 | + if protected: |
| 550 | + raise InstallConflictError( |
| 551 | + "These bridge copies are in a folder this account cannot change, such as " |
| 552 | + "Program Files: " + ", ".join(protected) + ". Moving them needs an " |
| 553 | + "administrator: delete or move them by hand from an administrator " |
| 554 | + "prompt, or install without move_other_copies. Nothing was changed." |
| 555 | + ) |
511 | 556 |
|
512 | 557 | if plan.destination.exists(): |
513 | 558 | if not force: |
514 | 559 | raise InstallConflictError("Existing bridge requires --force to replace") |
515 | 560 |
|
516 | | - backup_destination = state_backups_dir / ( |
517 | | - f"{plan.destination.name}.backup-{plan.now.strftime('%Y%m%dT%H%M%SZ')}" |
| 561 | + backup_destination = _free_path( |
| 562 | + state_backups_dir |
| 563 | + / f"{plan.destination.name}.backup-{plan.now.strftime('%Y%m%dT%H%M%SZ')}" |
518 | 564 | ) |
519 | | - if backup_destination.exists(): |
520 | | - raise InstallConflictError(f"Backup already exists: {backup_destination}") |
521 | 565 |
|
522 | 566 | # Stage outside mod discovery before moving any existing installation. |
523 | 567 | plan.records_path.parent.mkdir(parents=True, exist_ok=True) |
@@ -573,9 +617,9 @@ def apply_install( |
573 | 617 | rmtree(plan.destination) |
574 | 618 | if destination_removal_started and backup_destination is not None: |
575 | 619 | if installed or not destination_removed or not plan.destination.exists(): |
576 | | - copytree(backup_destination, plan.destination, dirs_exist_ok=True) |
| 620 | + _restore_changed(backup_destination, plan.destination) |
577 | 621 | for original, backup in reversed(restoring): |
578 | | - copytree(backup, original, dirs_exist_ok=True) |
| 622 | + _restore_changed(backup, original) |
579 | 623 | # Include prepared legacy copies whose removal was never reached. |
580 | 624 | # A failed restore above leaves every recovery copy intact. |
581 | 625 | for original, backup in reversed(owned_backups): |
|
0 commit comments