Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
92 changes: 92 additions & 0 deletions docs/pages/reference/tips.rst
Original file line number Diff line number Diff line change
@@ -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:
Expand Down
5 changes: 5 additions & 0 deletions docs/pages/reference/types.rst
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
Types
---------------

.. autoclass:: pathvalidate.LengthBehavior
:members:
:undoc-members:
:show-inheritance:

.. autoclass:: pathvalidate.Platform
:members:
:undoc-members:
Expand Down
3 changes: 2 additions & 1 deletion pathvalidate/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
validate_pathtype,
validate_unprintable_char,
)
from ._const import Platform
from ._const import LengthBehavior, Platform
from ._filename import (
FileNameSanitizer,
FileNameValidator,
Expand Down Expand Up @@ -49,6 +49,7 @@
"__version__",
"AbstractSanitizer",
"AbstractValidator",
"LengthBehavior",
"Platform",
"ascii_symbols",
"normalize_platform",
Expand Down
14 changes: 14 additions & 0 deletions pathvalidate/_const.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
"""
Expand Down
131 changes: 125 additions & 6 deletions pathvalidate/_filename.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,19 @@
.. codeauthor:: Tsuyoshi Hombashi <[email protected]>
"""

import codecs
import itertools
import posixpath
import re
import warnings
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
Expand All @@ -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:
Expand All @@ -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,
Expand All @@ -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)
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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.

Expand All @@ -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.
Expand Down Expand Up @@ -445,14 +541,36 @@ 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):
Sanitized 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`
Expand All @@ -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)
Loading