format_filename replaces invalid bytes
Before adoption: this commit came in with the history the project adopted, so no landing records it.
- Names are converted to bytes, handling surrogate escapes, then invalid bytes are replaced. - Remove _compat.get_filesystem_encoding, sys.getfilesystemencoding does not return None since Python 3.2. - Use format_filename in more places. - Test that surrogate escapes are not present in error messages. - Add information about when surrogate escapes are safe for output to format_filename docstring. - Move supports_symlinks check next to test instead of importing. - Improve click.Path documentation about str/bytes handling.
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
9 files+193 added−82 removed
- tests:+110 added−28 removed
- other:+83 added−54 removed
Provenance
- Commit
43c2e7f- Tree
7e4bd78- Author
Frazer McLean <frazer@frazermclean.co.uk>- Committer
David Lord <davidism@gmail.com>- Parent
0c8f301
9 files changed+193 added−82 removed
modified:docs/arguments.rst+3 added-9 removed
122 unmodified lines123 -------------------124 125 In the previous example, the files were opened immediately. But what if126 we just want the filename? The naïve way is to use the default string127-argument type. However, remember that Click is Unicode-based, so the string128-will always be a Unicode value. Unfortunately, filenames can be Unicode or129-bytes depending on which operating system is being used. As such, the type130-is insufficient.127+argument type. The :class:`Path` type has several checks available which raise nice128+errors if they fail, such as existence. Filenames in these error messages are formatted129+with :func:`format_filename`, so any undecodable bytes will be printed nicely.130 132-Instead, you should be using the :class:`Path` type, which automatically133-handles this ambiguity. Not only will it return either bytes or Unicode134-depending on what makes more sense, but it will also be able to do some135-basic checks for you such as existence checks.136-131 Example:132 133 .. click:example::134 129 unmodified linesmodified:src/click/_compat.py+3 added-6 removed
15 unmodified lines16 auto_wrap_for_ansi: t.Optional[t.Callable[[t.TextIO], t.TextIO]] = None17 _ansi_re = re.compile(r"\033\[[;?0-9]*[a-zA-Z]")18 19 20-def get_filesystem_encoding() -> str:21- return sys.getfilesystemencoding() or sys.getdefaultencoding()22-23-20 def _make_text_stream(21 stream: t.BinaryIO,22 encoding: t.Optional[str],23 errors: t.Optional[str],351 unmodified lines375 return open(file, mode, encoding=encoding, errors=errors)376 377 378 def open_stream(383- filename: str,379+ filename: "t.Union[str, os.PathLike[str]]",380 mode: str = "r",381 encoding: t.Optional[str] = None,382 errors: t.Optional[str] = "strict",383 atomic: bool = False,384 ) -> t.Tuple[t.IO[t.Any], bool]:385 binary = "b" in mode386+ filename = os.fspath(filename)387 388 # Standard streams first. These are simple because they ignore the389 # atomic flag. Use fsdecode to handle Path("-").390 if os.fsdecode(filename) == "-":169 unmodified lines560 561 else:562 563 def _get_argv_encoding() -> str:567- return getattr(sys.stdin, "encoding", None) or get_filesystem_encoding()564+ return getattr(sys.stdin, "encoding", None) or sys.getfilesystemencoding()565 566 def _get_windows_console_stream(567 f: t.TextIO, encoding: t.Optional[str], errors: t.Optional[str]568 ) -> t.Optional[t.TextIO]:55 unmodified linesmodified:src/click/exceptions.py+2 added-2 removed
1-import os1 import typing as t2 from gettext import gettext as _3 from gettext import ngettext4 5 from ._compat import get_text_stderr6 from .utils import echo7+from .utils import format_filename8 9 if t.TYPE_CHECKING:10 from .core import Command11 from .core import Context249 unmodified lines261 if hint is None:262 hint = _("unknown error")263 264 super().__init__(hint)265- self.ui_filename: str = os.fsdecode(filename)265+ self.ui_filename: str = format_filename(filename)266 self.filename = filename267 268 def format_message(self) -> str:269 return _("Could not open file {filename!r}: {message}").format(19 unmodified linesmodified:src/click/types.py+39 added-24 removed
1 import os2 import stat3+import sys4 import typing as t5 from datetime import datetime6 from gettext import gettext as _7 from gettext import ngettext8 9 from ._compat import _get_argv_encoding9-from ._compat import get_filesystem_encoding10 from ._compat import open_stream11 from .exceptions import BadParameter12+from .utils import format_filename13 from .utils import LazyFile14 from .utils import safecall15 16 if t.TYPE_CHECKING:190 unmodified lines207 enc = _get_argv_encoding()208 try:209 value = value.decode(enc)210 except UnicodeError:210- fs_enc = get_filesystem_encoding()211+ fs_enc = sys.getfilesystemencoding()212 if fs_enc != enc:213 try:214 value = value.decode(fs_enc)215 except UnicodeError:471 unmodified lines687 info_dict = super().to_info_dict()688 info_dict.update(mode=self.mode, encoding=self.encoding)689 return info_dict690 690- def resolve_lazy_flag(self, value: t.Any) -> bool:691+ def resolve_lazy_flag(self, value: "t.Union[str, os.PathLike[str]]") -> bool:692 if self.lazy is not None:693 return self.lazy693- if value == "-":694+ if os.fspath(value) == "-":695 return False696 elif "w" in self.mode:697 return True698 return False699 700 def convert(700- self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]701- ) -> t.Any:702- try:703- if hasattr(value, "read") or hasattr(value, "write"):704- return value701+ self,702+ value: t.Union[str, "os.PathLike[str]", t.IO[t.Any]],703+ param: t.Optional["Parameter"],704+ ctx: t.Optional["Context"],705+ ) -> t.IO[t.Any]:706+ if _is_file_like(value):707+ return value708 709+ value = t.cast("t.Union[str, os.PathLike[str]]", value)710+711+ try:712 lazy = self.resolve_lazy_flag(value)713 714 if lazy:715 lf = LazyFile(21 unmodified lines737 ctx.call_on_close(safecall(f.flush))738 739 return f740 except OSError as e: # noqa: B014735- self.fail(f"'{os.fsdecode(value)}': {e.strerror}", param, ctx)741+ self.fail(f"'{format_filename(value)}': {e.strerror}", param, ctx)742 743 def shell_complete(744 self, ctx: "Context", param: "Parameter", incomplete: str745 ) -> t.List["CompletionItem"]:10 unmodified lines756 757 return [CompletionItem(incomplete, type="file")]758 759 760+def _is_file_like(value: t.Any) -> "te.TypeGuard[t.IO[t.Any]]":761+ return hasattr(value, "read") or hasattr(value, "write")762+763+764 class Path(ParamType):765 """The ``Path`` type is similar to the :class:`File` type, but766 returns the filename instead of an open file. Various checks can be767 enabled to validate the type of file and permissions.68 unmodified lines836 allow_dash=self.allow_dash,837 )838 return info_dict839 830- def coerce_path_result(self, rv: t.Any) -> t.Any:831- if self.type is not None and not isinstance(rv, self.type):840+ def coerce_path_result(841+ self, value: "t.Union[str, os.PathLike[str]]"842+ ) -> "t.Union[str, bytes, os.PathLike[str]]":843+ if self.type is not None and not isinstance(value, self.type):844 if self.type is str:833- rv = os.fsdecode(rv)845+ return os.fsdecode(value)846 elif self.type is bytes:835- rv = os.fsencode(rv)847+ return os.fsencode(value)848 else:837- rv = self.type(rv)849+ return t.cast("os.PathLike[str]", self.type(value))850 839- return rv851+ return value852 853 def convert(842- self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]843- ) -> t.Any:854+ self,855+ value: "t.Union[str, os.PathLike[str]]",856+ param: t.Optional["Parameter"],857+ ctx: t.Optional["Context"],858+ ) -> "t.Union[str, bytes, os.PathLike[str]]":859 rv = value860 861 is_dash = self.file_okay and self.allow_dash and rv in (b"-", "-")862 11 unmodified lines874 if not self.exists:875 return self.coerce_path_result(rv)876 self.fail(877 _("{name} {filename!r} does not exist.").format(863- name=self.name.title(), filename=os.fsdecode(value)878+ name=self.name.title(), filename=format_filename(value)879 ),880 param,881 ctx,882 )883 884 if not self.file_okay and stat.S_ISREG(st.st_mode):885 self.fail(886 _("{name} {filename!r} is a file.").format(872- name=self.name.title(), filename=os.fsdecode(value)887+ name=self.name.title(), filename=format_filename(value)888 ),889 param,890 ctx,891 )892 if not self.dir_okay and stat.S_ISDIR(st.st_mode):893 self.fail(894 _("{name} '{filename}' is a directory.").format(880- name=self.name.title(), filename=os.fsdecode(value)895+ name=self.name.title(), filename=format_filename(value)896 ),897 param,898 ctx,899 )900 901 if self.readable and not os.access(rv, os.R_OK):902 self.fail(903 _("{name} {filename!r} is not readable.").format(889- name=self.name.title(), filename=os.fsdecode(value)904+ name=self.name.title(), filename=format_filename(value)905 ),906 param,907 ctx,908 )909 910 if self.writable and not os.access(rv, os.W_OK):911 self.fail(912 _("{name} {filename!r} is not writable.").format(898- name=self.name.title(), filename=os.fsdecode(value)913+ name=self.name.title(), filename=format_filename(value)914 ),915 param,916 ctx,917 )918 919 if self.executable and not os.access(value, os.X_OK):920 self.fail(921 _("{name} {filename!r} is not executable.").format(907- name=self.name.title(), filename=os.fsdecode(value)922+ name=self.name.title(), filename=format_filename(value)923 ),924 param,925 ctx,926 )163 unmodified linesmodified:src/click/utils.py+34 added-13 removed
9 unmodified lines10 from ._compat import _default_text_stdout11 from ._compat import _find_binary_writer12 from ._compat import auto_wrap_for_ansi13 from ._compat import binary_streams14-from ._compat import get_filesystem_encoding14 from ._compat import open_stream15 from ._compat import should_strip_ansi16 from ._compat import strip_ansi17 from ._compat import text_streams28 unmodified lines46 def make_str(value: t.Any) -> str:47 """Converts a value into a valid string."""48 if isinstance(value, bytes):49 try:51- return value.decode(get_filesystem_encoding())50+ return value.decode(sys.getfilesystemencoding())51 except UnicodeError:52 return value.decode("utf-8", "replace")53 return str(value)54 56 unmodified lines111 """112 113 def __init__(114 self,116- filename: str,115+ filename: t.Union[str, "os.PathLike[str]"],116 mode: str = "r",117 encoding: t.Optional[str] = None,118 errors: t.Optional[str] = "strict",119 atomic: bool = False,120 ):122- self.name = filename121+ self.name: str = os.fspath(filename)122 self.mode = mode123 self.encoding = encoding124 self.errors = errors125 self.atomic = atomic126 self._f: t.Optional[t.IO[t.Any]]127 self.should_close: bool128 130- if filename == "-":129+ if self.name == "-":130 self._f, self.should_close = open_stream(filename, mode, encoding, errors)131 else:132 if "r" in mode:133 # Open and close the file in case we're opening it for8 unmodified lines142 143 def __repr__(self) -> str:144 if self._f is not None:145 return repr(self._f)147- return f"<unopened file '{self.name}' {self.mode}>"146+ return f"<unopened file '{format_filename(self.name)}' {self.mode}>"147 148 def open(self) -> t.IO[t.Any]:149 """Opens the file if it's not yet open. This call might fail with150 a :exc:`FileError`. Not handling this error will produce an error245 unmodified lines396 return f397 398 399 def format_filename(401- filename: t.Union[str, bytes, "os.PathLike[t.AnyStr]"], shorten: bool = False400+ filename: "t.Union[str, bytes, os.PathLike[str], os.PathLike[bytes]]",401+ shorten: bool = False,402 ) -> str:403- """Formats a filename for user display. The main purpose of this404- function is to ensure that the filename can be displayed at all. This405- will decode the filename to unicode if necessary in a way that it will406- not fail. Optionally, it can shorten the filename to not include the407- full path to the filename.403+ """Format a filename as a string for display. Ensures the filename can be404+ displayed by replacing any invalid bytes or surrogate escapes in the name405+ with the replacement character ``�``.406 407+ Invalid bytes or surrogate escapes will raise an error when written to a408+ stream with ``errors="strict". This will typically happen with ``stdout``409+ when the locale is something like ``en_GB.UTF-8``.410+411+ Many scenarios *are* safe to write surrogates though, due to PEP 538 and412+ PEP 540, including:413+414+ - Writing to ``stderr``, which uses ``errors="backslashreplace"``.415+ - The system has ``LANG=C.UTF-8``, ``C``, or ``POSIX``. Python opens416+ stdout and stderr with ``errors="surrogateescape"``.417+ - None of ``LANG/LC_*`` are set. Python assumes ``LANG=C.UTF-8``.418+ - Python is started in UTF-8 mode with ``PYTHONUTF8=1`` or ``-X utf8``.419+ Python opens stdout and stderr with ``errors="surrogateescape"``.420+421 :param filename: formats a filename for UI display. This will also convert422 the filename into unicode without failing.423 :param shorten: this optionally shortens the filename to strip of the424 path that leads up to it.425 """426 if shorten:427 filename = os.path.basename(filename)428+ else:429+ filename = os.fspath(filename)430 417- return os.fsdecode(filename)431+ if isinstance(filename, bytes):432+ filename = filename.decode(sys.getfilesystemencoding(), "replace")433+ else:434+ filename = filename.encode("utf-8", "surrogateescape").decode(435+ "utf-8", "replace"436+ )437 438+ return filename439 440+441 def get_app_dir(app_name: str, roaming: bool = True, force_posix: bool = False) -> str:442 r"""Returns the config folder for the application. The default behavior443 is to return whatever is most appropriate for the operating system.444 175 unmodified linesmodified:tests/conftest.py-19 removed
1-import os2-import tempfile3-1 import pytest2 3 from click.testing import CliRunner4 5 6 @pytest.fixture(scope="function")7 def runner(request):8 return CliRunner()12-13-14-def _check_symlinks_supported():15- with tempfile.TemporaryDirectory(prefix="click-pytest-") as tempdir:16- target = os.path.join(tempdir, "target")17- open(target, "w").close()18- link = os.path.join(tempdir, "link")19-20- try:21- os.symlink(target, link)22- return True23- except OSError:24- return False25-26-27-symlinks_supported = _check_symlinks_supported()modified:tests/test_types.py+109 added-5 removed
1 import os.path2 import pathlib3+import tempfile4 5 import pytest5-from conftest import symlinks_supported6 7 import click8+from click import FileError9 10 11 @pytest.mark.parametrize(12 ("type", "value", "expect"),91 unmodified lines104 assert result.exception is None105 assert result.return_value == expect106 107 108+def _symlinks_supported():109+ with tempfile.TemporaryDirectory(prefix="click-pytest-") as tempdir:110+ target = os.path.join(tempdir, "target")111+ open(target, "w").close()112+ link = os.path.join(tempdir, "link")113+114+ try:115+ os.symlink(target, link)116+ return True117+ except OSError:118+ return False119+120+121 @pytest.mark.skipif(108- not symlinks_supported, reason="The current OS or FS doesn't support symlinks."122+ not _symlinks_supported(), reason="The current OS or FS doesn't support symlinks."123 )124 def test_path_resolve_symlink(tmp_path, runner):125 test_file = tmp_path / "file"112- test_file_str = os.fsdecode(test_file)126+ test_file_str = os.fspath(test_file)127 test_file.write_text("")128 129 path_type = click.Path(resolve_path=True)130 param = click.Argument(["a"], type=path_type)3 unmodified lines134 test_dir.mkdir()135 136 abs_link = test_dir / "abs"137 abs_link.symlink_to(test_file)124- abs_rv = path_type.convert(os.fsdecode(abs_link), param, ctx)138+ abs_rv = path_type.convert(os.fspath(abs_link), param, ctx)139 assert abs_rv == test_file_str140 141 rel_link = test_dir / "rel"142 rel_link.symlink_to(pathlib.Path("..") / "file")129- rel_rv = path_type.convert(os.fsdecode(rel_link), param, ctx)143+ rel_rv = path_type.convert(os.fspath(rel_link), param, ctx)144 assert rel_rv == test_file_str145+146+147+def _non_utf8_filenames_supported():148+ with tempfile.TemporaryDirectory(prefix="click-pytest-") as tempdir:149+ try:150+ f = open(os.path.join(tempdir, "\udcff"), "w")151+ except OSError:152+ return False153+154+ f.close()155+ return True156+157+158+@pytest.mark.skipif(159+ not _non_utf8_filenames_supported(),160+ reason="The current OS or FS doesn't support non-UTF-8 filenames.",161+)162+def test_path_surrogates(tmp_path, monkeypatch):163+ monkeypatch.chdir(tmp_path)164+ type = click.Path(exists=True)165+ path = pathlib.Path("\udcff")166+167+ with pytest.raises(click.BadParameter, match="'�' does not exist"):168+ type.convert(path, None, None)169+170+ type = click.Path(file_okay=False)171+ path.touch()172+173+ with pytest.raises(click.BadParameter, match="'�' is a file"):174+ type.convert(path, None, None)175+176+ path.unlink()177+ type = click.Path(dir_okay=False)178+ path.mkdir()179+180+ with pytest.raises(click.BadParameter, match="'�' is a directory"):181+ type.convert(path, None, None)182+183+ path.rmdir()184+185+ def no_access(*args, **kwargs):186+ """Test environments may be running as root, so we have to fake the result of187+ the access tests that use os.access188+ """189+ p = args[0]190+ assert p == path, f"unexpected os.access call on file not under test: {p!r}"191+ return False192+193+ path.touch()194+ type = click.Path(readable=True)195+196+ with pytest.raises(click.BadParameter, match="'�' is not readable"):197+ with monkeypatch.context() as m:198+ m.setattr(os, "access", no_access)199+ type.convert(path, None, None)200+201+ type = click.Path(readable=False, writable=True)202+203+ with pytest.raises(click.BadParameter, match="'�' is not writable"):204+ with monkeypatch.context() as m:205+ m.setattr(os, "access", no_access)206+ type.convert(path, None, None)207+208+ type = click.Path(readable=False, executable=True)209+210+ with pytest.raises(click.BadParameter, match="'�' is not executable"):211+ with monkeypatch.context() as m:212+ m.setattr(os, "access", no_access)213+ type.convert(path, None, None)214+215+ path.unlink()216+217+218+@pytest.mark.parametrize(219+ "type",220+ [221+ click.File(mode="r"),222+ click.File(mode="r", lazy=True),223+ ],224+)225+def test_file_surrogates(type, tmp_path):226+ path = tmp_path / "\udcff"227+228+ with pytest.raises(click.BadParameter, match="�': No such file or directory"):229+ type.convert(path, None, None)230+231+232+def test_file_error_surrogates():233+ message = FileError(filename="\udcff").format_message()234+ assert message == "Could not open file '�': unknown error"modified:tests/test_utils.py+1 added-4 removed
96 unmodified lines97 assert click.format_filename(b"foo.txt") == "foo.txt"98 assert click.format_filename(b"/x/foo.txt") == "/x/foo.txt"99 assert click.format_filename("/x/foo.txt") == "/x/foo.txt"100 assert click.format_filename("/x/foo.txt", shorten=True) == "foo.txt"101+ assert click.format_filename(b"/x/\xff.txt", shorten=True) == "�.txt"102 102- # filesystem encoding on windows permits this.103- if not WIN:104- assert click.format_filename(b"/x/foo\xff.txt", shorten=True) == "foo\udcff.txt"103 106-104 def test_prompts(runner):105 @click.command()106 def test():107 if click.confirm("Foo"):391 unmodified linesmodified:CHANGES.rst+2 added
24 unmodified lines25 - ``multiple=True`` is allowed for flag options again and does not require26 setting ``default=()``. :issue:`2246, 2292, 2295`27 - Make the decorators returned by ``@argument()`` and ``@option()`` reusable when the28 ``cls`` parameter is used. :issue:`2294`29+- Don't fail when writing filenames to streams with strict errors. Replace invalid30+ bytes with the replacement character (``�``). :issue:`2395`31 32 33 Version 8.1.334 -------------1040 unmodified lines