Skip to content

Bulk asynchronous downloader for multiple file hosts

fix: do not overwrite files while sorting (#99)

NTFSvolumeb6ffb422c8d5
diff --git a/cyberdrop_dl/utils/sorting.py b/cyberdrop_dl/utils/sorting.py
index 0ce31b103..708fcebca 100644
--- a/cyberdrop_dl/utils/sorting.py
+++ b/cyberdrop_dl/utils/sorting.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import asyncio
import dataclasses
import datetime
+import hashlib
import logging
import shutil
from pathlib import Path
@@ -27,11 +28,6 @@ if TYPE_CHECKING:
logger = logging.getLogger(__name__)
-async def _get_modified_date(file: Path) -> datetime.datetime:
- stat = await asyncio.to_thread(file.stat)
- return datetime.datetime.fromtimestamp(stat.st_mtime).replace(microsecond=0)
-
-
@dataclasses.dataclass(slots=True, frozen=True)
class Sorter:
live_manager: LiveManager
@@ -220,6 +216,21 @@ def _get_files(directory: Path) -> tuple[Path, tuple[Path, ...]]:
return directory, tuple(path for path in directory.resolve().rglob("*") if path.is_file())
+def _move_but_not_overwrite(source: Path, dest: Path) -> Path:
+ if dest.exists():
+ raise FileExistsError(dest)
+ _ = shutil.move(source, dest)
+ return dest
+
+
+def _have_same_content(source: Path, dest: Path) -> bool:
+ if source.stat().st_size != dest.stat().st_size:
+ return False
+
+ with source.open("rb") as f_in, dest.open("rb") as f_out:
+ return hashlib.file_digest(f_in, "md5").hexdigest() == hashlib.file_digest(f_out, "md5").hexdigest()
+
+
def _move_file(
source: Path,
dest: Path,
@@ -236,46 +247,43 @@ def _move_file(
dest_parent.mkdir(parents=True, exist_ok=True)
try:
- _ = shutil.move(source, dest)
- except FileExistsError:
- dest_stem = dest.stem
- source_size = source.stat().st_size
- for auto_index in range(1, max_retries + 1):
- if source_size == dest.stat().st_size:
- source.unlink()
- return dest
-
- new_filename = f"{dest_stem}{incrementer_format.format(i=auto_index)}{dest.suffix}"
- logger.warning(
- "Found name collision when moving '{}' to '{}'. Retring with '{}'",
- source,
- dest,
- dest := dest_parent / new_filename,
- )
+ try:
+ return _move_but_not_overwrite(source, dest)
+ except FileExistsError:
+ dest_stem = dest.stem
+ for auto_index in range(1, max_retries + 1):
+ if _have_same_content(source, dest):
+ source.unlink()
+ return dest
+
+ new_filename = f"{dest_stem}{incrementer_format.format(i=auto_index)}{dest.suffix}"
+ logger.warning(
+ "Found name collision when moving '{}' to '{}'. Retring with '{}'",
+ source,
+ dest,
+ dest := dest_parent / new_filename,
+ )
+
+ try:
+ return _move_but_not_overwrite(source, dest)
+ except FileExistsError:
+ continue
- try:
- _ = shutil.move(source, dest)
- except FileExistsError:
- continue
- except OSError:
- logger.exception("Unable to move '{}'", source)
- return
else:
- return dest
- else:
- logger.error("Unable to move '{}'. Giving up after {} attempts", source, max_retries)
- return
-
+ logger.error("Unable to move '{}'. Giving up after {} attempts", source, max_retries)
+ return
except OSError:
logger.exception("Unable to move '{}'", source)
return
- else:
- return dest
-
async def _try_probe(kind: str, file: Path) -> ffmpeg.FFprobeResult | None:
try:
return await ffmpeg.probe(file)
except (RuntimeError, CalledProcessError, OSError):
logger.exception(f"Unable to get {kind} properties of '{file}'")
+
+
+async def _get_modified_date(file: Path) -> datetime.datetime:
+ stat = await asyncio.to_thread(file.stat)
+ return datetime.datetime.fromtimestamp(stat.st_mtime).replace(microsecond=0)
diff --git a/tests/test_sorter.py b/tests/test_sorter.py
new file mode 100644
index 000000000..f16ca8598
--- /dev/null
+++ b/tests/test_sorter.py
@@ -0,0 +1,119 @@
+import shutil
+from pathlib import Path
+
+import pytest
+
+from cyberdrop_dl.utils.sorting import _have_same_content, _move_file
+
+
+class TestHaveSameContent:
+ def test_same_file_returns_true(self, tmp_path: Path) -> None:
+ foo = tmp_path / "foo.bin"
+ foo.write_bytes(b"12345")
+ assert _have_same_content(foo, foo)
+
+ def test_same_content_same_size_returns_true(self, tmp_path: Path) -> None:
+ foo, bar = tmp_path / "foo.bin", tmp_path / "bar.bin"
+ data = b"0" * 1_000
+ foo.write_bytes(data)
+ bar.write_bytes(data)
+ assert _have_same_content(foo, bar)
+
+ def test_different_size_returns_false(self, tmp_path: Path) -> None:
+ foo, bar = tmp_path / "foo.bin", tmp_path / "bar.bin"
+ foo.write_bytes(b"x")
+ bar.write_bytes(b"x" * 10)
+ assert not _have_same_content(foo, bar)
+
+ def test_same_size_different_content_returns_false(self, tmp_path: Path) -> None:
+ foo, bar = tmp_path / "foo.bin", tmp_path / "bar.bin"
+ foo.write_bytes(b"\x00" * 512)
+ bar.write_bytes(b"\xff" * 512)
+ assert not _have_same_content(foo, bar)
+
+ def test_empty_files_return_true(self, tmp_path: Path) -> None:
+ foo, bar = tmp_path / "foo.bin", tmp_path / "bar.bin"
+ foo.touch()
+ bar.touch()
+ assert _have_same_content(foo, bar)
+
+ def test_large_files_same_content_return_true(self, tmp_path: Path) -> None:
+ foo, bar = tmp_path / "foo.bin", tmp_path / "bar.bin"
+ data_10MB = b"A" * 1024 * 1024 * 10
+ foo.write_bytes(data_10MB)
+ bar.write_bytes(data_10MB)
+ assert _have_same_content(foo, bar)
+
+
+class TestMoveFile:
+ def test_same_file_returns_immediately(self, tmp_path: Path) -> None:
+ foo = tmp_path / "foo.txt"
+ foo.write_text("x")
+ assert _move_file(foo, foo) == foo
+ assert foo.exists()
+
+ def test_simple_move(self, tmp_path: Path) -> None:
+ src = tmp_path / "foo.txt"
+ src.write_text("data")
+ dst = tmp_path / "sub" / "bar.txt"
+ out = _move_file(src, dst)
+ assert out == dst
+ assert not src.exists()
+ assert dst.read_text() == "data"
+
+ def test_name_collision_same_size_diferent_content(self, tmp_path: Path) -> None:
+ src = tmp_path / "foo.txt"
+ src.write_text("abc")
+ dst = tmp_path / "bar.txt"
+ dst.write_text("123")
+ out = _move_file(src, dst)
+
+ assert out
+ assert out != dst
+ assert not src.exists()
+ assert dst.read_text() == "123"
+ assert out.read_text() == "abc"
+
+ def test_name_collision_different_size(self, tmp_path: Path) -> None:
+ src = tmp_path / "foo.jpg"
+ src.write_bytes(b"0" * 100)
+ dst = tmp_path / "bar.jpg"
+ dst.write_bytes(b"1" * 50)
+ out = _move_file(src, dst)
+ assert out
+ assert out == tmp_path / "bar1.jpg"
+ assert not src.exists()
+ assert out.stat().st_size == 100
+
+ def test_custom_incrementer_format(self, tmp_path: Path) -> None:
+ src = tmp_path / "foo.log"
+ src.write_text("a")
+ dest = tmp_path / "bar.log"
+ dest.write_text("x")
+ for i in range(1, 4):
+ (tmp_path / f"bar_{i}.log").write_text("x")
+ out = _move_file(src, dest, incrementer_format="_{i}")
+ assert out == tmp_path / "bar_4.log"
+
+ def test_max_retries_exceeded(self, tmp_path: Path) -> None:
+ src = tmp_path / "foo.txt"
+ src.write_text("x")
+ dest = tmp_path / "bar.txt"
+ dest.touch()
+ for i in range(1, 12):
+ (tmp_path / f"bar{i}.txt").touch()
+
+ assert _move_file(src, dest) is None
+ assert src.exists()
+
+ def test_os_error_during_move_cancels_it(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ src = tmp_path / "foo.txt"
+ src.write_text("x")
+ dst = tmp_path / "bar.txt"
+
+ def boom(*_, **_k):
+ raise OSError
+
+ monkeypatch.setattr(shutil, "move", boom)
+ assert _move_file(src, dst) is None
+ assert src.exists()