Skip to content
Myr

Merge branch '8.1.x' of https://github.com/Rowlando13/click into separate_virtualenv_I

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

authored by unknown · committed by unknown · parents 03f5496, 6986b08 · Browse files · 29 files+471 added−154 removed
This commit

State

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

Diff stats

29 files+471 added−154 removed

  • tests:+261 added−28 removed
  • other:+210 added−126 removed

29 files+471 added−154 removed

modified:.github/workflows/publish.yaml+10 added-10 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:docs/shell-completion.rst+1 added-1 removed
60 unmodified lines
61 Add this to ``~/.config/fish/completions/foo-bar.fish``:6263 .. code-block:: fish6465 eval (env _FOO_BAR_COMPLETE=fish_source foo-bar)65 _FOO_BAR_COMPLETE=fish_source foo-bar | source6667 This is the same file used for the activation script method68 below. For Fish it's probably always easier to use that method.69
218 unmodified lines
modified:requirements/dev.txt-2 removed
28 unmodified lines
29 # tox30 # virtualenv31identify==2.5.2432 # via pre-commit33nodeenv==1.8.034 # via pre-commit33pip-compile-multi==2.6.334 # via -r requirements/dev.in35pip-tools==6.13.036 # via pip-compile-multi
26 unmodified lines
modified:requirements/typing.in+1 added
1mypy2pyright
modified:requirements/typing.txt+8 added-1 removed
1# SHA1:7983aaa01d64547827c20395d77e248c41b2572f1# SHA1:0d25c235a98f3c8c55aefb59b91c82834e185f0a2#3# This file is autogenerated by pip-compile-multi4# To update, run:5#
2 unmodified lines
8mypy==1.4.19 # via -r requirements/typing.in10mypy-extensions==1.0.011 # via mypy12nodeenv==1.8.013 # via pyright14pyright==1.1.31715 # via -r requirements/typing.in16typing-extensions==4.6.317 # via mypy1819# The following packages are considered to be unsafe in a requirements file:20# setuptools
modified:src/click/__init__.py+1 added-1 removed
68 unmodified lines
69from .utils import get_binary_stream as get_binary_stream70from .utils import get_text_stream as get_text_stream71from .utils import open_file as open_file7273__version__ = "8.1.4.dev0"73__version__ = "8.1.7"
modified:src/click/_compat.py+13 added-16 removed
5 unmodified lines
6import typing as t7from weakref import WeakKeyDictionary89CYGWIN = sys.platform.startswith("cygwin")10MSYS2 = sys.platform.startswith("win") and ("GCC" in sys.version)11# Determine local App Engine environment, per Google's own suggestion12APP_ENGINE = "APPENGINE_RUNTIME" in os.environ and "Development/" in os.environ.get(13 "SERVER_SOFTWARE", ""14)15WIN = sys.platform.startswith("win") and not APP_ENGINE and not MSYS210WIN = sys.platform.startswith("win")11auto_wrap_for_ansi: t.Optional[t.Callable[[t.TextIO], t.TextIO]] = None12_ansi_re = re.compile(r"\033\[[;?0-9]*[a-zA-Z]")131420def get_filesystem_encoding() -> str:21 return sys.getfilesystemencoding() or sys.getdefaultencoding()222315def _make_text_stream(16 stream: t.BinaryIO,17 encoding: t.Optional[str],18 errors: t.Optional[str],
351 unmodified lines
370 return open(file, mode, encoding=encoding, errors=errors)371372373def open_stream(383 filename: str,374 filename: "t.Union[str, os.PathLike[str]]",375 mode: str = "r",376 encoding: t.Optional[str] = None,377 errors: t.Optional[str] = "strict",378 atomic: bool = False,379) -> t.Tuple[t.IO[t.Any], bool]:380 binary = "b" in mode381 filename = os.fspath(filename)382383 # Standard streams first. These are simple because they ignore the384 # atomic flag. Use fsdecode to handle Path("-").385 if os.fsdecode(filename) == "-":
129 unmodified lines
515 return locale.getpreferredencoding()516517 _ansi_stream_wrappers: t.MutableMapping[t.TextIO, t.TextIO] = WeakKeyDictionary()518527 def auto_wrap_for_ansi(519 def auto_wrap_for_ansi( # noqa: F811520 stream: t.TextIO, color: t.Optional[bool] = None521 ) -> t.TextIO:522 """Support ANSI color and style codes on Windows by wrapping a523 stream with colorama.
31 unmodified lines
555556else:557558 def _get_argv_encoding() -> str:567 return getattr(sys.stdin, "encoding", None) or get_filesystem_encoding()559 return getattr(sys.stdin, "encoding", None) or sys.getfilesystemencoding()560561 def _get_windows_console_stream(562 f: t.TextIO, encoding: t.Optional[str], errors: t.Optional[str]563 ) -> t.Optional[t.TextIO]:
11 unmodified lines
575 return False576577578def _make_cached_stream_func(587 src_func: t.Callable[[], t.TextIO], wrapper_func: t.Callable[[], t.TextIO]588) -> t.Callable[[], t.TextIO]:579 src_func: t.Callable[[], t.Optional[t.TextIO]],580 wrapper_func: t.Callable[[], t.TextIO],581) -> t.Callable[[], t.Optional[t.TextIO]]:582 cache: t.MutableMapping[t.TextIO, t.TextIO] = WeakKeyDictionary()583591 def func() -> t.TextIO:584 def func() -> t.Optional[t.TextIO]:585 stream = src_func()586587 if stream is None:588 return None589590 try:591 rv = cache.get(stream)592 except Exception:593 rv = None
30 unmodified lines
modified:src/click/_termui_impl.py+14 added
8 unmodified lines
9import sys10import time11import typing as t12from gettext import gettext as _13from io import StringIO14from types import TracebackType1516from ._compat import _default_text_stdout17from ._compat import CYGWIN
43 unmodified lines
61 self.show_percent = show_percent62 self.show_pos = show_pos63 self.item_show_func = item_show_func64 self.label: str = label or ""6566 if file is None:67 file = _default_text_stdout()6869 # There are no standard streams attached to write to. For example,70 # pythonw on Windows.71 if file is None:72 file = StringIO()7374 self.file = file75 self.color = color76 self.update_min_steps = update_min_steps77 self._completed_intervals = 0
281 unmodified lines
359360def pager(generator: t.Iterable[str], color: t.Optional[bool] = None) -> None:361 """Decide what method to use for paging through text."""362 stdout = _default_text_stdout()363364 # There are no standard streams attached to write to. For example,365 # pythonw on Windows.366 if stdout is None:367 stdout = StringIO()368369 if not isatty(sys.stdin) or not isatty(stdout):370 return _nullpager(stdout, generator, color)371 pager_cmd = (os.environ.get("PAGER", None) or "").strip()372 if pager_cmd:
367 unmodified lines
modified:src/click/decorators.py+11 added-20 removed
19 unmodified lines
2021R = t.TypeVar("R")22T = t.TypeVar("T")23_AnyCallable = t.Callable[..., t.Any]24_Decorator: "te.TypeAlias" = t.Callable[[T], T]24FC = t.TypeVar("FC", bound=t.Union[_AnyCallable, Command])252627def pass_context(f: "t.Callable[te.Concatenate[Context, P], R]") -> "t.Callable[P, R]":
120 unmodified lines
148) -> t.Callable[[_AnyCallable], CmdType]:149 ...150151153# variant: name omitted, cls _must_ be a keyword argument, @command(cmd=CommandCls, ...)154# The correct way to spell this overload is to use keyword-only argument syntax:155# def command(*, cls: t.Type[CmdType], **attrs: t.Any) -> ...156# However, mypy thinks this doesn't fit the overloaded function. Pyright does157# accept that spelling, and the following work-around makes pyright issue a158# warning that CmdType could be left unsolved, but mypy sees it as fine. *shrug*152# variant: name omitted, cls _must_ be a keyword argument, @command(cls=CommandCls, ...)153@t.overload154def command(155 name: None = None,156 *,162 cls: t.Type[CmdType] = ...,157 cls: t.Type[CmdType],158 **attrs: t.Any,159) -> t.Callable[[_AnyCallable], CmdType]:160 ...161
108 unmodified lines
270 ...271272273# variant: name omitted, cls _must_ be a keyword argument, @group(cmd=GroupCls, ...)279# The _correct_ way to spell this overload is to use keyword-only argument syntax:280# def group(*, cls: t.Type[GrpType], **attrs: t.Any) -> ...281# However, mypy thinks this doesn't fit the overloaded function. Pyright does282# accept that spelling, and the following work-around makes pyright issue a283# warning that GrpType could be left unsolved, but mypy sees it as fine. *shrug*274@t.overload275def group(276 name: None = None,277 *,287 cls: t.Type[GrpType] = ...,278 cls: t.Type[GrpType],279 **attrs: t.Any,280) -> t.Callable[[_AnyCallable], GrpType]:281 ...282
38 unmodified lines
321322323def argument(324 *param_decls: str, cls: t.Optional[t.Type[Argument]] = None, **attrs: t.Any334) -> _Decorator[FC]:325) -> t.Callable[[FC], FC]:326 """Attaches an argument to the command. All positional arguments are327 passed as parameter declarations to :class:`Argument`; all keyword328 arguments are forwarded unchanged (except ``cls``).329 This is equivalent to creating an :class:`Argument` instance manually
19 unmodified lines
349350351def option(352 *param_decls: str, cls: t.Optional[t.Type[Option]] = None, **attrs: t.Any362) -> _Decorator[FC]:353) -> t.Callable[[FC], FC]:354 """Attaches an option to the command. All positional arguments are355 passed as parameter declarations to :class:`Option`; all keyword356 arguments are forwarded unchanged (except ``cls``).357 This is equivalent to creating an :class:`Option` instance manually
17 unmodified lines
375376 return decorator377378388def confirmation_option(*param_decls: str, **kwargs: t.Any) -> _Decorator[FC]:379def confirmation_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]:380 """Add a ``--yes`` option which shows a prompt before continuing if381 not passed. If the prompt is declined, the program will exit.382383 :param param_decls: One or more option names. Defaults to the single
15 unmodified lines
399 kwargs.setdefault("help", "Confirm the action without prompting.")400 return option(*param_decls, **kwargs)401402412def password_option(*param_decls: str, **kwargs: t.Any) -> _Decorator[FC]:403def password_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]:404 """Add a ``--password`` option which prompts for a password, hiding405 input and asking to enter the value again for confirmation.406407 :param param_decls: One or more option names. Defaults to the single
15 unmodified lines
423 package_name: t.Optional[str] = None,424 prog_name: t.Optional[str] = None,425 message: t.Optional[str] = None,426 **kwargs: t.Any,436) -> _Decorator[FC]:427) -> t.Callable[[FC], FC]:428 """Add a ``--version`` option which immediately prints the version429 number and exits the program.430431 If ``version`` is not provided, Click will try to detect it using
97 unmodified lines
529 kwargs["callback"] = callback530 return option(*param_decls, **kwargs)531532542def help_option(*param_decls: str, **kwargs: t.Any) -> _Decorator[FC]:533def help_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]:534 """Add a ``--help`` option which immediately prints the help page535 and exits the program.536537 This is usually unnecessary, as the ``--help`` option is added to
24 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/shell_completion.py+25 added-21 removed
165 unmodified lines
166fi167"""168169_SOURCE_FISH = """\170function %(complete_func)s170function %(complete_func)s;171 set -l response (env %(complete_var)s=fish_complete COMP_WORDS=(commandline -cp) \172COMP_CWORD=(commandline -t) %(prog_name)s)172COMP_CWORD=(commandline -t) %(prog_name)s);173174 for completion in $response175 set -l metadata (string split "," $completion)174 for completion in $response;175 set -l metadata (string split "," $completion);176177 if test $metadata[1] = "dir"178 __fish_complete_directories $metadata[2]179 else if test $metadata[1] = "file"180 __fish_complete_path $metadata[2]181 else if test $metadata[1] = "plain"182 echo $metadata[2]183 end184 end185end177 if test $metadata[1] = "dir";178 __fish_complete_directories $metadata[2];179 else if test $metadata[1] = "file";180 __fish_complete_path $metadata[2];181 else if test $metadata[1] = "plain";182 echo $metadata[2];183 end;184 end;185end;186187complete --no-files --command %(prog_name)s --arguments \188"(%(complete_func)s)"188"(%(complete_func)s)";189"""190191192class ShellComplete:
36 unmodified lines
229 def func_name(self) -> str:230 """The name of the shell function defined by the completion231 script.232 """233 safe_name = re.sub(r"\W*", "", self.prog_name.replace("-", "_"), re.ASCII)233 safe_name = re.sub(r"\W*", "", self.prog_name.replace("-", "_"), flags=re.ASCII)234 return f"_{safe_name}_completion"235236 def source_vars(self) -> t.Dict[str, t.Any]:237 """Vars for formatting :attr:`source_template`.
62 unmodified lines
300301 name = "bash"302 source_template = _SOURCE_BASH303304 @staticmethod304 def _check_version(self) -> None:305 def _check_version() -> None:306 import subprocess307308 output = subprocess.run(309 ["bash", "-c", 'echo "${BASH_VERSION}"'], stdout=subprocess.PIPE
3 unmodified lines
313 if match is not None:314 major, minor = match.groups()315316 if major < "4" or major == "4" and minor < "4":316 raise RuntimeError(317 echo(318 _(319 "Shell completion is not supported for Bash"320 " versions older than 4.4."320 )321 ),322 err=True,323 )324 else:323 raise RuntimeError(324 _("Couldn't detect Bash version, shell completion is not supported.")325 echo(326 _("Couldn't detect Bash version, shell completion is not supported."),327 err=True,328 )329330 def source(self) -> str:331 self._check_version()
113 unmodified lines
445 if not isinstance(param, Argument):446 return False447448 assert param.name is not None446 value = ctx.params[param.name]449 # Will be None if expose_value is False.450 value = ctx.params.get(param.name)451 return (452 param.nargs == -1453 or ctx.get_parameter_source(param.name) is not ParameterSource.COMMANDLINE454 or (
142 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+39 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
115 unmodified lines
266 file = _default_text_stderr()267 else:268 file = _default_text_stdout()269270 # There are no standard streams attached to write to. For example,271 # pythonw on Windows.272 if file is None:273 return274275 # Convert non bytes/text into the native string type.276 if message is not None and not isinstance(message, (str, bytes, bytearray)):277 out: t.Optional[t.Union[str, bytes]] = str(message)278 else:
122 unmodified lines
401 return f402403404def format_filename(401 filename: t.Union[str, bytes, "os.PathLike[t.AnyStr]"], shorten: bool = False405 filename: "t.Union[str, bytes, os.PathLike[str], os.PathLike[bytes]]",406 shorten: bool = False,407) -> 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.408 """Format a filename as a string for display. Ensures the filename can be409 displayed by replacing any invalid bytes or surrogate escapes in the name410 with the replacement character ``�``.411412 Invalid bytes or surrogate escapes will raise an error when written to a413 stream with ``errors="strict". This will typically happen with ``stdout``414 when the locale is something like ``en_GB.UTF-8``.415416 Many scenarios *are* safe to write surrogates though, due to PEP 538 and417 PEP 540, including:418419 - Writing to ``stderr``, which uses ``errors="backslashreplace"``.420 - The system has ``LANG=C.UTF-8``, ``C``, or ``POSIX``. Python opens421 stdout and stderr with ``errors="surrogateescape"``.422 - None of ``LANG/LC_*`` are set. Python assumes ``LANG=C.UTF-8``.423 - Python is started in UTF-8 mode with ``PYTHONUTF8=1`` or ``-X utf8``.424 Python opens stdout and stderr with ``errors="surrogateescape"``.425426 :param filename: formats a filename for UI display. This will also convert427 the filename into unicode without failing.428 :param shorten: this optionally shortens the filename to strip of the429 path that leads up to it.430 """431 if shorten:432 filename = os.path.basename(filename)433 else:434 filename = os.fspath(filename)435417 return os.fsdecode(filename)436 if isinstance(filename, bytes):437 filename = filename.decode(sys.getfilesystemencoding(), "replace")438 else:439 filename = filename.encode("utf-8", "surrogateescape").decode(440 "utf-8", "replace"441 )442443 return filename444445446def get_app_dir(app_name: str, roaming: bool = True, force_posix: bool = False) -> str:447 r"""Returns the config folder for the application. The default behavior448 is to return whatever is most appropriate for the operating system.449
175 unmodified lines
added:tests/typing/typing_aliased_group.py+45 added
1"""Example from https://click.palletsprojects.com/en/8.1.x/advanced/#command-aliases"""2from __future__ import annotations34from typing_extensions import assert_type56import click789class AliasedGroup(click.Group):10 def get_command(self, ctx: click.Context, cmd_name: str) -> click.Command | None:11 rv = click.Group.get_command(self, ctx, cmd_name)12 if rv is not None:13 return rv14 matches = [x for x in self.list_commands(ctx) if x.startswith(cmd_name)]15 if not matches:16 return None17 elif len(matches) == 1:18 return click.Group.get_command(self, ctx, matches[0])19 ctx.fail(f"Too many matches: {', '.join(sorted(matches))}")2021 def resolve_command(22 self, ctx: click.Context, args: list[str]23 ) -> tuple[str | None, click.Command, list[str]]:24 # always return the full command name25 _, cmd, args = super().resolve_command(ctx, args)26 assert cmd is not None27 return cmd.name, cmd, args282930@click.command(cls=AliasedGroup)31def cli() -> None:32 pass333435assert_type(cli, AliasedGroup)363738@cli.command()39def push() -> None:40 pass414243@cli.command()44def pop() -> None:45 pass
added:tests/typing/typing_confirmation_option.py+13 added
1"""From https://click.palletsprojects.com/en/8.1.x/options/#yes-parameters"""2from typing_extensions import assert_type34import click567@click.command()8@click.confirmation_option(prompt="Are you sure you want to drop the db?")9def dropdb() -> None:10 click.echo("Dropped all tables!")111213assert_type(dropdb, click.Command)
added:tests/typing/typing_group_kw_options.py+11 added
1from typing_extensions import assert_type23import click456@click.group(context_settings={})7def hello() -> None:8 pass91011assert_type(hello, click.Group)
added:tests/typing/typing_help_option.py+13 added
1from typing_extensions import assert_type23import click456@click.command()7@click.help_option("-h", "--help")8def hello() -> None:9 """Simple program that greets NAME for a total of COUNT times."""10 click.echo("Hello!")111213assert_type(hello, click.Command)
added:tests/typing/typing_options.py+15 added
1"""From https://click.palletsprojects.com/en/8.1.x/quickstart/#adding-parameters"""2from typing_extensions import assert_type34import click567@click.command()8@click.option("--count", default=1, help="number of greetings")9@click.argument("name")10def hello(count: int, name: str) -> None:11 for _ in range(count):12 click.echo(f"Hello {name}!")131415assert_type(hello, click.Command)
added:tests/typing/typing_password_option.py+14 added
1import codecs23from typing_extensions import assert_type45import click678@click.command()9@click.password_option()10def encrypt(password: str) -> None:11 click.echo(f"encoded: to {codecs.encode(password, 'rot13')}")121314assert_type(encrypt, click.Command)
added:tests/typing/typing_simple_example.py+16 added
1"""The simple example from https://github.com/pallets/click#a-simple-example."""2from typing_extensions import assert_type34import click567@click.command()8@click.option("--count", default=1, help="Number of greetings.")9@click.option("--name", prompt="Your name", help="The person to greet.")10def hello(count: int, name: str) -> None:11 """Simple program that greets NAME for a total of COUNT times."""12 for _ in range(count):13 click.echo(f"Hello, {name}!")141516assert_type(hello, click.Command)
added:tests/typing/typing_version_option.py+15 added
1"""2From https://click.palletsprojects.com/en/8.1.x/options/#callbacks-and-eager-options.3"""4from typing_extensions import assert_type56import click789@click.command()10@click.version_option("0.1")11def hello() -> None:12 click.echo("Hello World!")131415assert_type(hello, click.Command)
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+10 added-4 removed
41 unmodified lines
42 click.echo("hello", file=f)43 assert f.getvalue() == "hello\n"444546def test_echo_no_streams(monkeypatch, runner):47 """echo should not fail when stdout and stderr are None with pythonw on Windows."""48 with runner.isolation():49 sys.stdout = None50 sys.stderr = None51 click.echo("test")52 click.echo("test", err=True)535455@pytest.mark.parametrize(56 ("styles", "ref"),57 [58 ({"fg": "black"}, "\x1b[30mx y\x1b[0m"),
47 unmodified lines
106 assert click.format_filename(b"foo.txt") == "foo.txt"107 assert click.format_filename(b"/x/foo.txt") == "/x/foo.txt"108 assert click.format_filename("/x/foo.txt") == "/x/foo.txt"109 assert click.format_filename("/x/foo.txt", shorten=True) == "foo.txt"110 assert click.format_filename(b"/x/\xff.txt", shorten=True) == "�.txt"111102 # 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"112106113def test_prompts(runner):114 @click.command()115 def test():116 if click.confirm("Foo"):
391 unmodified lines
modified:.pre-commit-config.yaml+3 added-3 removed
1 unmodified line
2 autoupdate_branch: "8.1.x"3 autoupdate_schedule: monthly4repos:5 - repo: https://github.com/asottile/pyupgrade6 rev: v3.7.06 rev: v3.10.17 hooks:8 - id: pyupgrade9 args: ["--py37-plus"]10 - repo: https://github.com/asottile/reorder-python-imports
1 unmodified line
12 hooks:13 - id: reorder-python-imports14 args: ["--application-directories", "src"]15 - repo: https://github.com/psf/black16 rev: 23.3.016 rev: 23.7.017 hooks:18 - id: black19 - repo: https://github.com/PyCQA/flake820 rev: 6.0.020 rev: 6.1.021 hooks:22 - id: flake823 additional_dependencies:24 - flake8-bugbear
7 unmodified lines
modified:CHANGES.rst+35 added-1 removed
1.. currentmodule:: click23Version 8.1.74-------------56Released 2023-08-1778- Fix issue with regex flags in shell completion. :issue:`2581`9- Bash version detection issues a warning instead of an error. :issue:`2574`10- Fix issue with completion script for Fish shell. :issue:`2567`111213Version 8.1.614-------------1516Released 2023-07-181718- Fix an issue with type hints for ``@click.group()``. :issue:`2558`192021Version 8.1.522-------------2324Released 2023-07-132526- Fix an issue with type hints for ``@click.command()``, ``@click.option()``, and27 other decorators. Introduce typing tests. :issue:`2558`282930Version 8.1.431-------------326Unreleased33Released 2023-07-063435- Replace all ``typing.Dict`` occurrences to ``typing.MutableMapping`` for36 parameter hints. :issue:`2255`37- Improve type hinting for decorators and give all generic types parameters.
14 unmodified lines
52- ``multiple=True`` is allowed for flag options again and does not require53 setting ``default=()``. :issue:`2246, 2292, 2295`54- Make the decorators returned by ``@argument()`` and ``@option()`` reusable when the55 ``cls`` parameter is used. :issue:`2294`56- Don't fail when writing filenames to streams with strict errors. Replace invalid57 bytes with the replacement character (``�``). :issue:`2395`58- Remove unnecessary attempt to detect MSYS2 environment. :issue:`2355`59- Remove outdated and unnecessary detection of App Engine environment. :pr:`2554`60- ``echo()`` does not fail when no streams are attached, such as with ``pythonw`` on61 Windows. :issue:`2415`62- Argument with ``expose_value=False`` do not cause completion to fail. :issue:`2336`636465Version 8.1.366-------------
1040 unmodified lines
modified:setup.cfg+1 added-1 removed
76 unmodified lines
77 # __init__ exports names78 src/click/__init__.py: F4017980[mypy]81files = src/click81files = src/click, tests/typing82python_version = 3.783show_error_codes = True84disallow_subclassing_any = True85disallow_untyped_calls = True
19 unmodified lines
modified:tox.ini+4 added-1 removed
18 unmodified lines
19commands = pre-commit run --all-files2021[testenv:typing]22deps = -r requirements/typing.txt23commands = mypy23commands =24 mypy25 pyright --verifytypes click26 pyright tests/typing2728[testenv:docs]29deps = -r requirements/docs.txt30commands = sphinx-build -W -b html -d {envtmpdir}/doctrees docs {envtmpdir}/html