Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 21 additions & 5 deletions src/websitebench/download.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import subprocess
import sysconfig
import tarfile
import tempfile
import time
from importlib import resources
from pathlib import Path
Expand Down Expand Up @@ -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}")
25 changes: 25 additions & 0 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down