From e65408d8c4406cc1e3d301029651704edf32d110 Mon Sep 17 00:00:00 2001 From: kevin9327 <5299031+kevin9327@users.noreply.github.com> Date: Sat, 31 Oct 2026 12:14:46 +0900 Subject: [PATCH] fix(reading): keep the extension when a long material name is cut --- deeptutor/reading/store.py | 13 +++++++++++- tests/reading/test_safe_filename.py | 32 +++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 tests/reading/test_safe_filename.py diff --git a/deeptutor/reading/store.py b/deeptutor/reading/store.py index 1cf741e38..5ea2e1e7d 100644 --- a/deeptutor/reading/store.py +++ b/deeptutor/reading/store.py @@ -1537,6 +1537,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. @@ -1549,7 +1552,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]