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 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

17 files+155 added−60 removed

modified:docs/advanced.rst+3 added-3 removed
77 unmodified lines
78object has a :attr:`~Context.params` attribute which is a dictionary of79all parameters. Whatever is in that dictionary is being passed to the80callbacks.8182This can be used to make up addition parameters. Generally this pattern82This can be used to make up additional parameters. Generally this pattern83is not recommended but in some cases it can be useful. At the very least84it's good to know that the system works this way.8586.. click:example::
194 unmodified lines
281 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`.2852. You can attach a :func:`argument` with ``nargs`` set to `-1` which2852. 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 lines
338 (: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.341342Generally though the combinated handling of options and arguments from342Generally though the combined handling of options and arguments from343your own commands and commands from another application are discouraged344and if you can avoid it, you should. It's a much better idea to have345everything below a subcommand be forwarded to another application than to346handle some arguments yourself.
142 unmodified lines
modified:docs/conf.py-2 removed
36 unmodified lines
37 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}44html_sidebars = {
13 unmodified lines
modified:requirements/build.txt+1 added-3 removed
4 unmodified lines
5#6# pip-compile-multi7#8build==0.10.09 # via -r requirements\build.in10colorama==0.4.611 # via build9 # via -r requirements/build.in10packaging==23.111 # via build12pyproject-hooks==1.0.013 # via build
2 unmodified lines
modified:requirements/dev.txt+12 added-10 removed
8 unmodified lines
9-r tests.txt10-r typing.txt11build==0.10.012 # via pip-tools13cachetools==5.3.013cachetools==5.3.114 # via tox15cfgv==3.3.116 # via pre-commit17chardet==5.1.0
1 unmodified line
19click==8.1.320 # via21 # pip-compile-multi22 # pip-tools23colorama==0.4.624 # via tox25distlib==0.3.626 # via virtualenv27filelock==3.12.028 # via29 # tox30 # virtualenv29identify==2.5.2331identify==2.5.2432 # via pre-commit31nodeenv==1.7.033nodeenv==1.8.034 # via pre-commit33pip-compile-multi==2.6.234 # via -r requirements\dev.in35pip-compile-multi==2.6.336 # via -r requirements/dev.in37pip-tools==6.13.038 # via pip-compile-multi37platformdirs==3.5.039platformdirs==3.5.140 # via41 # tox42 # virtualenv41pre-commit==3.3.142 # via -r requirements\dev.in43pre-commit==3.3.244 # via -r requirements/dev.in45pyproject-api==1.5.146 # via tox47pyproject-hooks==1.0.048 # via build49pyyaml==6.050 # via pre-commit51toposort==1.1052 # via pip-compile-multi51tox==4.5.152 # via -r requirements\dev.in53tox==4.5.254 # via -r requirements/dev.in55virtualenv==20.23.056 # via57 # pre-commit58 # tox
6 unmodified lines
modified:requirements/docs.txt+9 added-11 removed
7 unmodified lines
8alabaster==0.7.139 # via sphinx10babel==2.12.111 # via sphinx12certifi==2022.12.712certifi==2023.5.713 # via requests14charset-normalizer==3.1.015 # via requests16colorama==0.4.617 # via sphinx16docutils==0.18.117 # via18 # sphinx19 # sphinx-tabs
9 unmodified lines
29 # via30 # pallets-sphinx-themes31 # sphinx32pallets-sphinx-themes==2.1.035 # via -r requirements\docs.in33 # via -r requirements/docs.in34pygments==2.15.135 # via36 # sphinx37 # sphinx-tabs40requests==2.29.038requests==2.31.039 # via sphinx40snowballstemmer==2.2.041 # via sphinx44sphinx==7.0.042sphinx==7.0.143 # via46 # -r requirements\docs.in44 # -r requirements/docs.in45 # pallets-sphinx-themes46 # sphinx-issues47 # sphinx-tabs48 # sphinxcontrib-log-cabinet49sphinx-issues==3.0.152 # via -r requirements\docs.in50 # via -r requirements/docs.in51sphinx-tabs==3.4.154 # via -r requirements\docs.in52 # via -r requirements/docs.in53sphinxcontrib-applehelp==1.0.454 # via sphinx55sphinxcontrib-devhelp==1.0.256 # via sphinx
1 unmodified line
58 # via sphinx59sphinxcontrib-jsmath==1.0.160 # via sphinx61sphinxcontrib-log-cabinet==1.0.164 # via -r requirements\docs.in62 # via -r requirements/docs.in63sphinxcontrib-qthelp==1.0.364 # via sphinx65sphinxcontrib-serializinghtml==1.1.566 # via sphinx69urllib3==1.26.1567urllib3==2.0.268 # via requests
modified:requirements/tests.txt+1 added-3 removed
3 unmodified lines
4# To update, run:5#6# pip-compile-multi7#8colorama==0.4.69 # via pytest8exceptiongroup==1.1.19 # via pytest10iniconfig==2.0.011 # via pytest
1 unmodified line
13 # via pytest14pluggy==1.0.015 # via pytest16pytest==7.3.119 # via -r requirements\tests.in17 # via -r requirements/tests.in18tomli==2.0.119 # via pytest
modified:requirements/typing.txt+3 added-3 removed
3 unmodified lines
4# To update, run:5#6# pip-compile-multi7#8mypy==0.9918mypy==1.3.09 # via -r requirements/typing.in10mypy-extensions==0.4.310mypy-extensions==1.0.011 # via mypy12tomli==2.0.113 # via mypy14typing-extensions==4.4.014typing-extensions==4.6.215 # via mypy
modified:src/click/core.py+19 added-12 removed
262 unmodified lines
263 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 lines
310 and parent.default_map is not None311 ):312 default_map = parent.default_map.get(info_name)313314 self.default_map: t.Optional[t.Dict[str, t.Any]] = default_map314 self.default_map: t.Optional[t.MutableMapping[str, t.Any]] = default_map315316 #: 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 passes
542 unmodified lines
861862 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 the
3 unmodified lines
873 if context_settings is None:874 context_settings = {}875876 #: 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_settings878879 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 structure
33 unmodified lines
915916 :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 context
24 unmodified lines
948 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")953954 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 lines
1116 sys.exit(1)11171118 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, process
67 unmodified lines
11921193 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 lines
1479 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 """14851486 allow_extra_args = True1487 allow_interspersed_args = False
290 unmodified lines
1778 :class:`MultiCommand`, :class:`Command`, and1779 :class:`BaseCommand`.17801781 .. 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 """17841785 #: If set, this is used by the group's :meth:`command` decorator1786 #: as the default :class:`Command` class. This is useful to make all
17 unmodified lines
18041805 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 lines
1817 elif isinstance(commands, abc.Sequence):1818 commands = {c.name: c for c in commands if c.name is not None}18191820 #: The registered subcommands by their exported names.1818 self.commands: t.Dict[str, Command] = commands1821 self.commands: t.MutableMapping[str, Command] = commands18221823 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 lines
1946 """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.19501951 See :class:`MultiCommand` and :class:`Command` for the description of1952 ``name`` and ``attrs``.1953 """19541955 def __init__(1956 self,
515 unmodified lines
2472 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`.24772478 .. versionchanged:: 8.1.02479 Help text indentation is cleaned here instead of only in the2480 ``@option`` decorator.
470 unmodified lines
2951 """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.29542948 All parameters are passed onwards to the parameter constructor.2955 All parameters are passed onwards to the constructor of :class:`Parameter`.2956 """29572958 param_type_name = "argument"2959
64 unmodified lines
modified:src/click/decorators.py+14 added-2 removed
92 unmodified lines
93 return ctx.invoke(f, obj, *args, **kwargs)9495 return update_wrapper(new_func, f)9697 return decorator97 return decorator # type: ignore[return-value]9899100def pass_meta_key(101 key: str, *, doc_description: t.Optional[str] = None
24 unmodified lines
126 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]131132133CmdType = t.TypeVar("CmdType", bound=Command)134
200 unmodified lines
335 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.338339 For the default argument class, refer to :class:`Argument` and340 :class:`Parameter` for descriptions of parameters.341342 :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 """348349 def decorator(f: FC) -> FC:350 ArgumentClass = attrs.pop("cls", None) or Argument
9 unmodified lines
360 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.363364 For the default option class, refer to :class:`Option` and365 :class:`Parameter` for descriptions of parameters.366367 :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 """373374 def decorator(f: FC) -> FC:375 # Issue 926, copy attrs, so pre-defined options can re-use the same cls=
192 unmodified lines
modified:src/click/parser.py+1 added-1 removed
449 unmodified lines
450451 if stop:452 break453454 # 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 lines
modified:src/click/shell_completion.py+13 added-5 removed
14 unmodified lines
151617def 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 lines
213214 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 = cli
166 unmodified lines
388389 return f"{item.type},{item.value}"390391392ShellCompleteType = t.TypeVar("ShellCompleteType", bound=t.Type[ShellComplete])393394395_available_shells: t.Dict[str, t.Type[ShellComplete]] = {396 "bash": BashComplete,397 "fish": FishComplete,398 "zsh": ZshComplete,399}400401402def 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 lines
415 name = cls.name416417 _available_shells[name] = cls418419 return cls420421422def 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 lines
486 return last_option is not None and last_option in param.opts487488489def _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 lines
modified:src/click/utils.py+1 added-1 removed
428 unmodified lines
429430 :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 lines
modified:tests/test_shell_completion.py+72 added
1import pytest23import click.shell_completion4from click.core import Argument5from click.core import Command6from click.core import Group7from click.core import Option8from click.shell_completion import add_completion_class9from click.shell_completion import CompletionItem10from click.shell_completion import ShellComplete11from click.types import Choice12from click.types import File
330 unmodified lines
343 params=[Option(["-a"], type=Choice(["Au", "al", "Bc"], case_sensitive=value))],344 )345 completions = _get_words(cli, ["-a"], "a")346 assert completions == expect347348349@pytest.fixture()350def _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)356357358@pytest.mark.usefixtures("_restore_available_shells")359def test_add_completion_class():360 # At first, "mysh" is not in available shells361 assert "mysh" not in click.shell_completion._available_shells362363 class MyshComplete(ShellComplete):364 name = "mysh"365 source_template = "dummy source"366367 # "mysh" still not in available shells because it is not registered368 assert "mysh" not in click.shell_completion._available_shells369370 # Adding a completion class should return that class371 assert add_completion_class(MyshComplete) is MyshComplete372373 # Now, "mysh" is finally in available shells374 assert "mysh" in click.shell_completion._available_shells375 assert click.shell_completion._available_shells["mysh"] is MyshComplete376377378@pytest.mark.usefixtures("_restore_available_shells")379def 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_shells383384 class MyshComplete(ShellComplete):385 name = "not_mysh"386 source_template = "dummy source"387388 # "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_shells392393 # 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 MyshComplete397398 # 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 MyshComplete402403404@pytest.mark.usefixtures("_restore_available_shells")405def test_add_completion_class_decorator():406 # At first, "mysh" is not in available shells407 assert "mysh" not in click.shell_completion._available_shells408409 @add_completion_class410 class MyshComplete(ShellComplete):411 name = "mysh"412 source_template = "dummy source"413414 # 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 MyshComplete
modified:tests/test_termui.py+2 added-1 removed
173 unmodified lines
174 click.progressbar()175176177def test_progressbar_iter_outside_with_exceptions(runner):178 progress = click.progressbar(length=2)179180 with pytest.raises(RuntimeError, match="with block"):179 progress = click.progressbar(length=2)181 iter(progress)182183184def test_progressbar_is_iterator(runner, monkeypatch):
265 unmodified lines
modified:.pre-commit-config.yaml+1 added-1 removed
1 unmodified line
2 autoupdate_branch: "8.1.x"3 autoupdate_schedule: monthly4repos: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_imports
22 unmodified lines
modified:CHANGES.rst+3 added
12 unmodified lines
13-------------1415Unreleased1617- 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`222324Version 8.1.325-------------
1040 unmodified lines
modified:README.rst-2 removed
73 unmodified lines
74- 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