diff --git a/docs/pages/reference/tips.rst b/docs/pages/reference/tips.rst index dd69dbf..96d06b0 100644 --- a/docs/pages/reference/tips.rst +++ b/docs/pages/reference/tips.rst @@ -1,6 +1,98 @@ Tips ------------ +Choose how to handle long names +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +``sanitize_filename``, ``sanitize_filepath``, ``FileNameSanitizer`` and +``FilePathSanitizer`` accept ``length_behavior`` as a :py:class:`~pathvalidate.LengthBehavior` +member or an exact lowercase string: ``"keep"``, ``"trim"``, ``"trim_name"`` or +``"error"``. The default remains ``TRIM``. Length is measured in encoded bytes, +after invalid character replacement and before name handlers and Windows edge +cleanup. These policies leave the existing effective ``max_len`` limits unchanged. + +``TRIM_NAME`` preserves only the final extension (including its dot), as defined +by ``posixpath.splitext``. It keeps the longest stem prefix that fits when encoded +together with that extension, counting any BOM once and preserving code point +boundaries. It can produce an empty stem; it does not preserve grapheme clusters. +Dotfiles such as ``.bashrc`` have no extension and use the existing ``TRIM`` behavior. + +.. code-block:: python + + from pathvalidate import LengthBehavior, ValidationError, sanitize_filename + + print(sanitize_filename("archive.tar.gz", max_len=10, platform="linux", + fs_encoding="utf-8", length_behavior=LengthBehavior.TRIM_NAME)) + print(sanitize_filename("abc.txt", max_len=4, platform="linux", + fs_encoding="utf-8", length_behavior="trim_name")) + try: + sanitize_filename("abc.txt", max_len=3, platform="linux", + fs_encoding="utf-8", length_behavior="trim_name") + except ValidationError as error: + print(error.reason.name) + +.. code-block:: console + + archive.gz + .txt + INVALID_LENGTH + +An extension that cannot fit raises ``INVALID_LENGTH`` without falling back to +``TRIM``. ``ERROR`` raises the same reason immediately when the replaced name is +overlong. Both include the replaced component value, encoded byte count, encoding +and platform. Neither waits for ``validate_after_sanitize``. + +``KEEP`` retains the full length while still applying default name cleanup and +handlers. Final validation remains available and can reject the result: + +.. code-block:: python + + print(sanitize_filename("CON.txt", max_len=3, platform="windows", + fs_encoding="utf-8", length_behavior="keep")) + try: + sanitize_filename("CON.txt", max_len=3, platform="windows", + fs_encoding="utf-8", length_behavior="keep", + validate_after_sanitize=True) + except ValidationError as error: + print(error.reason.name) + +.. code-block:: console + + CON_.txt + INVALID_AFTER_SANITIZE + +Handlers run once in their existing order and may grow or alter the output; +Windows cleanup may remove a trailing dot. The length policy is not reapplied +to handler output. Final validation checks that output when requested. An injected +class validator keeps its original protocol and error priority; ``KEEP`` does not +override its decisions. + +For paths, each ordinary directory and filename component receives the same +policy and budget. The budget is not shared or divided, and drive/UNC and special +NTFS branches retain their existing handling. Combined paths can still exceed +``max_len`` even with ``ERROR``: + +.. code-block:: python + + from pathvalidate import sanitize_filepath + + print(sanitize_filepath("abcdefgh.txt/ijklmnop.log", max_len=8, + platform="linux", fs_encoding="utf-8", normalize=False, + length_behavior="trim_name")) + print(sanitize_filepath("abc/def", max_len=3, platform="linux", + fs_encoding="utf-8", length_behavior="error")) + try: + sanitize_filepath("abc/def", max_len=3, platform="linux", + fs_encoding="utf-8", length_behavior="error", + validate_after_sanitize=True) + except ValidationError as error: + print(error.reason.name) + +.. code-block:: console + + abcd.txt/ijkl.log + abc/def + INVALID_LENGTH + Handle dot directory entries (``.`` and ``..``) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The path components ``.`` (current directory) and ``..`` (parent directory) are reserved names according to the underlying file system specifications: diff --git a/docs/pages/reference/types.rst b/docs/pages/reference/types.rst index 0f76374..dd49d2a 100644 --- a/docs/pages/reference/types.rst +++ b/docs/pages/reference/types.rst @@ -1,6 +1,11 @@ Types --------------- +.. autoclass:: pathvalidate.LengthBehavior + :members: + :undoc-members: + :show-inheritance: + .. autoclass:: pathvalidate.Platform :members: :undoc-members: diff --git a/pathvalidate/__init__.py b/pathvalidate/__init__.py index f1b3d62..0380b7c 100644 --- a/pathvalidate/__init__.py +++ b/pathvalidate/__init__.py @@ -13,7 +13,7 @@ validate_pathtype, validate_unprintable_char, ) -from ._const import Platform +from ._const import LengthBehavior, Platform from ._filename import ( FileNameSanitizer, FileNameValidator, @@ -49,6 +49,7 @@ "__version__", "AbstractSanitizer", "AbstractValidator", + "LengthBehavior", "Platform", "ascii_symbols", "normalize_platform", diff --git a/pathvalidate/_const.py b/pathvalidate/_const.py index 4e8518b..f12c2da 100644 --- a/pathvalidate/_const.py +++ b/pathvalidate/_const.py @@ -24,6 +24,20 @@ ) # Only in root directory +@enum.unique +class LengthBehavior(enum.Enum): + """Length policy applied after character replacement and before name handlers.""" + + #: Keep the full name; final validation can still reject its length. + KEEP = "keep" + #: Truncate the entire name (the default). + TRIM = "trim" + #: Truncate the stem while preserving the final extension. + TRIM_NAME = "trim_name" + #: Raise INVALID_LENGTH if the name exceeds the byte budget. + ERROR = "error" + + @enum.unique class Platform(enum.Enum): """ diff --git a/pathvalidate/_filename.py b/pathvalidate/_filename.py index f2651ed..04c24d9 100644 --- a/pathvalidate/_filename.py +++ b/pathvalidate/_filename.py @@ -2,6 +2,7 @@ .. codeauthor:: Tsuyoshi Hombashi """ +import codecs import itertools import posixpath import re @@ -9,11 +10,11 @@ from collections.abc import Sequence from pathlib import Path, PurePath from re import Pattern -from typing import Final, Optional +from typing import Final, Optional, Union from ._base import AbstractSanitizer, AbstractValidator, BaseFile, BaseValidator from ._common import findall_to_str, is_nt_abspath, to_str, truncate_str, validate_pathtype -from ._const import DEFAULT_MIN_LEN, INVALID_CHAR_ERR_MSG_TMPL, Platform +from ._const import DEFAULT_MIN_LEN, INVALID_CHAR_ERR_MSG_TMPL, LengthBehavior, Platform from ._types import PathType, PlatformType from .error import ErrorAttrKey, ErrorReason, InvalidCharError, ValidationError from .handler import ReservedNameHandler, ValidationErrorHandler @@ -39,7 +40,11 @@ def __init__( additional_reserved_names: Optional[Sequence[str]] = None, validate_after_sanitize: bool = False, validator: Optional[AbstractValidator] = None, + length_behavior: Union[LengthBehavior, str] = LengthBehavior.TRIM, # noqa: FA100 ) -> None: + # Keep runtime annotations compatible with Python 3.9. + self.__length_behavior = LengthBehavior(length_behavior) + self.__default_validator: Optional[FileNameValidator] = None # noqa: FA100 if validator: fname_validator = validator else: @@ -51,6 +56,7 @@ def __init__( additional_reserved_names=additional_reserved_names, platform=platform, ) + self.__default_validator = fname_validator super().__init__( max_len=max_len, @@ -77,10 +83,10 @@ def sanitize(self, value: PathType, replacement_text: str = "") -> PathType: raise sanitized_filename = self._sanitize_regexp.sub(replacement_text, str(value)) - sanitized_filename = truncate_str(sanitized_filename, self._fs_encoding, self.max_len) + sanitized_filename = self.__sanitize_length(sanitized_filename) try: - self._validator.validate(sanitized_filename) + self.__validate_name(sanitized_filename) except ValidationError as e: if e.reason == ErrorReason.RESERVED_NAME: replacement_word = self._reserved_name_handler(e) @@ -116,6 +122,92 @@ def sanitize(self, value: PathType, replacement_text: str = "") -> PathType: return sanitized_filename # type: ignore + def __validate_name(self, value: str) -> None: + try: + self._validator.validate(value) + except ValidationError as e: + if ( + self.__length_behavior == LengthBehavior.KEEP + and self.__default_validator is not None + and e.reason == ErrorReason.INVALID_LENGTH + and e.byte_count is not None + and e.byte_count > self.__default_validator.max_len + ): + # The default validator checks length before name hygiene. KEEP + # still needs those checks, without changing injected validators. + self.__default_validator._validate_name(value) + else: + raise + + def __sanitize_length(self, value: str) -> str: + if self.__length_behavior == LengthBehavior.TRIM: + return truncate_str(value, self._fs_encoding, self.max_len) + + byte_count = len(value.encode(self._fs_encoding)) + if self.__length_behavior == LengthBehavior.KEEP or byte_count <= self.max_len: + return value + + if self.__length_behavior == LengthBehavior.ERROR: + raise self.__length_error(value, byte_count) + + stem, extension = posixpath.splitext(value) + if not extension: + return truncate_str(value, self._fs_encoding, self.max_len) + + encoding = codecs.lookup(self._fs_encoding).name + if encoding in ( + "ascii", + "utf-8", + "utf-8-sig", + "utf-16", + "utf-16-le", + "utf-16-be", + "utf-32", + "utf-32-le", + "utf-32-be", + ): + # These encodings grow monotonically with each code point. Bound + # the search by the byte budget, even for very long input names. + lower, upper = 0, min(len(stem), self.max_len) + while lower < upper: + middle = (lower + upper + 1) // 2 + if len((stem[:middle] + extension).encode(self._fs_encoding)) <= self.max_len: + lower = middle + else: + upper = middle - 1 + candidate = stem[:lower] + extension + if len(candidate.encode(self._fs_encoding)) <= self.max_len: + return candidate + else: + # Stateful and other codecs need not have monotonic byte lengths. + # Measure whole candidates, including any BOM/shift state, and do + # not reject the extension alone before trying longer prefixes. + for length in range(len(stem) - 1, -1, -1): + candidate = stem[:length] + extension + if len(candidate.encode(self._fs_encoding)) <= self.max_len: + return candidate + + raise self.__length_error(value, byte_count, preserve_extension=True) + + def __length_error( + self, value: str, byte_count: int, preserve_extension: bool = False + ) -> ValidationError: + description = ( + "cannot preserve the extension within the byte budget" + if preserve_extension + else "filename is too long" + ) + return ValidationError( + description=( + f"{description}: expected<={self.max_len:d} bytes, actual={byte_count:d} bytes" + ), + reason=ErrorReason.INVALID_LENGTH, + platform=self.platform, + fs_encoding=self._fs_encoding, + byte_count=byte_count, + value=value, + ) + def _get_sanitize_regexp(self) -> Pattern[str]: if self._is_windows(include_universal=True): return _RE_INVALID_WIN_FILENAME @@ -204,6 +296,9 @@ def validate(self, value: PathType) -> None: **err_kwargs, ) + self._validate_name(unicode_filename) + + def _validate_name(self, unicode_filename: str) -> None: self._validate_reserved_keywords(unicode_filename) self.__validate_universal_filename(unicode_filename) @@ -389,6 +484,7 @@ def sanitize_filename( reserved_name_handler: Optional[ValidationErrorHandler] = None, additional_reserved_names: Optional[Sequence[str]] = None, validate_after_sanitize: bool = False, + length_behavior: Union[LengthBehavior, str] = LengthBehavior.TRIM, # noqa: FA100 ) -> PathType: """Make a valid filename from a string. @@ -414,7 +510,7 @@ def sanitize_filename( .. include:: platform.txt max_len: Maximum byte length of the ``filename``. - Truncate the name length if the ``filename`` length exceeds this value. + Applied according to ``length_behavior`` after character replacement. Defaults to ``255``. fs_encoding: Filesystem encoding that is used to calculate the byte length of the filename. @@ -445,6 +541,20 @@ def sanitize_filename( Case insensitive. validate_after_sanitize: Execute validation after sanitization to the file name. + length_behavior: + :py:class:`~pathvalidate.LengthBehavior` or its exact lowercase value. + ``"trim"`` (default) truncates the whole name; ``"keep"`` keeps its + length; ``"error"`` raises if its encoded byte length exceeds ``max_len``. + ``"trim_name"`` keeps the final extension from :py:func:`posixpath.splitext` + and the longest stem prefix that fits, allowing an empty stem. It raises + if no prefix can preserve the extension, and uses ``"trim"`` when there + is no extension. Complete candidates are encoded using ``fs_encoding``. + + This stage runs before reserved/null handlers and Windows edge cleanup. + Handlers can grow the result; use ``validate_after_sanitize=True`` to + check the final value. ``"keep"`` still applies default name cleanup + and does not disable final validation or override an injected validator + on :py:class:`~pathvalidate.FileNameSanitizer`. Returns: Same type as the ``filename`` (str or PathLike object): @@ -452,7 +562,15 @@ def sanitize_filename( Raises: ValueError: - If the ``filename`` is an invalid filename. + If ``length_behavior`` is not a supported enum member or lowercase value, + even when the input is empty. + ValidationError (ErrorReason.INVALID_LENGTH): + If ``"error"`` detects an overlong name after character replacement, + or ``"trim_name"`` cannot preserve its extension within the byte budget. + The error includes the component value, byte count, encoding and platform. + ValidationError (ErrorReason.INVALID_AFTER_SANITIZE): + If requested final validation fails, including overlong ``"keep"`` + results or handler output. Example: :ref:`example-sanitize-filename` @@ -475,4 +593,5 @@ def sanitize_filename( reserved_name_handler=reserved_name_handler, additional_reserved_names=additional_reserved_names, validate_after_sanitize=validate_after_sanitize, + length_behavior=length_behavior, ).sanitize(filename, replacement_text) diff --git a/pathvalidate/_filepath.py b/pathvalidate/_filepath.py index df49ed4..c6eb79b 100644 --- a/pathvalidate/_filepath.py +++ b/pathvalidate/_filepath.py @@ -10,11 +10,17 @@ from collections.abc import Sequence from pathlib import Path, PurePath from re import Pattern -from typing import Final, Optional +from typing import Final, Optional, Union from ._base import AbstractSanitizer, AbstractValidator, BaseFile, BaseValidator from ._common import findall_to_str, is_nt_abspath, to_str, validate_pathtype -from ._const import _NTFS_RESERVED_FILE_NAMES, DEFAULT_MIN_LEN, INVALID_CHAR_ERR_MSG_TMPL, Platform +from ._const import ( + _NTFS_RESERVED_FILE_NAMES, + DEFAULT_MIN_LEN, + INVALID_CHAR_ERR_MSG_TMPL, + LengthBehavior, + Platform, +) from ._filename import FileNameSanitizer, FileNameValidator from ._types import PathType, PlatformType from .error import ErrorAttrKey, ErrorReason, InvalidCharError, ReservedNameError, ValidationError @@ -39,6 +45,7 @@ def __init__( normalize: bool = True, validate_after_sanitize: bool = False, validator: Optional[AbstractValidator] = None, + length_behavior: Union[LengthBehavior, str] = LengthBehavior.TRIM, # noqa: FA100 ) -> None: if validator: fpath_validator = validator @@ -71,6 +78,7 @@ def __init__( additional_reserved_names=additional_reserved_names, platform=self.platform, validate_after_sanitize=validate_after_sanitize, + length_behavior=length_behavior, ) self.__normalize = normalize @@ -417,6 +425,7 @@ def sanitize_filepath( additional_reserved_names: Optional[Sequence[str]] = None, normalize: bool = True, validate_after_sanitize: bool = False, + length_behavior: Union[LengthBehavior, str] = LengthBehavior.TRIM, # noqa: FA100 ) -> PathType: """Make a valid file path from a string. @@ -444,7 +453,8 @@ def sanitize_filepath( .. include:: platform.txt max_len: Maximum byte length of the file path. - Truncate the path if the value length exceeds the `max_len`. + Also passed unchanged to the existing filename sanitizer for each + ordinary component; the budget is not divided among components. If the value is |None| or minus, ``max_len`` will automatically determined by the ``platform``: - ``Linux``: 4096 @@ -482,6 +492,20 @@ def sanitize_filepath( If |True|, normalize the the file path. validate_after_sanitize: Execute validation after sanitization to the file path. + length_behavior: + :py:class:`~pathvalidate.LengthBehavior` or its exact lowercase value, + applied to each ordinary component by :py:func:`~pathvalidate.sanitize_filename`. + ``"trim"`` (default) truncates the whole component; ``"keep"`` keeps + its length; ``"error"`` rejects an overlong component; ``"trim_name"`` + preserves the final extension and the longest stem prefix that fits. + The same policy applies to directory components. An extension that cannot + fit raises; a component without an extension uses ``"trim"``. + + Length is measured after character replacement, before name handlers + and Windows edge cleanup. Handlers can grow the result. Drive/UNC and + special NTFS handling retain their existing bypasses. No policy guarantees + the combined path length: use ``validate_after_sanitize=True`` to check + the final components and path against the existing limits. Returns: Same type as the argument (str or PathLike object): @@ -489,7 +513,16 @@ def sanitize_filepath( Raises: ValueError: - If the ``file_path`` is an invalid file path. + If ``length_behavior`` is not a supported enum member or lowercase value, + even when the input is empty. + ValidationError (ErrorReason.INVALID_LENGTH): + If ``"error"`` rejects an ordinary component after character replacement, + ``"trim_name"`` cannot preserve its extension, or requested final path + validation detects an overlong path. A policy error includes the offending + component value, byte count, encoding and platform. + ValidationError (ErrorReason.INVALID_AFTER_SANITIZE): + If requested final component validation fails, including overlong + ``"keep"`` results or handler output. Example: :ref:`example-sanitize-file-path` @@ -513,4 +546,5 @@ def sanitize_filepath( reserved_name_handler=reserved_name_handler, additional_reserved_names=additional_reserved_names, validate_after_sanitize=validate_after_sanitize, + length_behavior=length_behavior, ).sanitize(file_path, replacement_text) diff --git a/test/test_length_behavior.py b/test/test_length_behavior.py new file mode 100644 index 0000000..a81a8d0 --- /dev/null +++ b/test/test_length_behavior.py @@ -0,0 +1,527 @@ +"""Length policies at the public filename and filepath boundaries.""" + +import codecs +from pathlib import Path, PurePosixPath, PureWindowsPath +from unittest.mock import Mock + +import pytest + +import pathvalidate as pv +from pathvalidate.handler import ReservedNameHandler, raise_error + + +@pytest.fixture(params=["function", "class"]) +def filename(request): + def sanitize(value, replacement_text="", **kwargs): + kwargs.setdefault("platform", "linux") + kwargs.setdefault("fs_encoding", "utf-8") + if request.param == "function": + return pv.sanitize_filename(value, replacement_text=replacement_text, **kwargs) + return pv.FileNameSanitizer(**kwargs).sanitize(value, replacement_text) + + return sanitize + + +@pytest.fixture(params=["function", "class"]) +def filepath(request): + def sanitize(value, **kwargs): + kwargs.setdefault("platform", "linux") + kwargs.setdefault("fs_encoding", "utf-8") + if request.param == "function": + return pv.sanitize_filepath(value, **kwargs) + return pv.FilePathSanitizer(**kwargs).sanitize(value) + + return sanitize + + +@pytest.fixture(params=["string", "enum"]) +def behavior(request): + return lambda value: value if request.param == "string" else pv.LengthBehavior(value) + + +def assert_length_error(error, value, budget, encoding="utf-8", platform=pv.Platform.LINUX): + assert error.reason == pv.ErrorReason.INVALID_LENGTH + assert error.platform == platform + assert error.fs_encoding == encoding + assert error.byte_count == len(value.encode(encoding)) + assert error.as_slog()["value"] == value + assert f"expected<={budget} bytes" in str(error) + assert f"actual={len(value.encode(encoding))} bytes" in str(error) + + +def test_public_enum(): + assert {member.name: member.value for member in pv.LengthBehavior} == { + "KEEP": "keep", + "TRIM": "trim", + "TRIM_NAME": "trim_name", + "ERROR": "error", + } + assert "LengthBehavior" in pv.__all__ + + +@pytest.mark.parametrize( + "mode, expected", [("keep", "abcdefgh.txt"), ("trim", "abcdefgh"), ("trim_name", "abcd.txt")] +) +def test_filename_policies(filename, behavior, mode, expected): + assert filename("abcdefgh.txt", max_len=8, length_behavior=behavior(mode)) == expected + + +@pytest.mark.parametrize("mode", ["keep", "trim", "trim_name", "error"]) +def test_exact_boundary(filename, behavior, mode): + assert filename("abcd.txt", max_len=8, length_behavior=behavior(mode)) == "abcd.txt" + + +@pytest.mark.parametrize("post", [False, True]) +def test_error_metadata(filename, behavior, post): + with pytest.raises(pv.ValidationError) as exc: + filename( + "abcdefgh.txt", + max_len=8, + length_behavior=behavior("error"), + validate_after_sanitize=post, + ) + assert_length_error(exc.value, "abcdefgh.txt", 8) + + +def test_keep_final_validation(filename, behavior): + with pytest.raises(pv.ValidationError) as exc: + filename( + "abcdefgh.txt", + max_len=8, + length_behavior=behavior("keep"), + validate_after_sanitize=True, + ) + assert exc.value.reason == pv.ErrorReason.INVALID_AFTER_SANITIZE + assert "PV1101" in exc.value.description + + +@pytest.mark.parametrize( + "value,budget,expected", + [ + ("archive.tar.gz", 10, "archive.gz"), + (".bashrc", 4, ".bas"), + (".config.json", 8, ".co.json"), + ("...txt", 4, "...t"), + ("abc.txt", 4, ".txt"), + ("filename.", 6, "filen."), + ("abcdef", 3, "abc"), + (".", 1, "."), + ("..", 1, "."), + ], +) +def test_extension_rules(filename, behavior, value, budget, expected): + assert filename(value, max_len=budget, length_behavior=behavior("trim_name")) == expected + + +@pytest.mark.parametrize( + "value,budget,encoding,expected", + [ + ("あいう.txt", 10, "utf-8", "あい.txt"), + ("あいう.txt", 12, "utf-16", "あ.txt"), + ("😀ab.txt", 12, "utf-16-le", "😀.txt"), + ("😀ab.txt", 12, "utf-16-be", "😀.txt"), + ("😀ab.txt", 11, "utf-16-le", ".txt"), + ("😀ab.txt", 11, "utf-16-be", ".txt"), + ("e\u0301.txt", 6, "utf-8", "e.txt"), + ("日本語.txt", 12, "iso2022_jp", "日.txt"), + ("あいう.txt", 10, "UTF8", "あい.txt"), + ("あいう.txt", 13, "utf-8-sig", "あい.txt"), + ("😀ab.txt", 24, "utf-32", "😀.txt"), + ], +) +def test_encoded_candidates(filename, behavior, value, budget, encoding, expected): + result = filename( + value, max_len=budget, fs_encoding=encoding, length_behavior=behavior("trim_name") + ) + assert result == expected + assert len(result.encode(encoding)) <= budget + + +@pytest.mark.parametrize( + "value,budget,encoding", + [ + ("abc.txt", 3, "utf-8"), + ("abc.longextension", 4, "utf-8"), + ("abc.txt", 1, "utf-16"), + ], +) +def test_extension_cannot_fit(filename, behavior, value, budget, encoding): + with pytest.raises(pv.ValidationError) as exc: + filename(value, max_len=budget, fs_encoding=encoding, length_behavior=behavior("trim_name")) + assert_length_error(exc.value, value, budget, encoding) + assert "extension" in exc.value.description + + +def test_unicode_error_metadata(filename, behavior): + with pytest.raises(pv.ValidationError) as exc: + filename("あいう.txt", max_len=10, length_behavior=behavior("error")) + assert_length_error(exc.value, "あいう.txt", 10) + + +@pytest.mark.parametrize("mode", ["keep", "trim", "trim_name", "error"]) +@pytest.mark.parametrize( + "encoding,error", [("ascii", UnicodeEncodeError), ("unknown-encoding", LookupError)] +) +def test_encoding_errors_propagate(filename, mode, encoding, error): + with pytest.raises(error): + filename("あ.txt", length_behavior=mode, fs_encoding=encoding) + + +def test_replacement_precedes_policy(filename, behavior): + assert filename("ab/cdef", max_len=6, length_behavior=behavior("error")) == "abcdef" + with pytest.raises(pv.ValidationError) as exc: + filename("ab/cd", replacement_text="LONG", max_len=6, length_behavior=behavior("error")) + assert_length_error(exc.value, "abLONGcd", 6) + + +@pytest.mark.parametrize( + "value,budget,expected", + [ + ("CON.txt", 3, "CON_.txt"), + (" badname. ", 3, "badname"), + ("custom.txt", 3, "custom_.txt"), + ], +) +def test_keep_name_hygiene(filename, behavior, value, budget, expected): + handler = Mock(side_effect=ReservedNameHandler.add_trailing_underscore) + assert ( + filename( + value, + max_len=budget, + platform="windows", + additional_reserved_names=["custom"], + reserved_name_handler=handler, + length_behavior=behavior("keep"), + ) + == expected + ) + assert handler.call_count == (0 if value.startswith(" ") else 1) + with pytest.raises(pv.ValidationError) as exc: + filename( + value, + max_len=budget, + platform="windows", + additional_reserved_names=["custom"], + length_behavior=behavior("keep"), + validate_after_sanitize=True, + ) + assert exc.value.reason == pv.ErrorReason.INVALID_AFTER_SANITIZE + + +@pytest.mark.parametrize("mode", ["keep", "trim", "trim_name", "error"]) +def test_existing_reserved_substitution(filename, behavior, mode): + assert ( + filename("CON.CON", max_len=20, platform="windows", length_behavior=behavior(mode)) + == "CON_.CON_" + ) + + +@pytest.mark.parametrize("post", [False, True]) +def test_handler_growth_is_not_reprocessed(filename, behavior, post): + handler = Mock(return_value="long-handler-output") + kwargs = { + "max_len": 3, + "platform": "windows", + "length_behavior": behavior("error"), + "reserved_name_handler": handler, + "validate_after_sanitize": post, + } + if post: + with pytest.raises(pv.ValidationError) as exc: + filename("CON", **kwargs) + assert exc.value.reason == pv.ErrorReason.INVALID_AFTER_SANITIZE + else: + assert filename("CON", **kwargs) == "long-handler-output" + handler.assert_called_once() + + +@pytest.mark.parametrize("mode", ["keep", "trim", "trim_name", "error"]) +@pytest.mark.parametrize("value", ["", "/"]) +def test_null_handler(filename, behavior, mode, value): + handler = Mock(side_effect=raise_error) + with pytest.raises(pv.ValidationError) as exc: + filename(value, length_behavior=behavior(mode), null_value_handler=handler) + assert exc.value.reason == pv.ErrorReason.NULL_NAME + handler.assert_called_once() + + +def test_no_extension_null_and_windows_trailing_dot(filename): + assert filename("あ", max_len=1, length_behavior="trim_name") == "" + with pytest.raises(pv.ValidationError) as exc: + filename("あ", max_len=1, length_behavior="trim_name", validate_after_sanitize=True) + assert exc.value.reason == pv.ErrorReason.INVALID_AFTER_SANITIZE + assert ( + filename("filename.", max_len=6, length_behavior="trim_name", platform="windows") == "filen" + ) + with pytest.raises(pv.ValidationError) as exc: + filename(" badname. ", max_len=3, platform="windows", length_behavior="error") + assert_length_error(exc.value, " badname. ", 3, platform=pv.Platform.WINDOWS) + + +def test_path_component_and_total_budgets(filepath, behavior): + kwargs = {"max_len": 8, "normalize": False, "length_behavior": behavior("trim_name")} + assert filepath("abcdefgh.txt/ijklmnop.log", **kwargs) == "abcd.txt/ijkl.log" + with pytest.raises(pv.ValidationError) as exc: + filepath("abcdefgh.txt/ijklmnop.log", validate_after_sanitize=True, **kwargs) + assert exc.value.reason == pv.ErrorReason.INVALID_LENGTH + assert filepath("abc/def", max_len=3, length_behavior=behavior("error")) == "abc/def" + with pytest.raises(pv.ValidationError) as exc: + filepath( + "abc/def", max_len=3, length_behavior=behavior("error"), validate_after_sanitize=True + ) + assert exc.value.reason == pv.ErrorReason.INVALID_LENGTH + with pytest.raises(pv.ValidationError) as exc: + filepath("/abcdefgh.txt/end", max_len=8, length_behavior=behavior("error")) + assert_length_error(exc.value, "abcdefgh.txt", 8) + + +@pytest.mark.parametrize( + "mode,expected", [("keep", "abcdefgh.txt"), ("trim", "abcdefgh"), ("trim_name", "abcd.txt")] +) +def test_path_policies(filepath, behavior, mode, expected): + assert filepath("abcdefgh.txt", max_len=8, length_behavior=behavior(mode)) == expected + + +@pytest.mark.parametrize("mode", ["keep", "trim", "trim_name", "error"]) +def test_path_special_bypass(filepath, behavior, mode): + kwargs = {"max_len": 2, "length_behavior": behavior(mode)} + assert filepath("$Mft", **kwargs) == "$Mft_" + with pytest.raises(pv.ValidationError) as exc: + filepath("$Mft", validate_after_sanitize=True, **kwargs) + assert exc.value.reason == pv.ErrorReason.INVALID_LENGTH + + +@pytest.mark.parametrize("normalize,expected", [(False, "/abc/./def/../ghi"), (True, "/abc/ghi")]) +def test_path_dot_entries(filepath, normalize, expected): + assert ( + filepath("/abc//./def/../ghi/", max_len=3, length_behavior="error", normalize=normalize) + == expected + ) + + +@pytest.mark.parametrize( + "value,expected", + [ + ("C:\\abcdefgh.txt\\ijklmnop.log", "C:\\abcd.txt\\ijkl.log"), + ("\\\\server\\share\\abcdefgh.txt", "\\\\server\\share\\abcd.txt"), + ], +) +def test_drive_and_unc(filepath, value, expected): + assert ( + filepath(value, max_len=8, platform="windows", normalize=False, length_behavior="trim_name") + == expected + ) + + +@pytest.mark.parametrize("path_type", [Path, PurePosixPath, PureWindowsPath]) +def test_path_return_types(filename, filepath, path_type): + for sanitize in (filename, filepath): + result = sanitize(path_type("abcdefgh.txt"), max_len=8, length_behavior="trim_name") + assert type(result) is type(Path()) + assert result == Path("abcd.txt") + assert filename(PurePosixPath("abc/def.txt"), max_len=8, length_behavior="trim_name") == Path( + "abcd.txt" + ) + + +def test_input_types(filename, filepath): + for sanitize in (filename, filepath): + assert sanitize(Path(""), length_behavior="error") == Path(".") + assert sanitize("", length_behavior="error") == "" + with pytest.raises(TypeError): + sanitize(123, length_behavior="keep") + + +@pytest.mark.parametrize("invalid", ["TRIM", "unknown", "", None, 1, [], {}]) +def test_invalid_policy_is_early(filename, filepath, invalid): + for sanitize in (filename, filepath): + handler = Mock(return_value="null") + with pytest.raises(ValueError): + sanitize("", length_behavior=invalid, null_value_handler=handler) + handler.assert_not_called() + + +@pytest.mark.parametrize("post", [False, True]) +def test_injected_validator_protocol(post): + validator = Mock(spec=pv.AbstractValidator) + validator.validate.side_effect = pv.ValidationError(reason=pv.ErrorReason.INVALID_LENGTH) + handler = Mock(return_value="reserved") + sanitizer = pv.FileNameSanitizer( + 3, "utf-8", "windows", None, handler, None, post, validator, "keep" + ) + if post: + with pytest.raises(pv.ValidationError) as exc: + sanitizer.sanitize("CON.txt") + assert exc.value.reason == pv.ErrorReason.INVALID_AFTER_SANITIZE + else: + assert sanitizer.sanitize("CON.txt") == "CON.txt" + assert validator.validate.call_count == (2 if post else 1) + assert all(call.args == ("CON.txt",) for call in validator.validate.call_args_list) + handler.assert_not_called() + + +@pytest.mark.parametrize("post", [False, True]) +def test_injected_path_validator_protocol(post): + error = pv.ValidationError(reason=pv.ErrorReason.INVALID_LENGTH) + validator = Mock(spec=pv.AbstractValidator) + validator.validate.side_effect = error + handler = Mock(side_effect=ReservedNameHandler.add_trailing_underscore) + sanitizer = pv.FilePathSanitizer( + 3, "utf-8", "windows", None, handler, None, False, post, validator, "keep" + ) + if post: + # The ordinary component's requested final validation runs first. + with pytest.raises(pv.ValidationError) as exc: + sanitizer.sanitize("CON.txt") + assert exc.value.reason == pv.ErrorReason.INVALID_AFTER_SANITIZE + validator.validate.assert_not_called() + else: + assert sanitizer.sanitize("CON.txt") == "CON_.txt" + validator.validate.assert_called_once_with("CON_.txt") + handler.assert_called_once() + + +@pytest.mark.parametrize("post", [False, True]) +def test_custom_path_final_error_is_unchanged(post): + error = pv.ValidationError(reason=pv.ErrorReason.INVALID_CHARACTER) + validator = Mock(spec=pv.AbstractValidator) + validator.validate.side_effect = error + sanitizer = pv.FilePathSanitizer( + 3, "utf-8", "linux", None, None, None, False, post, validator, "keep" + ) + if post: + with pytest.raises(pv.ValidationError) as exc: + sanitizer.sanitize("abc") + assert exc.value is error + else: + assert sanitizer.sanitize("abc") == "abc" + assert validator.validate.call_count == (2 if post else 1) + + +def test_injected_concrete_filename_validator_keeps_length_priority(): + validator = pv.FileNameValidator(max_len=3, platform="windows", fs_encoding="utf-8") + handler = Mock(side_effect=ReservedNameHandler.add_trailing_underscore) + sanitizer = pv.FileNameSanitizer( + max_len=3, + platform="windows", + fs_encoding="utf-8", + length_behavior="keep", + validator=validator, + reserved_name_handler=handler, + ) + assert sanitizer.sanitize("CON.txt") == "CON.txt" + handler.assert_not_called() + + +def test_old_positional_arguments(): + assert ( + pv.sanitize_filename("abcdefgh.txt", "", "linux", 8, "utf-8", None, None, None, None, False) + == "abcdefgh" + ) + assert ( + pv.sanitize_filepath( + "abcdefgh.txt", "", "linux", 8, "utf-8", None, None, None, None, False, False + ) + == "abcdefgh" + ) + validator = Mock(spec=pv.AbstractValidator) + assert ( + pv.FileNameSanitizer(8, "utf-8", "linux", None, None, None, False, validator).sanitize( + "abcdefgh.txt" + ) + == "abcdefgh" + ) + validator.validate.assert_called_once_with("abcdefgh") + validator.reset_mock() + assert ( + pv.FilePathSanitizer( + 8, "utf-8", "linux", None, None, None, False, False, validator + ).sanitize("abcdefgh.txt") + == "abcdefgh" + ) + validator.validate.assert_called_once_with("abcdefgh") + + +@pytest.mark.parametrize("mode", ["keep", "trim", "trim_name", "error"]) +@pytest.mark.parametrize( + "platform,limit", [("linux", 4096), ("windows", 260), ("macos", 1024), ("universal", 260)] +) +@pytest.mark.parametrize("budget", [0, -1, 10000]) +def test_effective_budgets_unchanged(mode, platform, limit, budget): + for sanitizer_type in (pv.FileNameSanitizer, pv.FilePathSanitizer): + assert ( + sanitizer_type(max_len=budget, platform=platform, length_behavior=mode).max_len == limit + ) + + +def test_none_and_default_budgets(filename): + assert len(filename("a" * 300)) == 255 + for sanitize in (pv.sanitize_filename, pv.sanitize_filepath): + assert len(sanitize("a" * 5000, max_len=None, platform="linux")) == 4096 + # None is supported by the wrappers, not the existing class constructors. + for sanitizer_type in (pv.FileNameSanitizer, pv.FilePathSanitizer): + with pytest.raises(TypeError): + sanitizer_type(max_len=None) + + +@pytest.mark.parametrize("sanitize", [pv.sanitize_filename, pv.sanitize_filepath]) +def test_deprecated_check_reserved(sanitize): + with pytest.warns(DeprecationWarning): + assert ( + sanitize( + "CON.txt", + platform="windows", + max_len=3, + check_reserved=False, + length_behavior="keep", + ) + == "CON.txt" + ) + + +@pytest.mark.parametrize( + "encoding,value,budget,expected", + [ + ("iso2022_jp", "日本語", 8, "日本"), + ("utf-7", "日本語", 7, "日本"), + ("utf-16", "あ", 1, ""), + ], +) +def test_shared_trim_behavior_remains(filename, encoding, value, budget, expected): + for mode in ("trim", "trim_name"): + assert ( + filename(value, max_len=budget, fs_encoding=encoding, length_behavior=mode) == expected + ) + + +def test_nonmonotonic_codec(filename): + # A registered codec can shrink a longer prefix, even when the extension + # alone exceeds the budget. Neither early rejection nor bisection is valid. + lengths = { + ".txt": 10, + "a.txt": 5, + "ab.txt": 7, + "abc.txt": 12, + "abcd.txt": 9, + "abcde.txt": 6, + "abcdef.txt": 15, + } + + def encode(value, errors="strict"): + return b"x" * lengths[value], len(value) + + def search(name): + if name == "pathvalidate_nonmonotonic": + return codecs.CodecInfo(name=name, encode=encode, decode=None) + return None + + codecs.register(search) + assert ( + filename( + "abcdef.txt", + max_len=6, + fs_encoding="pathvalidate_nonmonotonic", + length_behavior="trim_name", + ) + == "abcde.txt" + )