mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-06 05:51:24 +08:00
Merge pull request #2225 from kevin9327/fix/reading-long-name-keeps-extension
fix(reading): keep the extension when a long material name is cut
This commit is contained in:
@@ -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:
|
||||
|
||||
32
tests/reading/test_safe_filename.py
Normal file
32
tests/reading/test_safe_filename.py
Normal file
@@ -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]
|
||||
Reference in New Issue
Block a user