diff --git a/pathvalidate/_filename.py b/pathvalidate/_filename.py index f2651ed..1303d37 100644 --- a/pathvalidate/_filename.py +++ b/pathvalidate/_filename.py @@ -76,7 +76,7 @@ def sanitize(self, value: PathType, replacement_text: str = "") -> PathType: return self._null_value_handler(e) # type: ignore raise - sanitized_filename = self._sanitize_regexp.sub(replacement_text, str(value)) + sanitized_filename = self._sanitize_regexp.sub(lambda match: replacement_text, str(value)) sanitized_filename = truncate_str(sanitized_filename, self._fs_encoding, self.max_len) try: @@ -86,7 +86,9 @@ def sanitize(self, value: PathType, replacement_text: str = "") -> PathType: replacement_word = self._reserved_name_handler(e) if e.reserved_name != replacement_word: sanitized_filename = re.sub( - re.escape(e.reserved_name), replacement_word, sanitized_filename + re.escape(e.reserved_name), + lambda match: replacement_word, + sanitized_filename, ) elif e.reason == ErrorReason.INVALID_CHARACTER and self._is_windows( include_universal=True diff --git a/pathvalidate/_filepath.py b/pathvalidate/_filepath.py index df49ed4..b9a2393 100644 --- a/pathvalidate/_filepath.py +++ b/pathvalidate/_filepath.py @@ -92,7 +92,9 @@ def sanitize(self, value: PathType, replacement_text: str = "") -> PathType: unicode_filepath = to_str(value) drive, unicode_filepath = self.__split_drive(unicode_filepath) - unicode_filepath = self._sanitize_regexp.sub(replacement_text, unicode_filepath) + unicode_filepath = self._sanitize_regexp.sub( + lambda match: replacement_text, unicode_filepath + ) if self.__normalize and unicode_filepath: unicode_filepath = os.path.normpath(unicode_filepath) sanitized_path = unicode_filepath diff --git a/test/test_literal_replacements.py b/test/test_literal_replacements.py new file mode 100644 index 0000000..40f64fe --- /dev/null +++ b/test/test_literal_replacements.py @@ -0,0 +1,30 @@ +import pytest + +from pathvalidate import sanitize_filename, sanitize_filepath + + +@pytest.mark.parametrize("replacement", [r"\n", r"\1", r"\g<0>", "\\"]) +def test_filename_replacement_is_literal(replacement): + assert sanitize_filename("a/b", replacement_text=replacement, platform="linux") == ( + "a" + replacement + "b" + ) + + +@pytest.mark.parametrize("replacement", [r"\n", r"\1", r"\g<0>"]) +def test_filepath_replacement_is_literal(replacement): + assert sanitize_filepath( + "a\x00b", replacement_text=replacement, platform="linux", normalize=False + ) == ("a" + replacement.replace("\\", "/") + "b") + + +@pytest.mark.parametrize("replacement", [r"\n", r"\1", r"\g<0>", "\\"]) +def test_reserved_name_handler_replacement_is_literal(replacement): + assert ( + sanitize_filename( + "reserved", + platform="linux", + additional_reserved_names=["reserved"], + reserved_name_handler=lambda error: replacement, + ) + == replacement + )