Skip to content
Myr

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

15 files+208 added−176 removed

modified:docs/arguments.rst+3 added
181 unmodified lines
182file in the same folder, and upon completion, the file will be moved over to183the original location. This is useful if a file regularly read by other184users is modified.185186187.. _environment-variables:188189Environment Variables190---------------------191192Like options, arguments can also grab values from an environment variable.
74 unmodified lines
modified:docs/commands.rst+2 added-1 removed
273 unmodified lines
274 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.277278.. _command-pipelines:279280Command Pipelines280-----------------281------------------282283When using chaining, a common pattern is to have each command process the284result of the previous command.285
254 unmodified lines
modified:docs/documentation.rst+1 added-1 removed
34 unmodified lines
3536.. _documenting-arguments:3738Documenting Arguments39~~~~~~~~~~~~~~~~~~~~~39----------------------4041:func:`click.argument` does not take a ``help`` parameter. This is to42follow the general convention of Unix tools of using arguments for only43the most necessary things, and to document them in the command help text
224 unmodified lines
modified:docs/index.rst+2 added
67 unmodified lines
6869 why70 quickstart71 entry-points72 virtualenv73 setuptools74 parameters75 options76 arguments77 commands
31 unmodified lines
modified:docs/parameters.rst+48 added-54 removed
1 unmodified line
2==========34.. currentmodule:: click56Click supports two types of parameters for scripts: options and arguments.7There is generally some confusion among authors of command line scripts of8when to use which, so here is a quick overview of the differences. As its9name indicates, an option is optional. While arguments can be optional10within reason, they are much more restricted in how optional they can be.6Click supports only two types of parameters for scripts (by design): options and arguments.712To help you decide between options and arguments, the recommendation is13to use arguments exclusively for things like going to subcommands or input14filenames / URLs, and have everything else be an option instead.8Options9----------------1016Differences17-----------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.1819Arguments can do less than options. The following features are only20available for options:19Arguments20----------------2122* 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`.2729On the other hand arguments, unlike options, can accept an arbitrary number30of arguments. Options can strictly ever only accept a fixed number of31arguments (defaults to 1), or they may be specified multiple times using32:ref:`multiple-options`.28.. _parameter_names:2930Parameter Names31---------------3233Parameters (options and arguments) have a name that will be used as34the Python argument name when calling the decorated function with35values.3637.. click:example::3839 @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)4647In 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`.48The option's names are ``-t`` and ``--times``. More names are available for options and are covered in :ref:`options`.4950And what it looks like when run:5152.. click:run::5354 invoke(multi_echo, ['--times=3', 'index.txt'], prog_name='multi_echo')5556Parameter Types57---------------5837Parameters can be of different types. Types can be implemented with38different behavior and some are supported out of the box:59The supported parameter types are:6061``str`` / :data:`click.STRING`:62 The default parameter type which indicates unicode strings.63
30 unmodified lines
9495.. autoclass:: DateTime96 :noindex:9777Custom parameter types can be implemented by subclassing78:class:`click.ParamType`. For simple cases, passing a Python function that79fails with a `ValueError` is also supported, though discouraged.98How to Implement Custom Types99-------------------------------10081.. _parameter_names:101To 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.10283Parameter Names84---------------8586Parameters (both options and arguments) have a name that will be used as87the Python argument name when calling the decorated function with88values.8990Arguments take only one positional name. To provide a different name for91use in help text, see :ref:`doc-meta-variables`.9293Options can have many names that may be prefixed with one or two dashes.94Names with one dash are parsed as short options, names with two are95parsed as long options. If a name is not prefixed, it is used as the96Python argument name and not parsed as an option name. Otherwise, the97first name with a two dash prefix is used, or the first with a one dash98prefix if there are none with two. The prefix is removed and dashes are99converted to underscores to get the Python argument name.100101102Implementing Custom Types103-------------------------104105To implement a custom type, you need to subclass the :class:`ParamType`106class. Override the :meth:`~ParamType.convert` method to convert the107value from a string to the correct type.108103The following code implements an integer type that accepts hex and octal104numbers in addition to normal integers, and converts them into regular105integers.106
31 unmodified lines
modified:docs/quickstart.rst+15 added-85 removed
1 unmodified line
2==========34.. currentmodule:: click56You can get the library directly from PyPI::6Install7----------------------8Install from PyPI::910 pip install click1110The installation into a :ref:`virtualenv` is heavily recommended.12Installing into a virtual environment is highly recommended. We suggest :ref:`virtualenv-heading`.1312.. _virtualenv:1314virtualenv15----------1617Virtualenv is probably what you want to use for developing Click18applications.1920What problem does virtualenv solve? Chances are that you want to use it21for other projects besides your Click script. But the more projects you22have, the more likely it is that you will be working with different23versions of Python itself, or at least different versions of Python24libraries. Let's face it: quite often libraries break backwards25compatibility, and it's unlikely that any serious application will have26zero dependencies. So what do you do if two or more of your projects have27conflicting dependencies?2829Virtualenv to the rescue! Virtualenv enables multiple side-by-side30installations of Python, one for each project. It doesn't actually31install separate copies of Python, but it does provide a clever way to32keep different project environments isolated.3334Create your project folder, then a virtualenv within it::3536 $ mkdir myproject37 $ cd myproject38 $ python3 -m venv .venv3940Now, whenever you want to work on a project, you only have to activate the41corresponding environment. On OS X and Linux, do the following::4243 $ . .venv/bin/activate44 (venv) $4546If you are a Windows user, the following command is for you::4748 > .venv\scripts\activate49 (venv) >5051Either way, you should now be using your virtualenv (notice how the prompt of52your shell has changed to show the active environment).5354And if you want to stop using the virtualenv, use the following command::5556 $ deactivate5758After doing this, the prompt of your shell should be as familiar as before.5960Now, let's move on. Enter the following command to get Click activated in your61virtualenv::6263 $ pip install click6465A few seconds later and you are good to go.6667Screencast and Examples14Examples15-----------------------1670There is a screencast available which shows the basic API of Click and71how to build simple applications with it. It also explores how to build72commands with subcommands.17Some 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.1874* `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.2877Examples of Click applications can be found in the documentation as well78as in the GitHub repository together with readme files:7980* ``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>`_9829Basic Concepts - Creating a Command30-----------------------------------3132Click is based on declaring commands through decorators. Internally, there
174 unmodified lines
added:docs/virtualenv.rst+54 added
1.. _virtualenv-heading:23Virtualenv4=========================56Why Use Virtualenv?7-------------------------89You should use `Virtualenv <https://virtualenv.pypa.io/en/latest/>`_ because:1011* It allows you to install multiple versions of the same dependency.1213* If you have an operating system version of Python, it prevents you from changing its dependencies and potentially messing up your os.1415How to Use Virtualenv16-----------------------------1718Create your project folder, then a virtualenv within it::1920 $ mkdir myproject21 $ cd myproject22 $ python3 -m venv .venv2324Now, whenever you want to work on a project, you only have to activate the25corresponding environment.2627.. tabs::2829 .. group-tab:: OSX/Linux3031 .. code-block:: text3233 $ . .venv/bin/activate34 (venv) $3536 .. group-tab:: Windows3738 .. code-block:: text3940 > .venv\scripts\activate41 (venv) >424344You are now using your virtualenv (notice how the prompt of your shell has changed to show the active environment).4546To install packages in the virtual environment::4748 $ pip install click4950And if you want to stop using the virtualenv, use the following command::5152 $ deactivate5354After doing this, the prompt of your shell should be as familiar as before.
modified:src/click/__init__.py+1 added
17 unmodified lines
18from .decorators import command as command19from .decorators import confirmation_option as confirmation_option20from .decorators import group as group21from .decorators import help_option as help_option22from .decorators import HelpOption as HelpOption23from .decorators import make_pass_decorator as make_pass_decorator24from .decorators import option as option25from .decorators import pass_context as pass_context26from .decorators import pass_obj as pass_obj
98 unmodified lines
modified:src/click/core.py+7 added-5 removed
1444 unmodified lines
1445 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`.14481449 .. versionchanged:: 8.21450 Merged with and replaces the ``MultiCommand`` base class.14511449 .. versionchanged:: 8.01450 The ``commands`` argument can be a list of command objects.14511452 .. versionchanged:: 8.21453 Merged with and replaces the ``MultiCommand`` base class.1454 """14551456 allow_extra_args = True1457 allow_interspersed_args = False
1170 unmodified lines
26282629 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 )26352636 if not opts and not secondary_opts:2637 raise TypeError(2638 f"No options defined but a name was passed ({name})."
355 unmodified lines
2994 ) -> 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 lines
modified:src/click/decorators.py+31 added-21 removed
1from __future__ import annotations23import inspect4import typing as t5from collections import abc6from functools import update_wrapper7from gettext import gettext as _89from .core import Argument
514 unmodified lines
524 kwargs["callback"] = callback525 return option(*param_decls, **kwargs)526527527def help_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]:528 """Add a ``--help`` option which immediately prints the help page528class HelpOption(Option):529 """Pre-configured ``--help`` option which immediately prints the help page530 and exits the program.531 """532531 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",)540535 :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)546540 def callback(ctx: Context, param: Parameter, value: bool) -> None:541 if not value or ctx.resilient_parsing:542 return547 super().__init__(param_decls, **kwargs)548549 @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()555547 if not param_decls:548 param_decls = ("--help",)556550 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"] = callback557def help_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]:558 """Decorator for the pre-configured ``--help`` option defined above.559560 :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 lines
5from gettext import gettext as _6from gettext import ngettext78from ._compat import get_text_stderr9from .globals import resolve_color_default10from .utils import echo11from .utils import format_filename1213if t.TYPE_CHECKING:
16 unmodified lines
30 exit_code = 13132 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 = message3839 def format_message(self) -> str:40 return self.message
4 unmodified lines
45 def show(self, file: t.IO[t.Any] | None = None) -> None:46 if file is None:47 file = get_text_stderr()4845 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 )545556class UsageError(ClickException):57 """An internal exception that signals a usage error. This typically
249 unmodified lines
modified:src/click/utils.py+1 added-1 removed
312 unmodified lines
313 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)320321 file.write(out) # type: ignore
306 unmodified lines
modified:tests/test_testing.py+21 added
3 unmodified lines
45import pytest67import click8from click.exceptions import ClickException9from click.testing import CliRunner101112def test_runner():
186 unmodified lines
199 assert result.output == f"{click.style('hello world', fg='blue')}\n"200 assert not result.exception201202203def test_with_color_errors():204 class CLIError(ClickException):205 def format_message(self) -> str:206 return click.style(self.message, fg="red")207208 @click.command()209 def cli():210 raise CLIError("Red error")211212 runner = CliRunner()213214 result = runner.invoke(cli)215 assert result.output == "Error: Red error\n"216 assert result.exception217218 result = runner.invoke(cli, color=True)219 assert result.output == f"Error: {click.style('Red error', fg='red')}\n"220 assert result.exception221222223def test_with_color_but_pause_not_blocking():224 @click.command()225 def cli():226 click.pause()
204 unmodified lines
modified:tests/test_utils.py+11 added-7 removed
34 unmodified lines
35 assert outstreams[0].getvalue() == b"\x1b[31mx\x1b[39m"363738def test_echo_custom_file():39 import io4041 f = io.StringIO()39 f = StringIO()40 click.echo("hello", file=f)41 assert f.getvalue() == "hello\n"4243
162 unmodified lines
206 out, err = capfd.readouterr()207 assert out == expected_output208209212@pytest.mark.skipif(WIN, reason="Test does not make sense on Windows.")210def test_echo_color_flag(monkeypatch, capfd):211 isatty = True212 monkeypatch.setattr(click._compat, "isatty", lambda x: isatty)213
14 unmodified lines
228 out, err = capfd.readouterr()229 assert out == f"{styled_text}\n"230231 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"238239 stream = StringIO()240 click.echo(styled_text, file=stream, color=True)241 assert stream.getvalue() == f"{styled_text}\n"242243244def 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 lines
modified:CHANGES.rst+2 added
76 unmodified lines
77- 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`.838485Version 8.1.786-------------
1100 unmodified lines