diff --git a/deeptutor/reading/store.py b/deeptutor/reading/store.py index 642228a5a..1927bed07 100644 --- a/deeptutor/reading/store.py +++ b/deeptutor/reading/store.py @@ -1542,6 +1542,9 @@ def _carry_dir(source: Path, target: Path) -> None: shutil.copy2(entry, destination) +_MAX_FILENAME_CHARS = 180 + + def _safe_filename(name: str, *, fallback: str) -> str: """A filesystem-safe basename for the stored original. @@ -1554,7 +1557,15 @@ def _safe_filename(name: str, *, fallback: str) -> str: if os.altsep: base = base.replace(os.altsep, "_") base = base.strip(". ") or Path(fallback).name or "material" - return base[:180] + if len(base) <= _MAX_FILENAME_CHARS: + return base + # Cut the stem, not the extension: the stored original is found again by + # its suffix (a PDF is only re-extracted when the raw file ends in .pdf). + suffix = Path(base).suffix + if len(suffix) > 16: + suffix = "" + stem = base[: len(base) - len(suffix)][: _MAX_FILENAME_CHARS - len(suffix)] + return stem.rstrip(". ") + suffix def _guess_mime(filename: str) -> str: diff --git a/tests/reading/test_safe_filename.py b/tests/reading/test_safe_filename.py new file mode 100644 index 000000000..204d2ea22 --- /dev/null +++ b/tests/reading/test_safe_filename.py @@ -0,0 +1,32 @@ +"""The stored original keeps its extension when a long display name is cut.""" + +from __future__ import annotations + +from deeptutor.reading.store import _safe_filename + + +def test_long_name_keeps_its_extension() -> None: + name = "A" * 300 + ".pdf" + + stored = _safe_filename(name, fallback="material") + + assert stored.endswith(".pdf") + assert len(stored) == 180 + + +def test_cut_does_not_leave_a_trailing_dot_or_space_before_the_extension() -> None: + name = "A" * 175 + " . " + "B" * 50 + ".epub" + + stored = _safe_filename(name, fallback="material") + + assert stored == "A" * 175 + ".epub" + + +def test_short_name_is_unchanged() -> None: + assert _safe_filename("lecture notes.pdf", fallback="material") == "lecture notes.pdf" + + +def test_overlong_suffix_is_cut_like_the_rest_of_the_name() -> None: + name = "paper." + "x" * 300 + + assert _safe_filename(name, fallback="material") == name[:180]