diff --git a/src/websitebench/download.py b/src/websitebench/download.py index e865f697..c0508c78 100644 --- a/src/websitebench/download.py +++ b/src/websitebench/download.py @@ -15,6 +15,7 @@ import subprocess import sysconfig import tarfile +import tempfile import time from importlib import resources from pathlib import Path @@ -154,10 +155,25 @@ def install( restore_modes(source, index["tasks"][task]["executables"]) verify_task(source, index["tasks"][task]) destination = output / task - if destination.exists(): - if not force: - raise ValueError(f"{destination} exists; pass --force to replace it") - shutil.rmtree(destination) + if not force and destination.exists(): + raise ValueError(f"{destination} exists; pass --force to replace it") output.mkdir(parents=True, exist_ok=True) - shutil.move(str(source), destination) + with tempfile.TemporaryDirectory( + dir=output, prefix=".websitebench-install-" + ) as tmp: + staging = Path(tmp) + replacement = staging / task + shutil.move(str(source), replacement) + if force and destination.is_dir() and not destination.is_symlink(): + # Keep the backup outside staging so it survives a failed rollback. + backup = staging.with_name(f"{staging.name}.backup") + destination.rename(backup) + try: + replacement.rename(destination) + except OSError: + backup.rename(destination) + raise + shutil.rmtree(backup) + else: + replacement.rename(destination) print(f"OK {task} -> {destination}") diff --git a/tests/test_cli.py b/tests/test_cli.py index 09e3422f..e73109e7 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -141,6 +141,31 @@ def test_failed_download_installs_nothing(self): self.assertIn("error:", err) self.assertEqual(list(self.root.iterdir()), []) + def test_force_restores_installed_task_when_replacement_fails(self): + task = self.output / "sample" + write_task(task) + marker = task / "original.txt" + marker.write_text("Original task.\n") + failure = OSError("cannot install replacement") + rename = os.rename + + def fail_replacement(source, destination): + if Path(destination) == task and not (Path(source) / marker.name).exists(): + raise failure + rename(source, destination) + + with ( + mock.patch.object(cli, "fetch_hub", side_effect=fake_hub), + mock.patch.object(os, "rename", side_effect=fail_replacement), + mock.patch.object(download.shutil, "copytree", side_effect=failure), + ): + code, _, err = run_cli("download", "--output", str(self.output), "--force") + self.assertEqual(code, 1) + self.assertIn(str(failure), err) + self.assertTrue(marker.is_file()) + self.assertEqual(marker.read_text(), "Original task.\n") + self.assertEqual(list(self.output.iterdir()), [task]) + def test_missing_command_is_reported(self): missing = FileNotFoundError(2, "No such file or directory", "harbor") with mock.patch.object(cli, "fetch_hub", side_effect=missing):