Merge branch '8.1.x'
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by David Lord · parents 388b0e1, 6986b08 · Browse files · 18 files·+221 added−49 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
18 files+221 added−49 removed
- tests:+142 added−0 removed
- other:+79 added−49 removed
Provenance
- Commit
b765b12- Tree
86f8e22- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent 1
388b0e1- Parent 2
6986b08
18 files changed+221 added−49 removed
modified: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/_compat.py+1 added-1 removed
514 unmodified lines515 return locale.getpreferredencoding()516 517 _ansi_stream_wrappers: t.MutableMapping[t.TextIO, t.TextIO] = WeakKeyDictionary()518 519- 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.100 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/shell_completion.py+23 added-20 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()265 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:.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.8.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+27 added
8 unmodified lines9 :pr:`326`10 - Use ``flit_core`` instead of ``setuptools`` as build backend.11 12 13+Version 8.1.714+-------------15+16+Released 2023-08-1717+18+- Fix issue with regex flags in shell completion. :issue:`2581`19+- Bash version detection issues a warning instead of an error. :issue:`2574`20+- Fix issue with completion script for Fish shell. :issue:`2567`21+22+23+Version 8.1.624+-------------25+26+Released 2023-07-1827+28+- Fix an issue with type hints for ``@click.group()``. :issue:`2558`29+30+31+Version 8.1.532+-------------33+34+Released 2023-07-1335+36+- Fix an issue with type hints for ``@click.command()``, ``@click.option()``, and37+ other decorators. Introduce typing tests. :issue:`2558`38+39+40 Version 8.1.441 -------------42 43 Released 2023-07-061073 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