Merge stable into main (#2799)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Most changes are to documentation.
authored by Rowlando13 · committed by GitHub · parents 0ef55fd, dea4ff7 · Browse files · 15 files·+208 added−176 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
15 files+208 added−176 removed
- tests:+32 added−7 removed
- other:+176 added−169 removed
Provenance
- Commit
d791537- Tree
aede7d8- Author
Rowlando13 <67291205+Rowlando13@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent 1
0ef55fd- Parent 2
dea4ff7
15 files changed+208 added−176 removed
modified:docs/arguments.rst+3 added
181 unmodified lines182 file in the same folder, and upon completion, the file will be moved over to183 the original location. This is useful if a file regularly read by other184 users is modified.185 186+187+.. _environment-variables:188+189 Environment Variables190 ---------------------191 192 Like options, arguments can also grab values from an environment variable.74 unmodified linesmodified:docs/commands.rst+2 added-1 removed
273 unmodified lines274 command in the chain.275 - The :attr:`Context.invoked_subcommand` attribute will be ``'*'`` because the276 parser doesn't know the full list of commands that will run yet.277 278+.. _command-pipelines:279 280 Command Pipelines280------------------281+------------------282 283 When using chaining, a common pattern is to have each command process the284 result of the previous command.285 254 unmodified linesmodified:docs/documentation.rst+1 added-1 removed
34 unmodified lines35 36 .. _documenting-arguments:37 38 Documenting Arguments39-~~~~~~~~~~~~~~~~~~~~~39+----------------------40 41 :func:`click.argument` does not take a ``help`` parameter. This is to42 follow the general convention of Unix tools of using arguments for only43 the most necessary things, and to document them in the command help text224 unmodified linesmodified:docs/index.rst+2 added
67 unmodified lines68 69 why70 quickstart71 entry-points72+ virtualenv73+ setuptools74 parameters75 options76 arguments77 commands31 unmodified linesmodified:docs/parameters.rst+48 added-54 removed
1 unmodified line2 ==========3 4 .. currentmodule:: click5 6-Click supports two types of parameters for scripts: options and arguments.7-There is generally some confusion among authors of command line scripts of8-when to use which, so here is a quick overview of the differences. As its9-name indicates, an option is optional. While arguments can be optional10-within reason, they are much more restricted in how optional they can be.6+Click supports only two types of parameters for scripts (by design): options and arguments.7 12-To help you decide between options and arguments, the recommendation is13-to use arguments exclusively for things like going to subcommands or input14-filenames / URLs, and have everything else be an option instead.8+Options9+----------------10 16-Differences17------------11+* Are optional.12+* Recommended to use for everything except subcommands, urls, or files.13+* Can take a fixed number of arguments. The default is 1. They may be specified multiple times using :ref:`multiple-options`.14+* Are fully documented by the help page.15+* Have automatic prompting for missing input.16+* Can act as flags (boolean or otherwise).17+* Can be pulled from environment variables.18 19-Arguments can do less than options. The following features are only20-available for options:19+Arguments20+----------------21 22-* automatic prompting for missing input23-* act as flags (boolean or otherwise)24-* option values can be pulled from environment variables, arguments can not25-* options are fully documented in the help page, arguments are not26- (:ref:`this is intentional <documenting-arguments>` as arguments27- might be too specific to be automatically documented)22+* Are optional with in reason, but not entirely so.23+* Recommended to use for subcommands, urls, or files.24+* Can take an arbitrary number of arguments.25+* Are not fully documented by the help page since they may be too specific to be automatically documented. For more see :ref:`documenting-arguments`.26+* Can be pulled from environment variables but only explicitly named ones. For more see :ref:`environment-variables`.27 29-On the other hand arguments, unlike options, can accept an arbitrary number30-of arguments. Options can strictly ever only accept a fixed number of31-arguments (defaults to 1), or they may be specified multiple times using32-:ref:`multiple-options`.28+.. _parameter_names:29 30+Parameter Names31+---------------32+33+Parameters (options and arguments) have a name that will be used as34+the Python argument name when calling the decorated function with35+values.36+37+.. click:example::38+39+ @click.command()40+ @click.argument('filename')41+ @click.option('-t', '--times', type=int)42+ def multi_echo(filename, times):43+ """Print value filename multiple times."""44+ for x in range(times):45+ click.echo(filename)46+47+In the above example the argument's name is ``filename``. The name must match the python arg name. To provide a different name for use in help text, see :ref:`doc-meta-variables`.48+The option's names are ``-t`` and ``--times``. More names are available for options and are covered in :ref:`options`.49+50+And what it looks like when run:51+52+.. click:run::53+54+ invoke(multi_echo, ['--times=3', 'index.txt'], prog_name='multi_echo')55+56 Parameter Types57 ---------------58 37-Parameters can be of different types. Types can be implemented with38-different behavior and some are supported out of the box:59+The supported parameter types are:60 61 ``str`` / :data:`click.STRING`:62 The default parameter type which indicates unicode strings.63 30 unmodified lines94 95 .. autoclass:: DateTime96 :noindex:97 77-Custom parameter types can be implemented by subclassing78-:class:`click.ParamType`. For simple cases, passing a Python function that79-fails with a `ValueError` is also supported, though discouraged.98+How to Implement Custom Types99+-------------------------------100 81-.. _parameter_names:101+To implement a custom type, you need to subclass the :class:`ParamType` class. For simple cases, passing a Python function that fails with a `ValueError` is also supported, though discouraged. Override the :meth:`~ParamType.convert` method to convert the value from a string to the correct type.102 83-Parameter Names84----------------85-86-Parameters (both options and arguments) have a name that will be used as87-the Python argument name when calling the decorated function with88-values.89-90-Arguments take only one positional name. To provide a different name for91-use in help text, see :ref:`doc-meta-variables`.92-93-Options can have many names that may be prefixed with one or two dashes.94-Names with one dash are parsed as short options, names with two are95-parsed as long options. If a name is not prefixed, it is used as the96-Python argument name and not parsed as an option name. Otherwise, the97-first name with a two dash prefix is used, or the first with a one dash98-prefix if there are none with two. The prefix is removed and dashes are99-converted to underscores to get the Python argument name.100-101-102-Implementing Custom Types103--------------------------104-105-To implement a custom type, you need to subclass the :class:`ParamType`106-class. Override the :meth:`~ParamType.convert` method to convert the107-value from a string to the correct type.108-103 The following code implements an integer type that accepts hex and octal104 numbers in addition to normal integers, and converts them into regular105 integers.106 31 unmodified linesmodified:docs/quickstart.rst+15 added-85 removed
1 unmodified line2 ==========3 4 .. currentmodule:: click5 6-You can get the library directly from PyPI::6+Install7+----------------------8+Install from PyPI::9 10 pip install click11 10-The installation into a :ref:`virtualenv` is heavily recommended.12+Installing into a virtual environment is highly recommended. We suggest :ref:`virtualenv-heading`.13 12-.. _virtualenv:13-14-virtualenv15-----------16-17-Virtualenv is probably what you want to use for developing Click18-applications.19-20-What problem does virtualenv solve? Chances are that you want to use it21-for other projects besides your Click script. But the more projects you22-have, the more likely it is that you will be working with different23-versions of Python itself, or at least different versions of Python24-libraries. Let's face it: quite often libraries break backwards25-compatibility, and it's unlikely that any serious application will have26-zero dependencies. So what do you do if two or more of your projects have27-conflicting dependencies?28-29-Virtualenv to the rescue! Virtualenv enables multiple side-by-side30-installations of Python, one for each project. It doesn't actually31-install separate copies of Python, but it does provide a clever way to32-keep different project environments isolated.33-34-Create your project folder, then a virtualenv within it::35-36- $ mkdir myproject37- $ cd myproject38- $ python3 -m venv .venv39-40-Now, whenever you want to work on a project, you only have to activate the41-corresponding environment. On OS X and Linux, do the following::42-43- $ . .venv/bin/activate44- (venv) $45-46-If you are a Windows user, the following command is for you::47-48- > .venv\scripts\activate49- (venv) >50-51-Either way, you should now be using your virtualenv (notice how the prompt of52-your shell has changed to show the active environment).53-54-And if you want to stop using the virtualenv, use the following command::55-56- $ deactivate57-58-After doing this, the prompt of your shell should be as familiar as before.59-60-Now, let's move on. Enter the following command to get Click activated in your61-virtualenv::62-63- $ pip install click64-65-A few seconds later and you are good to go.66-67-Screencast and Examples14+Examples15 -----------------------16 70-There is a screencast available which shows the basic API of Click and71-how to build simple applications with it. It also explores how to build72-commands with subcommands.17+Some standalone examples of Click applications are packaged with Click. They are available in the `examples folder <https://github.com/pallets/click/tree/main/examples>`_ of the repo.18 74-* `Building Command Line Applications with Click75- <https://www.youtube.com/watch?v=kNke39OZ2k0>`_19+* `inout <https://github.com/pallets/click/tree/main/examples/inout>`_ : A very simple example of an application that can read from files and write to files and also accept input from stdin or write to stdout.20+* `validation <https://github.com/pallets/click/tree/main/examples/validation>`_ : A simple example of an application that performs custom validation of parameters in different ways.21+* `naval <https://github.com/pallets/click/tree/main/examples/naval>`_ : Port of the `docopt <http://docopt.org/>`_ naval example.22+* `colors <https://github.com/pallets/click/tree/main/examples/colors>`_ : A simple example that colorizes text. Uses colorama on Windows.23+* `aliases <https://github.com/pallets/click/tree/main/examples/aliases>`_ : An advanced example that implements :ref:`aliases`.24+* `imagepipe <https://github.com/pallets/click/tree/main/examples/imagepipe>`_ : A complex example that implements some :ref:`command-pipelines` . It chains together image processing instructions. Requires pillow.25+* `repo <https://github.com/pallets/click/tree/main/examples/repo>`_ : An advanced example that implements a Git-/Mercurial-like command line interface.26+* `complex <https://github.com/pallets/click/tree/main/examples/complex>`_ : A very advanced example that implements loading subcommands dynamically from a plugin folder.27+* `termui <https://github.com/pallets/click/tree/main/examples/termui>`_ : A simple example that showcases terminal UI helpers provided by click.28 77-Examples of Click applications can be found in the documentation as well78-as in the GitHub repository together with readme files:79-80-* ``inout``: `File input and output81- <https://github.com/pallets/click/tree/main/examples/inout>`_82-* ``naval``: `Port of docopt naval example83- <https://github.com/pallets/click/tree/main/examples/naval>`_84-* ``aliases``: `Command alias example85- <https://github.com/pallets/click/tree/main/examples/aliases>`_86-* ``repo``: `Git-/Mercurial-like command line interface87- <https://github.com/pallets/click/tree/main/examples/repo>`_88-* ``complex``: `Complex example with plugin loading89- <https://github.com/pallets/click/tree/main/examples/complex>`_90-* ``validation``: `Custom parameter validation example91- <https://github.com/pallets/click/tree/main/examples/validation>`_92-* ``colors``: `Color support demo93- <https://github.com/pallets/click/tree/main/examples/colors>`_94-* ``termui``: `Terminal UI functions demo95- <https://github.com/pallets/click/tree/main/examples/termui>`_96-* ``imagepipe``: `Command chaining demo97- <https://github.com/pallets/click/tree/main/examples/imagepipe>`_98-29 Basic Concepts - Creating a Command30 -----------------------------------31 32 Click is based on declaring commands through decorators. Internally, there174 unmodified linesadded:docs/virtualenv.rst+54 added
1+.. _virtualenv-heading:2+3+Virtualenv4+=========================5+6+Why Use Virtualenv?7+-------------------------8+9+You should use `Virtualenv <https://virtualenv.pypa.io/en/latest/>`_ because:10+11+* It allows you to install multiple versions of the same dependency.12+13+* If you have an operating system version of Python, it prevents you from changing its dependencies and potentially messing up your os.14+15+How to Use Virtualenv16+-----------------------------17+18+Create your project folder, then a virtualenv within it::19+20+ $ mkdir myproject21+ $ cd myproject22+ $ python3 -m venv .venv23+24+Now, whenever you want to work on a project, you only have to activate the25+corresponding environment.26+27+.. tabs::28+29+ .. group-tab:: OSX/Linux30+31+ .. code-block:: text32+33+ $ . .venv/bin/activate34+ (venv) $35+36+ .. group-tab:: Windows37+38+ .. code-block:: text39+40+ > .venv\scripts\activate41+ (venv) >42+43+44+You are now using your virtualenv (notice how the prompt of your shell has changed to show the active environment).45+46+To install packages in the virtual environment::47+48+ $ pip install click49+50+And if you want to stop using the virtualenv, use the following command::51+52+ $ deactivate53+54+After doing this, the prompt of your shell should be as familiar as before.modified:src/click/__init__.py+1 added
17 unmodified lines18 from .decorators import command as command19 from .decorators import confirmation_option as confirmation_option20 from .decorators import group as group21 from .decorators import help_option as help_option22+from .decorators import HelpOption as HelpOption23 from .decorators import make_pass_decorator as make_pass_decorator24 from .decorators import option as option25 from .decorators import pass_context as pass_context26 from .decorators import pass_obj as pass_obj98 unmodified linesmodified:src/click/core.py+7 added-5 removed
1444 unmodified lines1445 will be the value returned by the group's callback, or an empty list if1446 ``chain`` is enabled.1447 :param kwargs: Other arguments passed to :class:`Command`.1448 1449- .. versionchanged:: 8.21450- Merged with and replaces the ``MultiCommand`` base class.1451-1449 .. versionchanged:: 8.01450 The ``commands`` argument can be a list of command objects.1451+1452+ .. versionchanged:: 8.21453+ Merged with and replaces the ``MultiCommand`` base class.1454 """1455 1456 allow_extra_args = True1457 allow_interspersed_args = False1170 unmodified lines2628 2629 if name is None:2630 if not expose_value:2631 return None, opts, secondary_opts2632- raise TypeError("Could not determine name for option")2632+ raise TypeError(2633+ f"Could not determine name for option with declarations {decls!r}"2634+ )2635 2636 if not opts and not secondary_opts:2637 raise TypeError(2638 f"No options defined but a name was passed ({name})."355 unmodified lines2994 ) -> tuple[str | None, list[str], list[str]]:2995 if not decls:2996 if not expose_value:2997 return None, [], []2996- raise TypeError("Could not determine name for argument")2998+ raise TypeError("Argument is marked as exposed, but does not have a name.")2999 if len(decls) == 1:3000 name = arg = decls[0]3001 name = name.replace("-", "_").lower()3002 else:38 unmodified linesmodified:src/click/decorators.py+31 added-21 removed
1 from __future__ import annotations2 3 import inspect4 import typing as t5+from collections import abc6 from functools import update_wrapper7 from gettext import gettext as _8 9 from .core import Argument514 unmodified lines524 kwargs["callback"] = callback525 return option(*param_decls, **kwargs)526 527 527-def help_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]:528- """Add a ``--help`` option which immediately prints the help page528+class HelpOption(Option):529+ """Pre-configured ``--help`` option which immediately prints the help page530 and exits the program.531+ """532 531- This is usually unnecessary, as the ``--help`` option is added to532- each command automatically unless ``add_help_option=False`` is533- passed.533+ def __init__(534+ self,535+ param_decls: abc.Sequence[str] | None = None,536+ **kwargs: t.Any,537+ ) -> None:538+ if not param_decls:539+ param_decls = ("--help",)540 535- :param param_decls: One or more option names. Defaults to the single536- value ``"--help"``.537- :param kwargs: Extra arguments are passed to :func:`option`.538- """541+ kwargs.setdefault("is_flag", True)542+ kwargs.setdefault("expose_value", False)543+ kwargs.setdefault("is_eager", True)544+ kwargs.setdefault("help", _("Show this message and exit."))545+ kwargs.setdefault("callback", self.show_help)546 540- def callback(ctx: Context, param: Parameter, value: bool) -> None:541- if not value or ctx.resilient_parsing:542- return547+ super().__init__(param_decls, **kwargs)548 549+ @staticmethod550+ def show_help(ctx: Context, param: Parameter, value: bool) -> None:551+ """Callback that print the help page on ``<stdout>`` and exits."""552+ if value and not ctx.resilient_parsing:544- echo(ctx.get_help(), color=ctx.color)545- ctx.exit()553+ echo(ctx.get_help(), color=ctx.color)554+ ctx.exit()555 547- if not param_decls:548- param_decls = ("--help",)556 550- kwargs.setdefault("is_flag", True)551- kwargs.setdefault("expose_value", False)552- kwargs.setdefault("is_eager", True)553- kwargs.setdefault("help", _("Show this message and exit."))554- kwargs["callback"] = callback557+def help_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]:558+ """Decorator for the pre-configured ``--help`` option defined above.559+560+ :param param_decls: One or more option names. Defaults to the single561+ value ``"--help"``.562+ :param kwargs: Extra arguments are passed to :func:`option`.563+ """564+ kwargs.setdefault("cls", HelpOption)565 return option(*param_decls, **kwargs)modified:src/click/exceptions.py+9 added-1 removed
4 unmodified lines5 from gettext import gettext as _6 from gettext import ngettext7 8 from ._compat import get_text_stderr9+from .globals import resolve_color_default10 from .utils import echo11 from .utils import format_filename12 13 if t.TYPE_CHECKING:16 unmodified lines30 exit_code = 131 32 def __init__(self, message: str) -> None:33 super().__init__(message)34+ # The context will be removed by the time we print the message, so cache35+ # the color settings here to be used later on (in `show`)36+ self.show_color: bool | None = resolve_color_default()37 self.message = message38 39 def format_message(self) -> str:40 return self.message4 unmodified lines45 def show(self, file: t.IO[t.Any] | None = None) -> None:46 if file is None:47 file = get_text_stderr()48 45- echo(_("Error: {message}").format(message=self.format_message()), file=file)49+ echo(50+ _("Error: {message}").format(message=self.format_message()),51+ file=file,52+ color=self.show_color,53+ )54 55 56 class UsageError(ClickException):57 """An internal exception that signals a usage error. This typically249 unmodified linesmodified:src/click/utils.py+1 added-1 removed
312 unmodified lines313 if should_strip_ansi(file, color):314 out = strip_ansi(out)315 elif WIN:316 if auto_wrap_for_ansi is not None:317- file = auto_wrap_for_ansi(file) # type: ignore317+ file = auto_wrap_for_ansi(file, color) # type: ignore318 elif not color:319 out = strip_ansi(out)320 321 file.write(out) # type: ignore306 unmodified linesmodified:tests/test_testing.py+21 added
3 unmodified lines4 5 import pytest6 7 import click8+from click.exceptions import ClickException9 from click.testing import CliRunner10 11 12 def test_runner():186 unmodified lines199 assert result.output == f"{click.style('hello world', fg='blue')}\n"200 assert not result.exception201 202 203+def test_with_color_errors():204+ class CLIError(ClickException):205+ def format_message(self) -> str:206+ return click.style(self.message, fg="red")207+208+ @click.command()209+ def cli():210+ raise CLIError("Red error")211+212+ runner = CliRunner()213+214+ result = runner.invoke(cli)215+ assert result.output == "Error: Red error\n"216+ assert result.exception217+218+ result = runner.invoke(cli, color=True)219+ assert result.output == f"Error: {click.style('Red error', fg='red')}\n"220+ assert result.exception221+222+223 def test_with_color_but_pause_not_blocking():224 @click.command()225 def cli():226 click.pause()204 unmodified linesmodified:tests/test_utils.py+11 added-7 removed
34 unmodified lines35 assert outstreams[0].getvalue() == b"\x1b[31mx\x1b[39m"36 37 38 def test_echo_custom_file():39- import io40-41- f = io.StringIO()39+ f = StringIO()40 click.echo("hello", file=f)41 assert f.getvalue() == "hello\n"42 43 162 unmodified lines206 out, err = capfd.readouterr()207 assert out == expected_output208 209 212-@pytest.mark.skipif(WIN, reason="Test does not make sense on Windows.")210 def test_echo_color_flag(monkeypatch, capfd):211 isatty = True212 monkeypatch.setattr(click._compat, "isatty", lambda x: isatty)213 14 unmodified lines228 out, err = capfd.readouterr()229 assert out == f"{styled_text}\n"230 231 isatty = False235- click.echo(styled_text)236- out, err = capfd.readouterr()237- assert out == f"{text}\n"232+ # Faking isatty() is not enough on Windows;233+ # the implementation caches the colorama wrapped stream234+ # so we have to use a new stream for each test235+ stream = StringIO()236+ click.echo(styled_text, file=stream)237+ assert stream.getvalue() == f"{text}\n"238 239+ stream = StringIO()240+ click.echo(styled_text, file=stream, color=True)241+ assert stream.getvalue() == f"{styled_text}\n"242 243+244 def test_prompt_cast_default(capfd, monkeypatch):245 monkeypatch.setattr(sys, "stdin", StringIO("\n"))246 value = click.prompt("value", default="100", type=int)247 capfd.readouterr()264 unmodified linesmodified:CHANGES.rst+2 added
76 unmodified lines77 - The test runner handles stripping color consistently on Windows.78 :issue:`2705`79 - Show correct value for flag default when using ``default_map``.80 :issue:`2632`81+- Fix ``click.echo(color=...)`` passing ``color`` to coloroma so it can be82+ forced on Windows. :issue:`2606`.83 84 85 Version 8.1.786 -------------1100 unmodified lines