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 b0538df, ac15816 · Browse files · 17 files·+155 added−60 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
17 files+155 added−60 removed
- tests:+74 added−1 removed
- other:+81 added−59 removed
Provenance
- Commit
7271763- Tree
01bd8c2- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent 1
b0538df- Parent 2
ac15816
17 files changed+155 added−60 removed
modified:docs/advanced.rst+3 added-3 removed
77 unmodified lines78 object has a :attr:`~Context.params` attribute which is a dictionary of79 all parameters. Whatever is in that dictionary is being passed to the80 callbacks.81 82-This can be used to make up addition parameters. Generally this pattern82+This can be used to make up additional parameters. Generally this pattern83 is not recommended but in some cases it can be useful. At the very least84 it's good to know that the system works this way.85 86 .. click:example::194 unmodified lines281 you also set :attr:`~Context.allow_extra_args` as otherwise the282 command will abort with an error that there are leftover arguments.283 If you go with this solution, the extra arguments will be collected in284 :attr:`Context.args`.285-2. You can attach a :func:`argument` with ``nargs`` set to `-1` which285+2. You can attach an :func:`argument` with ``nargs`` set to `-1` which286 will eat up all leftover arguments. In this case it's recommended to287 set the `type` to :data:`UNPROCESSED` to avoid any string processing288 on those arguments as otherwise they are forced into unicode strings289 automatically which is often not what you want.48 unmodified lines338 (:attr:`~Context.allow_interspersed_args`) which instructs the parser339 to not allow arguments and options to be mixed. Depending on your340 situation this might improve your results.341 342-Generally though the combinated handling of options and arguments from342+Generally though the combined handling of options and arguments from343 your own commands and commands from another application are discouraged344 and if you can avoid it, you should. It's a much better idea to have345 everything below a subcommand be forwarded to another application than to346 handle some arguments yourself.142 unmodified linesmodified:docs/conf.py-2 removed
36 unmodified lines37 ProjectLink("Donate", "https://palletsprojects.com/donate"),38 ProjectLink("PyPI Releases", "https://pypi.org/project/click/"),39 ProjectLink("Source Code", "https://github.com/pallets/click/"),40 ProjectLink("Issue Tracker", "https://github.com/pallets/click/issues/"),41- ProjectLink("Website", "https://palletsprojects.com/p/click"),42- ProjectLink("Twitter", "https://twitter.com/PalletsTeam"),41 ProjectLink("Chat", "https://discord.gg/pallets"),42 ]43 }44 html_sidebars = {13 unmodified linesmodified:requirements/build.txt+1 added-3 removed
4 unmodified lines5 #6 # pip-compile-multi7 #8 build==0.10.09- # via -r requirements\build.in10-colorama==0.4.611- # via build9+ # via -r requirements/build.in10 packaging==23.111 # via build12 pyproject-hooks==1.0.013 # via build2 unmodified linesmodified:requirements/dev.txt+12 added-10 removed
8 unmodified lines9 -r tests.txt10 -r typing.txt11 build==0.10.012 # via pip-tools13-cachetools==5.3.013+cachetools==5.3.114 # via tox15 cfgv==3.3.116 # via pre-commit17 chardet==5.1.01 unmodified line19 click==8.1.320 # via21 # pip-compile-multi22 # pip-tools23+colorama==0.4.624+ # via tox25 distlib==0.3.626 # via virtualenv27 filelock==3.12.028 # via29 # tox30 # virtualenv29-identify==2.5.2331+identify==2.5.2432 # via pre-commit31-nodeenv==1.7.033+nodeenv==1.8.034 # via pre-commit33-pip-compile-multi==2.6.234- # via -r requirements\dev.in35+pip-compile-multi==2.6.336+ # via -r requirements/dev.in37 pip-tools==6.13.038 # via pip-compile-multi37-platformdirs==3.5.039+platformdirs==3.5.140 # via41 # tox42 # virtualenv41-pre-commit==3.3.142- # via -r requirements\dev.in43+pre-commit==3.3.244+ # via -r requirements/dev.in45 pyproject-api==1.5.146 # via tox47 pyproject-hooks==1.0.048 # via build49 pyyaml==6.050 # via pre-commit51 toposort==1.1052 # via pip-compile-multi51-tox==4.5.152- # via -r requirements\dev.in53+tox==4.5.254+ # via -r requirements/dev.in55 virtualenv==20.23.056 # via57 # pre-commit58 # tox6 unmodified linesmodified:requirements/docs.txt+9 added-11 removed
7 unmodified lines8 alabaster==0.7.139 # via sphinx10 babel==2.12.111 # via sphinx12-certifi==2022.12.712+certifi==2023.5.713 # via requests14 charset-normalizer==3.1.015 # via requests16-colorama==0.4.617- # via sphinx16 docutils==0.18.117 # via18 # sphinx19 # sphinx-tabs9 unmodified lines29 # via30 # pallets-sphinx-themes31 # sphinx32 pallets-sphinx-themes==2.1.035- # via -r requirements\docs.in33+ # via -r requirements/docs.in34 pygments==2.15.135 # via36 # sphinx37 # sphinx-tabs40-requests==2.29.038+requests==2.31.039 # via sphinx40 snowballstemmer==2.2.041 # via sphinx44-sphinx==7.0.042+sphinx==7.0.143 # via46- # -r requirements\docs.in44+ # -r requirements/docs.in45 # pallets-sphinx-themes46 # sphinx-issues47 # sphinx-tabs48 # sphinxcontrib-log-cabinet49 sphinx-issues==3.0.152- # via -r requirements\docs.in50+ # via -r requirements/docs.in51 sphinx-tabs==3.4.154- # via -r requirements\docs.in52+ # via -r requirements/docs.in53 sphinxcontrib-applehelp==1.0.454 # via sphinx55 sphinxcontrib-devhelp==1.0.256 # via sphinx1 unmodified line58 # via sphinx59 sphinxcontrib-jsmath==1.0.160 # via sphinx61 sphinxcontrib-log-cabinet==1.0.164- # via -r requirements\docs.in62+ # via -r requirements/docs.in63 sphinxcontrib-qthelp==1.0.364 # via sphinx65 sphinxcontrib-serializinghtml==1.1.566 # via sphinx69-urllib3==1.26.1567+urllib3==2.0.268 # via requestsmodified:requirements/tests.txt+1 added-3 removed
3 unmodified lines4 # To update, run:5 #6 # pip-compile-multi7 #8-colorama==0.4.69- # via pytest8 exceptiongroup==1.1.19 # via pytest10 iniconfig==2.0.011 # via pytest1 unmodified line13 # via pytest14 pluggy==1.0.015 # via pytest16 pytest==7.3.119- # via -r requirements\tests.in17+ # via -r requirements/tests.in18 tomli==2.0.119 # via pytestmodified:requirements/typing.txt+3 added-3 removed
3 unmodified lines4 # To update, run:5 #6 # pip-compile-multi7 #8-mypy==0.9918+mypy==1.3.09 # via -r requirements/typing.in10-mypy-extensions==0.4.310+mypy-extensions==1.0.011 # via mypy12 tomli==2.0.113 # via mypy14-typing-extensions==4.4.014+typing-extensions==4.6.215 # via mypymodified:src/click/core.py+19 added-12 removed
262 unmodified lines263 parent: t.Optional["Context"] = None,264 info_name: t.Optional[str] = None,265 obj: t.Optional[t.Any] = None,266 auto_envvar_prefix: t.Optional[str] = None,267- default_map: t.Optional[t.Dict[str, t.Any]] = None,267+ default_map: t.Optional[t.MutableMapping[str, t.Any]] = None,268 terminal_width: t.Optional[int] = None,269 max_content_width: t.Optional[int] = None,270 resilient_parsing: bool = False,271 allow_extra_args: t.Optional[bool] = None,38 unmodified lines310 and parent.default_map is not None311 ):312 default_map = parent.default_map.get(info_name)313 314- self.default_map: t.Optional[t.Dict[str, t.Any]] = default_map314+ self.default_map: t.Optional[t.MutableMapping[str, t.Any]] = default_map315 316 #: This flag indicates if a subcommand is going to be executed. A317 #: group callback can use this information to figure out if it's318 #: being executed directly or because the execution flow passes542 unmodified lines861 862 def __init__(863 self,864 name: t.Optional[str],865- context_settings: t.Optional[t.Dict[str, t.Any]] = None,865+ context_settings: t.Optional[t.MutableMapping[str, t.Any]] = None,866 ) -> None:867 #: the name the command thinks it has. Upon registering a command868 #: on a :class:`Group` the group will default the command name869 #: with this information. You should instead use the3 unmodified lines873 if context_settings is None:874 context_settings = {}875 876 #: an optional dictionary with defaults passed to the context.877- self.context_settings: t.Dict[str, t.Any] = context_settings877+ self.context_settings: t.MutableMapping[str, t.Any] = context_settings878 879 def to_info_dict(self, ctx: Context) -> t.Dict[str, t.Any]:880 """Gather information that could be useful for a tool generating881 user-facing documentation. This traverses the entire structure33 unmodified lines915 916 :param info_name: the info name for this invocation. Generally this917 is the most descriptive name for the script or918 command. For the toplevel script it's usually919- the name of the script, for commands below it it's919+ the name of the script, for commands below it's920 the name of the command.921 :param args: the arguments to parse as list of strings.922 :param parent: the parent context if available.923 :param extra: extra keyword arguments forwarded to the context24 unmodified lines948 def invoke(self, ctx: Context) -> t.Any:949 """Given a context, this invokes the command. The default950 implementation is raising a not implemented error.951 """952- raise NotImplementedError("Base commands are not invokable by default")952+ raise NotImplementedError("Base commands are not invocable by default")953 954 def shell_complete(self, ctx: Context, incomplete: str) -> t.List["CompletionItem"]:955 """Return a list of completions for the incomplete value. Looks956 at the names of chained multi-commands.159 unmodified lines1116 sys.exit(1)1117 1118 def _main_shell_completion(1119 self,1120- ctx_args: t.Dict[str, t.Any],1120+ ctx_args: t.MutableMapping[str, t.Any],1121 prog_name: str,1122 complete_var: t.Optional[str] = None,1123 ) -> None:1124 """Check if the shell is asking for tab completion, process67 unmodified lines1192 1193 def __init__(1194 self,1195 name: t.Optional[str],1196- context_settings: t.Optional[t.Dict[str, t.Any]] = None,1196+ context_settings: t.Optional[t.MutableMapping[str, t.Any]] = None,1197 callback: t.Optional[t.Callable[..., t.Any]] = None,1198 params: t.Optional[t.List["Parameter"]] = None,1199 help: t.Optional[str] = None,1200 epilog: t.Optional[str] = None,278 unmodified lines1479 multiple commands to be chained together.1480 :param result_callback: The result callback to attach to this multi1481 command. This can be set or changed later with the1482 :meth:`result_callback` decorator.1483+ :param attrs: Other command arguments described in :class:`Command`.1484 """1485 1486 allow_extra_args = True1487 allow_interspersed_args = False290 unmodified lines1778 :class:`MultiCommand`, :class:`Command`, and1779 :class:`BaseCommand`.1780 1781 .. versionchanged:: 8.01781- The ``commmands`` argument can be a list of command objects.1782+ The ``commands`` argument can be a list of command objects.1783 """1784 1785 #: If set, this is used by the group's :meth:`command` decorator1786 #: as the default :class:`Command` class. This is useful to make all17 unmodified lines1804 1805 def __init__(1806 self,1807 name: t.Optional[str] = None,1807- commands: t.Optional[t.Union[t.Dict[str, Command], t.Sequence[Command]]] = None,1808+ commands: t.Optional[1809+ t.Union[t.MutableMapping[str, Command], t.Sequence[Command]]1810+ ] = None,1811 **attrs: t.Any,1812 ) -> None:1813 super().__init__(name, **attrs)1814 2 unmodified lines1817 elif isinstance(commands, abc.Sequence):1818 commands = {c.name: c for c in commands if c.name is not None}1819 1820 #: The registered subcommands by their exported names.1818- self.commands: t.Dict[str, Command] = commands1821+ self.commands: t.MutableMapping[str, Command] = commands1822 1823 def add_command(self, cmd: Command, name: t.Optional[str] = None) -> None:1824 """Registers another :class:`Command` with this group. If the name1825 is not provided, the name of the command is used.120 unmodified lines1946 """A command collection is a multi command that merges multiple multi1947 commands together into one. This is a straightforward implementation1948 that accepts a list of different multi commands as sources and1949 provides all the commands for each of them.1950+1951+ See :class:`MultiCommand` and :class:`Command` for the description of1952+ ``name`` and ``attrs``.1953 """1954 1955 def __init__(1956 self,515 unmodified lines2472 variable in case a prefix is defined on the2473 context.2474 :param help: the help string.2475 :param hidden: hide this option from help outputs.2476+ :param attrs: Other command arguments described in :class:`Parameter`.2477 2478 .. versionchanged:: 8.1.02479 Help text indentation is cleaned here instead of only in the2480 ``@option`` decorator.470 unmodified lines2951 """Arguments are positional parameters to a command. They generally2952 provide fewer features than options but can have infinite ``nargs``2953 and are required by default.2954 2948- All parameters are passed onwards to the parameter constructor.2955+ All parameters are passed onwards to the constructor of :class:`Parameter`.2956 """2957 2958 param_type_name = "argument"2959 64 unmodified linesmodified:src/click/decorators.py+14 added-2 removed
92 unmodified lines93 return ctx.invoke(f, obj, *args, **kwargs)94 95 return update_wrapper(new_func, f)96 97- return decorator97+ return decorator # type: ignore[return-value]98 99 100 def pass_meta_key(101 key: str, *, doc_description: t.Optional[str] = None24 unmodified lines126 decorator.__doc__ = (127 f"Decorator that passes {doc_description} as the first argument"128 " to the decorated function."129 )130- return decorator130+ return decorator # type: ignore[return-value]131 132 133 CmdType = t.TypeVar("CmdType", bound=Command)134 200 unmodified lines335 arguments are forwarded unchanged (except ``cls``).336 This is equivalent to creating an :class:`Argument` instance manually337 and attaching it to the :attr:`Command.params` list.338 339+ For the default argument class, refer to :class:`Argument` and340+ :class:`Parameter` for descriptions of parameters.341+342 :param cls: the argument class to instantiate. This defaults to343 :class:`Argument`.344+ :param param_decls: Passed as positional arguments to the constructor of345+ ``cls``.346+ :param attrs: Passed as keyword arguments to the constructor of ``cls``.347 """348 349 def decorator(f: FC) -> FC:350 ArgumentClass = attrs.pop("cls", None) or Argument9 unmodified lines360 arguments are forwarded unchanged (except ``cls``).361 This is equivalent to creating an :class:`Option` instance manually362 and attaching it to the :attr:`Command.params` list.363 364+ For the default option class, refer to :class:`Option` and365+ :class:`Parameter` for descriptions of parameters.366+367 :param cls: the option class to instantiate. This defaults to368 :class:`Option`.369+ :param param_decls: Passed as positional arguments to the constructor of370+ ``cls``.371+ :param attrs: Passed as keyword arguments to the constructor of ``cls``.372 """373 374 def decorator(f: FC) -> FC:375 # Issue 926, copy attrs, so pre-defined options can re-use the same cls=192 unmodified linesmodified:src/click/parser.py+1 added-1 removed
449 unmodified lines450 451 if stop:452 break453 454- # If we got any unknown options we re-combinate the string of the454+ # If we got any unknown options we recombine the string of the455 # remaining options and re-attach the prefix, then report that456 # to the state as new larg. This way there is basic combinatorics457 # that can be achieved while still ignoring unknown arguments.458 if self.ignore_unknown_options and unknown_options:71 unmodified linesmodified:src/click/shell_completion.py+13 added-5 removed
14 unmodified lines15 16 17 def shell_complete(18 cli: BaseCommand,19- ctx_args: t.Dict[str, t.Any],19+ ctx_args: t.MutableMapping[str, t.Any],20 prog_name: str,21 complete_var: str,22 instruction: str,23 ) -> int:189 unmodified lines213 214 def __init__(215 self,216 cli: BaseCommand,217- ctx_args: t.Dict[str, t.Any],217+ ctx_args: t.MutableMapping[str, t.Any],218 prog_name: str,219 complete_var: str,220 ) -> None:221 self.cli = cli166 unmodified lines388 389 return f"{item.type},{item.value}"390 391 392+ShellCompleteType = t.TypeVar("ShellCompleteType", bound=t.Type[ShellComplete])393+394+395 _available_shells: t.Dict[str, t.Type[ShellComplete]] = {396 "bash": BashComplete,397 "fish": FishComplete,398 "zsh": ZshComplete,399 }400 401 402 def add_completion_class(400- cls: t.Type[ShellComplete], name: t.Optional[str] = None401-) -> None:403+ cls: ShellCompleteType, name: t.Optional[str] = None404+) -> ShellCompleteType:405 """Register a :class:`ShellComplete` subclass under the given name.406 The name will be provided by the completion instruction environment407 variable during completion.408 6 unmodified lines415 name = cls.name416 417 _available_shells[name] = cls418 419+ return cls420 421+422 def get_completion_class(shell: str) -> t.Optional[t.Type[ShellComplete]]:423 """Look up a registered :class:`ShellComplete` subclass by the name424 provided by the completion instruction environment variable. If the425 name isn't registered, returns ``None``.60 unmodified lines486 return last_option is not None and last_option in param.opts487 488 489 def _resolve_context(485- cli: BaseCommand, ctx_args: t.Dict[str, t.Any], prog_name: str, args: t.List[str]490+ cli: BaseCommand,491+ ctx_args: t.MutableMapping[str, t.Any],492+ prog_name: str,493+ args: t.List[str],494 ) -> Context:495 """Produce the context hierarchy starting with the command and496 traversing the complete arguments. This only follows the commands,497 it doesn't trigger input prompts or callbacks.91 unmodified linesmodified:src/click/utils.py+1 added-1 removed
428 unmodified lines429 430 :param app_name: the application name. This should be properly capitalized431 and can contain whitespace.432 :param roaming: controls if the folder should be roaming or not on Windows.433- Has no affect otherwise.433+ Has no effect otherwise.434 :param force_posix: if this is set to `True` then on any POSIX system the435 folder will be stored in the home folder with a leading436 dot instead of the XDG config home or darwin's437 application support folder.148 unmodified linesmodified:tests/test_shell_completion.py+72 added
1 import pytest2 3+import click.shell_completion4 from click.core import Argument5 from click.core import Command6 from click.core import Group7 from click.core import Option8+from click.shell_completion import add_completion_class9 from click.shell_completion import CompletionItem10 from click.shell_completion import ShellComplete11 from click.types import Choice12 from click.types import File330 unmodified lines343 params=[Option(["-a"], type=Choice(["Au", "al", "Bc"], case_sensitive=value))],344 )345 completions = _get_words(cli, ["-a"], "a")346 assert completions == expect347+348+349+@pytest.fixture()350+def _restore_available_shells(tmpdir):351+ prev_available_shells = click.shell_completion._available_shells.copy()352+ click.shell_completion._available_shells.clear()353+ yield354+ click.shell_completion._available_shells.clear()355+ click.shell_completion._available_shells.update(prev_available_shells)356+357+358+@pytest.mark.usefixtures("_restore_available_shells")359+def test_add_completion_class():360+ # At first, "mysh" is not in available shells361+ assert "mysh" not in click.shell_completion._available_shells362+363+ class MyshComplete(ShellComplete):364+ name = "mysh"365+ source_template = "dummy source"366+367+ # "mysh" still not in available shells because it is not registered368+ assert "mysh" not in click.shell_completion._available_shells369+370+ # Adding a completion class should return that class371+ assert add_completion_class(MyshComplete) is MyshComplete372+373+ # Now, "mysh" is finally in available shells374+ assert "mysh" in click.shell_completion._available_shells375+ assert click.shell_completion._available_shells["mysh"] is MyshComplete376+377+378+@pytest.mark.usefixtures("_restore_available_shells")379+def test_add_completion_class_with_name():380+ # At first, "mysh" is not in available shells381+ assert "mysh" not in click.shell_completion._available_shells382+ assert "not_mysh" not in click.shell_completion._available_shells383+384+ class MyshComplete(ShellComplete):385+ name = "not_mysh"386+ source_template = "dummy source"387+388+ # "mysh" and "not_mysh" are still not in available shells because389+ # it is not registered yet390+ assert "mysh" not in click.shell_completion._available_shells391+ assert "not_mysh" not in click.shell_completion._available_shells392+393+ # Adding a completion class should return that class.394+ # Because we are using the "name" parameter, the name isn't taken395+ # from the class.396+ assert add_completion_class(MyshComplete, name="mysh") is MyshComplete397+398+ # Now, "mysh" is finally in available shells399+ assert "mysh" in click.shell_completion._available_shells400+ assert "not_mysh" not in click.shell_completion._available_shells401+ assert click.shell_completion._available_shells["mysh"] is MyshComplete402+403+404+@pytest.mark.usefixtures("_restore_available_shells")405+def test_add_completion_class_decorator():406+ # At first, "mysh" is not in available shells407+ assert "mysh" not in click.shell_completion._available_shells408+409+ @add_completion_class410+ class MyshComplete(ShellComplete):411+ name = "mysh"412+ source_template = "dummy source"413+414+ # Using `add_completion_class` as a decorator adds the new shell immediately415+ assert "mysh" in click.shell_completion._available_shells416+ assert click.shell_completion._available_shells["mysh"] is MyshCompletemodified:tests/test_termui.py+2 added-1 removed
173 unmodified lines174 click.progressbar()175 176 177 def test_progressbar_iter_outside_with_exceptions(runner):178+ progress = click.progressbar(length=2)179+180 with pytest.raises(RuntimeError, match="with block"):179- progress = click.progressbar(length=2)181 iter(progress)182 183 184 def test_progressbar_is_iterator(runner, monkeypatch):265 unmodified linesmodified:.pre-commit-config.yaml+1 added-1 removed
1 unmodified line2 autoupdate_branch: "8.1.x"3 autoupdate_schedule: monthly4 repos:5 - repo: https://github.com/asottile/pyupgrade6- rev: v3.3.26+ rev: v3.4.07 hooks:8 - id: pyupgrade9 args: ["--py37-plus"]10 - repo: https://github.com/asottile/reorder_python_imports22 unmodified linesmodified:CHANGES.rst+3 added
12 unmodified lines13 -------------14 15 Unreleased16 17+- Replace all ``typing.Dict`` occurrences to ``typing.MutableMapping`` for18+ parameter hints. :issue:`2255`19 - Improve type hinting for decorators and give all generic types parameters.20 :issue:`2398`21+- Fix return value and type signature of `shell_completion.add_completion_class` function. :pr:`2421`22 23 24 Version 8.1.325 -------------1040 unmodified linesmodified:README.rst-2 removed
73 unmodified lines74 - Changes: https://click.palletsprojects.com/changes/75 - PyPI Releases: https://pypi.org/project/click/76 - Source Code: https://github.com/pallets/click77 - Issue Tracker: https://github.com/pallets/click/issues78-- Website: https://palletsprojects.com/p/click79-- Twitter: https://twitter.com/PalletsTeam78 - Chat: https://discord.gg/pallets