Skip to content
Myr

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

18 files+221 added−49 removed

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/_compat.py+1 added-1 removed
514 unmodified lines
515 return locale.getpreferredencoding()516517 _ansi_stream_wrappers: t.MutableMapping[t.TextIO, t.TextIO] = WeakKeyDictionary()518519 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 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/shell_completion.py+23 added-20 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()
265 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:.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.8.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+27 added
8 unmodified lines
9 :pr:`326`10- Use ``flit_core`` instead of ``setuptools`` as build backend.111213Version 8.1.714-------------1516Released 2023-08-171718- 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`212223Version 8.1.624-------------2526Released 2023-07-182728- Fix an issue with type hints for ``@click.group()``. :issue:`2558`293031Version 8.1.532-------------3334Released 2023-07-133536- Fix an issue with type hints for ``@click.command()``, ``@click.option()``, and37 other decorators. Introduce typing tests. :issue:`2558`383940Version 8.1.441-------------4243Released 2023-07-06
1073 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