fix(naming): truncate filenames by UTF-8 bytes (#1703)

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **Bug Fixes**
* Filename length limits now account for UTF-8 bytes, so names with
multibyte characters stay within the configured limit without ending in
a partial character.
* Long Unicode author and title names now produce library paths that
stay within the supported byte limit, retain the `.epub` extension, and
can still be created and read.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
This commit is contained in:
Ihar Hrachyshka authored and GitHub committed 2026-11-13 00:46:00 -05:00
1 parent a5fe803b8f
commit 44e1c6a660
2 files changed
+31 -2

No files matched your search

+3 -2
View File
@@ -57,11 +57,12 @@ def _sanitize(name: str | None, max_length: int = 245) -> str:
sanitized = INVALID_CHARS.sub("_", name)
sanitized = re.sub(r"^[\s.]+|[\s.]+$", "", sanitized) # Strip whitespace and dots
sanitized = re.sub(r"_+", "_", sanitized) # Collapse underscores
return sanitized[:max_length]
# Filesystem component limits count bytes; discard any partial final character.
return sanitized.encode("utf-8")[:max_length].decode("utf-8", errors="ignore")
def sanitize_filename(name: str | None, max_length: int = 245) -> str:
"""Sanitize a string for use as a filename or path component."""
"""Sanitize a filename or path component within a UTF-8 byte limit."""
return _sanitize(name, max_length)
+28
View File
@@ -517,6 +517,21 @@ class TestSanitizeFilename:
assert sanitize_filename("") == ""
assert sanitize_filename(None) == ""
@pytest.mark.parametrize(
"name,max_length,expected",
[
("aéz", 2, "a"),
("aéz", 3, "aé"),
("a界z", 3, "a"),
("a界z", 4, "a界"),
("a📚z", 4, "a"),
("a📚z", 5, "a📚"),
("é", 1, ""),
],
)
def test_unicode_byte_limit_keeps_whole_characters(self, name, max_length, expected):
assert sanitize_filename(name, max_length=max_length) == expected
class TestFormatSeriesPosition:
"""Tests for series position formatting."""
@@ -780,3 +795,16 @@ class TestFilesystemOperations:
assert path is not None
# Title component should be truncated
assert len(path.stem) < 250
@pytest.mark.parametrize("character", ["Ж", "界", "📚"])
def test_long_unicode_names_can_be_saved(self, temp_library, character):
metadata = {"Author": character * 200, "Title": character * 200}
path = build_library_path(str(temp_library), "{Author}/{Title}", metadata, extension="epub")
assert len(path.parent.name.encode("utf-8")) <= 245
assert len(path.stem.encode("utf-8")) <= 245
assert path.suffix == ".epub"
path.parent.mkdir(parents=True)
path.write_bytes(b"book content")
assert path.read_bytes() == b"book content"