mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-02 00:29:37 +08:00
Byte-fit KB upload filenames and folder segments to NAME_MAX, and share fit_filename_bytes with attachment/reading stores.
36 lines
1.3 KiB
Python
36 lines
1.3 KiB
Python
"""Portable filename normalization for stored user attachments.
|
|
|
|
A single path component holds at most 255 bytes on ext4 (the filesystem
|
|
behind the official Docker deployment): a longer name makes ``open`` or
|
|
``mkdir`` fail with ``[Errno 36] File name too long``. ``fit_filename_bytes``
|
|
is the one owner of that limit.
|
|
"""
|
|
|
|
import re
|
|
|
|
_UNSAFE_CHARS = re.compile(r'[<>:"/\\|?*]')
|
|
_CONTROL_CHARS = re.compile(r"[\x00-\x1f\x7f]")
|
|
|
|
NAME_MAX_BYTES = 255
|
|
|
|
|
|
def safe_filename(name: str) -> str:
|
|
"""Replace unsafe path / control characters; ``.`` / ``..`` become empty."""
|
|
cleaned = _CONTROL_CHARS.sub("", _UNSAFE_CHARS.sub("_", name or "")).strip().strip(".")
|
|
return cleaned
|
|
|
|
|
|
def fit_filename_bytes(name: str, *, max_bytes: int = NAME_MAX_BYTES, suffix: str = "") -> str:
|
|
"""Trim the stem of *name* so it fits in *max_bytes* UTF-8 bytes.
|
|
|
|
*suffix* (the extension the caller already matched, e.g. ``.docling.json``)
|
|
is preserved verbatim and in full; only the stem is cut, and never in the
|
|
middle of a multi-byte character. Names already within the limit come
|
|
back unchanged.
|
|
"""
|
|
if len(name.encode("utf-8")) <= max_bytes:
|
|
return name
|
|
stem = name[: len(name) - len(suffix)] if suffix else name
|
|
room = max_bytes - len(suffix.encode("utf-8"))
|
|
return stem.encode("utf-8")[: max(room, 0)].decode("utf-8", errors="ignore") + suffix
|