Skip to content
Myr

`format_filename` replaces invalid bytes (#2553)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by David Lord · committed by GitHub · parents 0c8f301, 43c2e7f · Browse files · 9 files+193 added−82 removed
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

9 files+193 added−82 removed

modified:docs/arguments.rst+3 added-9 removed
122 unmodified lines
123-------------------124125In the previous example, the files were opened immediately. But what if126we just want the filename? The naïve way is to use the default string127argument type. However, remember that Click is Unicode-based, so the string128will always be a Unicode value. Unfortunately, filenames can be Unicode or129bytes depending on which operating system is being used. As such, the type130is insufficient.127argument type. The :class:`Path` type has several checks available which raise nice128errors if they fail, such as existence. Filenames in these error messages are formatted129with :func:`format_filename`, so any undecodable bytes will be printed nicely.130132Instead, you should be using the :class:`Path` type, which automatically133handles this ambiguity. Not only will it return either bytes or Unicode134depending on what makes more sense, but it will also be able to do some135basic checks for you such as existence checks.136131Example:132133.. click:example::134
129 unmodified lines
modified:src/click/_compat.py+3 added-6 removed
15 unmodified lines
16auto_wrap_for_ansi: t.Optional[t.Callable[[t.TextIO], t.TextIO]] = None17_ansi_re = re.compile(r"\033\[[;?0-9]*[a-zA-Z]")181920def get_filesystem_encoding() -> str:21 return sys.getfilesystemencoding() or sys.getdefaultencoding()222320def _make_text_stream(21 stream: t.BinaryIO,22 encoding: t.Optional[str],23 errors: t.Optional[str],
351 unmodified lines
375 return open(file, mode, encoding=encoding, errors=errors)376377378def 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)387388 # Standard streams first. These are simple because they ignore the389 # atomic flag. Use fsdecode to handle Path("-").390 if os.fsdecode(filename) == "-":
169 unmodified lines
560561else:562563 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()565566 def _get_windows_console_stream(567 f: t.TextIO, encoding: t.Optional[str], errors: t.Optional[str]568 ) -> t.Optional[t.TextIO]:
55 unmodified lines
modified:src/click/exceptions.py+2 added-2 removed
1import os1import typing as t2from gettext import gettext as _3from gettext import ngettext45from ._compat import get_text_stderr6from .utils import echo7from .utils import format_filename89if t.TYPE_CHECKING:10 from .core import Command11 from .core import Context
249 unmodified lines
261 if hint is None:262 hint = _("unknown error")263264 super().__init__(hint)265 self.ui_filename: str = os.fsdecode(filename)265 self.ui_filename: str = format_filename(filename)266 self.filename = filename267268 def format_message(self) -> str:269 return _("Could not open file {filename!r}: {message}").format(
19 unmodified lines
modified:src/click/types.py+39 added-24 removed
1import os2import stat3import sys4import typing as t5from datetime import datetime6from gettext import gettext as _7from gettext import ngettext89from ._compat import _get_argv_encoding9from ._compat import get_filesystem_encoding10from ._compat import open_stream11from .exceptions import BadParameter12from .utils import format_filename13from .utils import LazyFile14from .utils import safecall1516if t.TYPE_CHECKING:
190 unmodified lines
207 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 lines
687 info_dict = super().to_info_dict()688 info_dict.update(mode=self.mode, encoding=self.encoding)689 return info_dict690690 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 False699700 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 value708709 value = t.cast("t.Union[str, os.PathLike[str]]", value)710711 try:712 lazy = self.resolve_lazy_flag(value)713714 if lazy:715 lf = LazyFile(
21 unmodified lines
737 ctx.call_on_close(safecall(f.flush))738739 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)742743 def shell_complete(744 self, ctx: "Context", param: "Parameter", incomplete: str745 ) -> t.List["CompletionItem"]:
10 unmodified lines
756757 return [CompletionItem(incomplete, type="file")]758759760def _is_file_like(value: t.Any) -> "te.TypeGuard[t.IO[t.Any]]":761 return hasattr(value, "read") or hasattr(value, "write")762763764class 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 lines
836 allow_dash=self.allow_dash,837 )838 return info_dict839830 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))850839 return rv851 return value852853 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 = value860861 is_dash = self.file_okay and self.allow_dash and rv in (b"-", "-")862
11 unmodified lines
874 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 )883884 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 )900901 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 )909910 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 )918919 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 lines
modified:src/click/utils.py+34 added-13 removed
9 unmodified lines
10from ._compat import _default_text_stdout11from ._compat import _find_binary_writer12from ._compat import auto_wrap_for_ansi13from ._compat import binary_streams14from ._compat import get_filesystem_encoding14from ._compat import open_stream15from ._compat import should_strip_ansi16from ._compat import strip_ansi17from ._compat import text_streams
28 unmodified lines
46def 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 lines
111 """112113 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: bool128130 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 for
8 unmodified lines
142143 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}>"147148 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 error
245 unmodified lines
396 return f397398399def 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 ``�``.406407 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``.410411 Many scenarios *are* safe to write surrogates though, due to PEP 538 and412 PEP 540, including:413414 - 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"``.420421 :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)430417 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 )437438 return filename439440441def 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 lines
modified:tests/conftest.py-19 removed
1import os2import tempfile31import pytest23from click.testing import CliRunner456@pytest.fixture(scope="function")7def runner(request):8 return CliRunner()121314def _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")1920 try:21 os.symlink(target, link)22 return True23 except OSError:24 return False252627symlinks_supported = _check_symlinks_supported()
modified:tests/test_types.py+109 added-5 removed
1import os.path2import pathlib3import tempfile45import pytest5from conftest import symlinks_supported67import click8from click import FileError91011@pytest.mark.parametrize(12 ("type", "value", "expect"),
91 unmodified lines
104 assert result.exception is None105 assert result.return_value == expect106107108def _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")113114 try:115 os.symlink(target, link)116 return True117 except OSError:118 return False119120121@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)124def 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("")128129 path_type = click.Path(resolve_path=True)130 param = click.Argument(["a"], type=path_type)
3 unmodified lines
134 test_dir.mkdir()135136 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_str140141 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_str145146147def _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 False153154 f.close()155 return True156157158@pytest.mark.skipif(159 not _non_utf8_filenames_supported(),160 reason="The current OS or FS doesn't support non-UTF-8 filenames.",161)162def test_path_surrogates(tmp_path, monkeypatch):163 monkeypatch.chdir(tmp_path)164 type = click.Path(exists=True)165 path = pathlib.Path("\udcff")166167 with pytest.raises(click.BadParameter, match="'�' does not exist"):168 type.convert(path, None, None)169170 type = click.Path(file_okay=False)171 path.touch()172173 with pytest.raises(click.BadParameter, match="'�' is a file"):174 type.convert(path, None, None)175176 path.unlink()177 type = click.Path(dir_okay=False)178 path.mkdir()179180 with pytest.raises(click.BadParameter, match="'�' is a directory"):181 type.convert(path, None, None)182183 path.rmdir()184185 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 False192193 path.touch()194 type = click.Path(readable=True)195196 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)200201 type = click.Path(readable=False, writable=True)202203 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)207208 type = click.Path(readable=False, executable=True)209210 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)214215 path.unlink()216217218@pytest.mark.parametrize(219 "type",220 [221 click.File(mode="r"),222 click.File(mode="r", lazy=True),223 ],224)225def test_file_surrogates(type, tmp_path):226 path = tmp_path / "\udcff"227228 with pytest.raises(click.BadParameter, match="�': No such file or directory"):229 type.convert(path, None, None)230231232def 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 lines
97 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"102102 # 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"103106104def test_prompts(runner):105 @click.command()106 def test():107 if click.confirm("Foo"):
391 unmodified lines
modified:CHANGES.rst+2 added
24 unmodified lines
25- ``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`313233Version 8.1.334-------------
1040 unmodified lines