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
Provenance
- Commit
5a6cde9- Tree
0ea3c05- Author
unknown <edward.g2013@gmail.com>- Committer
unknown <edward.g2013@gmail.com>- Parent 1
03f5496- Parent 2
6986b08
29 files changed+471 added−154 removed
modified:.github/workflows/publish.yaml+10 added-10 removed
7 unmodified lines891011121312131415161714 unmodified lines3233343536363738394016 unmodified lines57585960616263646564666766676869686970717172727 unmodified lines runs-on: ubuntu-latest outputs: hash: ${{ steps.hash.outputs.hash }} steps: - uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c - uses: actions/setup-python@5ccb29d8773c3f3f653e1705f474dfaa8a06a912 - uses: actions/checkout@8f4b7f84864484a7bf31766abe9204da3cbe65b3 - uses: actions/setup-python@d27e3f3d7c64b4bbf8e4abfb9b63b83e846e0435 with: python-version: '3.x' cache: 'pip' cache-dependency-path: 'requirements/*.txt'14 unmodified lines actions: read id-token: write contents: write # Can't pin with hash due to how this workflow works. uses: slsa-framework/slsa-github-generator/.github/workflows/generator_generic_slsa3.yml@v1.4.0 uses: slsa-framework/slsa-github-generator/.github/workflows/generator_generic_slsa3.yml@v1.7.0 with: base64-subjects: ${{ needs.build.outputs.hash }} create-release: # Upload the sdist, wheels, and provenance to a GitHub release. They remain16 unmodified lines # Wait for approval before attempting to upload to PyPI. This allows reviewing the # files in the draft release. environment: 'publish' runs-on: ubuntu-latest permissions: id-token: write steps: - uses: actions/download-artifact@9bc31d5ccc31df68ecc42ccf4149144866c47d8a # Try uploading to Test PyPI first, in case something fails. - uses: pypa/gh-action-pypi-publish@c7f29f7adef1a245bd91520e94867e5c6eedddcc - uses: pypa/gh-action-pypi-publish@29930c9cf57955dc1b98162d0d8bc3ec80d9e75c with: password: ${{ secrets.TEST_PYPI_TOKEN }} repository_url: https://test.pypi.org/legacy/ packages_dir: artifact/ - uses: pypa/gh-action-pypi-publish@c7f29f7adef1a245bd91520e94867e5c6eedddcc repository-url: https://test.pypi.org/legacy/ packages-dir: artifact/ - uses: pypa/gh-action-pypi-publish@29930c9cf57955dc1b98162d0d8bc3ec80d9e75c with: password: ${{ secrets.PYPI_TOKEN }} packages_dir: artifact/ packages-dir: artifact/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:docs/shell-completion.rst+1 added-1 removed
60 unmodified lines61 Add this to ``~/.config/fish/completions/foo-bar.fish``:62 63 .. code-block:: fish64 65- eval (env _FOO_BAR_COMPLETE=fish_source foo-bar)65+ _FOO_BAR_COMPLETE=fish_source foo-bar | source66 67 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 linesmodified:requirements/dev.txt-2 removed
28 unmodified lines29 # tox30 # virtualenv31 identify==2.5.2432 # via pre-commit33-nodeenv==1.8.034- # via pre-commit33 pip-compile-multi==2.6.334 # via -r requirements/dev.in35 pip-tools==6.13.036 # via pip-compile-multi26 unmodified linesmodified:requirements/typing.in+1 added
1 mypy2+pyrightmodified: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 lines8 mypy==1.4.19 # via -r requirements/typing.in10 mypy-extensions==1.0.011 # via mypy12+nodeenv==1.8.013+ # via pyright14+pyright==1.1.31715+ # via -r requirements/typing.in16 typing-extensions==4.6.317 # via mypy18+19+# The following packages are considered to be unsafe in a requirements file:20+# setuptoolsmodified:src/click/__init__.py+1 added-1 removed
68 unmodified lines69 from .utils import get_binary_stream as get_binary_stream70 from .utils import get_text_stream as get_text_stream71 from .utils import open_file as open_file72 73-__version__ = "8.1.4.dev0"73+__version__ = "8.1.7"modified:src/click/_compat.py+13 added-16 removed
5 unmodified lines6 import typing as t7 from weakref import WeakKeyDictionary8 9 CYGWIN = sys.platform.startswith("cygwin")10-MSYS2 = sys.platform.startswith("win") and ("GCC" in sys.version)11-# Determine local App Engine environment, per Google's own suggestion12-APP_ENGINE = "APPENGINE_RUNTIME" in os.environ and "Development/" in os.environ.get(13- "SERVER_SOFTWARE", ""14-)15-WIN = sys.platform.startswith("win") and not APP_ENGINE and not MSYS210+WIN = sys.platform.startswith("win")11 auto_wrap_for_ansi: t.Optional[t.Callable[[t.TextIO], t.TextIO]] = None12 _ansi_re = re.compile(r"\033\[[;?0-9]*[a-zA-Z]")13 14 20-def get_filesystem_encoding() -> str:21- return sys.getfilesystemencoding() or sys.getdefaultencoding()22-23-15 def _make_text_stream(16 stream: t.BinaryIO,17 encoding: t.Optional[str],18 errors: t.Optional[str],351 unmodified lines370 return open(file, mode, encoding=encoding, errors=errors)371 372 373 def 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)382 383 # Standard streams first. These are simple because they ignore the384 # atomic flag. Use fsdecode to handle Path("-").385 if os.fsdecode(filename) == "-":129 unmodified lines515 return locale.getpreferredencoding()516 517 _ansi_stream_wrappers: t.MutableMapping[t.TextIO, t.TextIO] = WeakKeyDictionary()518 527- 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 lines555 556 else:557 558 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()560 561 def _get_windows_console_stream(562 f: t.TextIO, encoding: t.Optional[str], errors: t.Optional[str]563 ) -> t.Optional[t.TextIO]:11 unmodified lines575 return False576 577 578 def _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()583 591- def func() -> t.TextIO:584+ def func() -> t.Optional[t.TextIO]:585 stream = src_func()586+587+ if stream is None:588+ return None589+590 try:591 rv = cache.get(stream)592 except Exception:593 rv = None30 unmodified linesmodified:src/click/_termui_impl.py+14 added
8 unmodified lines9 import sys10 import time11 import typing as t12 from gettext import gettext as _13+from io import StringIO14 from types import TracebackType15 16 from ._compat import _default_text_stdout17 from ._compat import CYGWIN43 unmodified lines61 self.show_percent = show_percent62 self.show_pos = show_pos63 self.item_show_func = item_show_func64 self.label: str = label or ""65+66 if file is None:67 file = _default_text_stdout()68+69+ # There are no standard streams attached to write to. For example,70+ # pythonw on Windows.71+ if file is None:72+ file = StringIO()73+74 self.file = file75 self.color = color76 self.update_min_steps = update_min_steps77 self._completed_intervals = 0281 unmodified lines359 360 def 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()363+364+ # There are no standard streams attached to write to. For example,365+ # pythonw on Windows.366+ if stdout is None:367+ stdout = StringIO()368+369 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 linesmodified:src/click/decorators.py+11 added-20 removed
19 unmodified lines20 21 R = t.TypeVar("R")22 T = t.TypeVar("T")23 _AnyCallable = t.Callable[..., t.Any]24-_Decorator: "te.TypeAlias" = t.Callable[[T], T]24 FC = t.TypeVar("FC", bound=t.Union[_AnyCallable, Command])25 26 27 def pass_context(f: "t.Callable[te.Concatenate[Context, P], R]") -> "t.Callable[P, R]":120 unmodified lines148 ) -> t.Callable[[_AnyCallable], CmdType]:149 ...150 151 153-# 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.overload154 def 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 lines270 ...271 272 273 # 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.overload275 def 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 lines321 322 323 def 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 manually19 unmodified lines349 350 351 def 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 manually17 unmodified lines375 376 return decorator377 378 388-def confirmation_option(*param_decls: str, **kwargs: t.Any) -> _Decorator[FC]:379+def 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.382 383 :param param_decls: One or more option names. Defaults to the single15 unmodified lines399 kwargs.setdefault("help", "Confirm the action without prompting.")400 return option(*param_decls, **kwargs)401 402 412-def password_option(*param_decls: str, **kwargs: t.Any) -> _Decorator[FC]:403+def 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.406 407 :param param_decls: One or more option names. Defaults to the single15 unmodified lines423 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.430 431 If ``version`` is not provided, Click will try to detect it using97 unmodified lines529 kwargs["callback"] = callback530 return option(*param_decls, **kwargs)531 532 542-def help_option(*param_decls: str, **kwargs: t.Any) -> _Decorator[FC]:533+def 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.536 537 This is usually unnecessary, as the ``--help`` option is added to24 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/shell_completion.py+25 added-21 removed
165 unmodified lines166 fi167 """168 169 _SOURCE_FISH = """\170-function %(complete_func)s170+function %(complete_func)s;171 set -l response (env %(complete_var)s=fish_complete COMP_WORDS=(commandline -cp) \172-COMP_CWORD=(commandline -t) %(prog_name)s)172+COMP_CWORD=(commandline -t) %(prog_name)s);173 174- for completion in $response175- set -l metadata (string split "," $completion)174+ for completion in $response;175+ set -l metadata (string split "," $completion);176 177- 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- end185-end177+ 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;185+end;186 187 complete --no-files --command %(prog_name)s --arguments \188-"(%(complete_func)s)"188+"(%(complete_func)s)";189 """190 191 192 class ShellComplete:36 unmodified lines229 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"235 236 def source_vars(self) -> t.Dict[str, t.Any]:237 """Vars for formatting :attr:`source_template`.62 unmodified lines300 301 name = "bash"302 source_template = _SOURCE_BASH303 304+ @staticmethod304- def _check_version(self) -> None:305+ def _check_version() -> None:306 import subprocess307 308 output = subprocess.run(309 ["bash", "-c", 'echo "${BASH_VERSION}"'], stdout=subprocess.PIPE3 unmodified lines313 if match is not None:314 major, minor = match.groups()315 316 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 )329 330 def source(self) -> str:331 self._check_version()113 unmodified lines445 if not isinstance(param, Argument):446 return False447 448 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 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+39 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 error115 unmodified lines266 file = _default_text_stderr()267 else:268 file = _default_text_stdout()269 270+ # There are no standard streams attached to write to. For example,271+ # pythonw on Windows.272+ if file is None:273+ return274+275 # 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 lines401 return f402 403 404 def 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 ``�``.411 412+ 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``.415+416+ Many scenarios *are* safe to write surrogates though, due to PEP 538 and417+ PEP 540, including:418+419+ - 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"``.425+426 :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)435 417- 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+ )442 443+ return filename444 445+446 def 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 linesadded:tests/typing/typing_aliased_group.py+45 added
1+"""Example from https://click.palletsprojects.com/en/8.1.x/advanced/#command-aliases"""2+from __future__ import annotations3+4+from typing_extensions import assert_type5+6+import click7+8+9+class 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))}")20+21+ 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, args28+29+30+@click.command(cls=AliasedGroup)31+def cli() -> None:32+ pass33+34+35+assert_type(cli, AliasedGroup)36+37+38+@cli.command()39+def push() -> None:40+ pass41+42+43+@cli.command()44+def pop() -> None:45+ passadded:tests/typing/typing_confirmation_option.py+13 added
1+"""From https://click.palletsprojects.com/en/8.1.x/options/#yes-parameters"""2+from typing_extensions import assert_type3+4+import click5+6+7+@click.command()8+@click.confirmation_option(prompt="Are you sure you want to drop the db?")9+def dropdb() -> None:10+ click.echo("Dropped all tables!")11+12+13+assert_type(dropdb, click.Command)added:tests/typing/typing_group_kw_options.py+11 added
1+from typing_extensions import assert_type2+3+import click4+5+6+@click.group(context_settings={})7+def hello() -> None:8+ pass9+10+11+assert_type(hello, click.Group)added:tests/typing/typing_help_option.py+13 added
1+from typing_extensions import assert_type2+3+import click4+5+6+@click.command()7+@click.help_option("-h", "--help")8+def hello() -> None:9+ """Simple program that greets NAME for a total of COUNT times."""10+ click.echo("Hello!")11+12+13+assert_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"""2+from typing_extensions import assert_type3+4+import click5+6+7+@click.command()8+@click.option("--count", default=1, help="number of greetings")9+@click.argument("name")10+def hello(count: int, name: str) -> None:11+ for _ in range(count):12+ click.echo(f"Hello {name}!")13+14+15+assert_type(hello, click.Command)added:tests/typing/typing_password_option.py+14 added
1+import codecs2+3+from typing_extensions import assert_type4+5+import click6+7+8+@click.command()9+@click.password_option()10+def encrypt(password: str) -> None:11+ click.echo(f"encoded: to {codecs.encode(password, 'rot13')}")12+13+14+assert_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."""2+from typing_extensions import assert_type3+4+import click5+6+7+@click.command()8+@click.option("--count", default=1, help="Number of greetings.")9+@click.option("--name", prompt="Your name", help="The person to greet.")10+def 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}!")14+15+16+assert_type(hello, click.Command)added:tests/typing/typing_version_option.py+15 added
1+"""2+From https://click.palletsprojects.com/en/8.1.x/options/#callbacks-and-eager-options.3+"""4+from typing_extensions import assert_type5+6+import click7+8+9+@click.command()10+@click.version_option("0.1")11+def hello() -> None:12+ click.echo("Hello World!")13+14+15+assert_type(hello, click.Command)modified: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+10 added-4 removed
41 unmodified lines42 click.echo("hello", file=f)43 assert f.getvalue() == "hello\n"44 45 46+def 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)53+54+55 @pytest.mark.parametrize(56 ("styles", "ref"),57 [58 ({"fg": "black"}, "\x1b[30mx y\x1b[0m"),47 unmodified lines106 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"111 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"112 106-113 def test_prompts(runner):114 @click.command()115 def test():116 if click.confirm("Foo"):391 unmodified linesmodified:.pre-commit-config.yaml+3 added-3 removed
1 unmodified line2 autoupdate_branch: "8.1.x"3 autoupdate_schedule: monthly4 repos: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-imports1 unmodified line12 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-bugbear7 unmodified linesmodified:CHANGES.rst+35 added-1 removed
1 .. currentmodule:: click2 3+Version 8.1.74+-------------5+6+Released 2023-08-177+8+- 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`11+12+13+Version 8.1.614+-------------15+16+Released 2023-07-1817+18+- Fix an issue with type hints for ``@click.group()``. :issue:`2558`19+20+21+Version 8.1.522+-------------23+24+Released 2023-07-1325+26+- Fix an issue with type hints for ``@click.command()``, ``@click.option()``, and27+ other decorators. Introduce typing tests. :issue:`2558`28+29+30 Version 8.1.431 -------------32 6-Unreleased33+Released 2023-07-0634 35 - 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 lines52 - ``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`63 64 65 Version 8.1.366 -------------1040 unmodified linesmodified:setup.cfg+1 added-1 removed
76 unmodified lines77 # __init__ exports names78 src/click/__init__.py: F40179 80 [mypy]81-files = src/click81+files = src/click, tests/typing82 python_version = 3.783 show_error_codes = True84 disallow_subclassing_any = True85 disallow_untyped_calls = True19 unmodified linesmodified:tox.ini+4 added-1 removed
18 unmodified lines19 commands = pre-commit run --all-files20 21 [testenv:typing]22 deps = -r requirements/typing.txt23-commands = mypy23+commands =24+ mypy25+ pyright --verifytypes click26+ pyright tests/typing27 28 [testenv:docs]29 deps = -r requirements/docs.txt30 commands = sphinx-build -W -b html -d {envtmpdir}/doctrees docs {envtmpdir}/html