Resolve merge conflict from merging in main.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Edward G · committed by Edward G · parents ff4b7f7, c9f7d9d · Browse files · 18 files·+706 added−389 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
18 files+706 added−389 removed
- tests:+39 added−0 removed
- other:+667 added−389 removed
Provenance
- Commit
d79f0fb- Tree
ede54c5- Author
Edward G <edward.g2013@gmail.com>- Committer
Edward G <edward.g2013@gmail.com>- Parent 1
ff4b7f7- Parent 2
c9f7d9d
18 files changed+706 added−389 removed
modified:docs/advanced.rst+62 added
107 unmodified lines108 println()109 invoke(roll, args=["--rolls=2d12"])110 println()111 invoke(roll, input=["42", "2d12"])112+ :depth: 1113+ :local:114 115+.. _custom-groups:116+117+Custom Groups118+-------------119+120+You can customize the behavior of a group beyond the arguments it accepts by121+subclassing :class:`click.Group`.122+123+The most common methods to override are :meth:`~click.Group.get_command` and124+:meth:`~click.Group.list_commands`.125+126+The following example implements a basic plugin system that loads commands from127+Python files in a folder. The command is lazily loaded to avoid slow startup.128+129+.. code-block:: python130+131+ import importlib.util132+ import os133+ import click134+135+ class PluginGroup(click.Group):136+ def __init__(self, name=None, plugin_folder="commands", **kwargs):137+ super().__init__(name=name, **kwargs)138+ self.plugin_folder = plugin_folder139+140+ def list_commands(self, ctx):141+ rv = []142+143+ for filename in os.listdir(self.plugin_folder):144+ if filename.endswith(".py"):145+ rv.append(filename[:-3])146+147+ rv.sort()148+ return rv149+150+ def get_command(self, ctx, name):151+ path = os.path.join(self.plugin_folder, f"{name}.py")152+ spec = importlib.util.spec_from_file_location(name, path)153+ module = importlib.util.module_from_spec(spec)154+ spec.loader.exec_module(module)155+ return module.cli156+157+ cli = PluginGroup(158+ plugin_folder=os.path.join(os.path.dirname(__file__), "commands")159+ )160+161+ if __name__ == "__main__":162+ cli()163+164+Custom classes can also be used with decorators:165+166+.. code-block:: python167+168+ @click.group(169+ cls=PluginGroup,170+ plugin_folder=os.path.join(os.path.dirname(__file__), "commands")171+ )172+ def cli():173+ pass174+175 .. _aliases:176 177 Command Aliases178 ---------------487 unmodified linesmodified:docs/api.rst+6 added
4 unmodified lines5 6 This part of the documentation lists the full API reference of all public7 classes and functions.8 9+.. contents::10+ :depth: 111+ :local:12+13 Decorators14 ----------15 16 .. autofunction:: command185 unmodified lines202 203 .. autofunction:: add_completion_class204 205 206+.. _testing:207+208 Testing209 -------210 211 .. currentmodule:: click.testing6 unmodified linesadded:docs/commands-and-groups.rst+218 added
1+Basic Commands, Groups, Context2+================================3+4+.. currentmodule:: click5+6+Commands and Groups are the building blocks for Click applications. :class:`Command` wraps a function to make it into a cli command. :class:`Group` wraps Commands and Groups to make them into applications. :class:`Context` is how groups and commands communicate.7+8+.. contents::9+ :depth: 110+ :local:11+12+Basic Command Example13+----------------------14+A simple command decorator takes no arguments.15+16+.. click:example::17+ @click.command()18+ @click.option('--count', default=1)19+ def hello(count):20+ for x in range(count):21+ click.echo("Hello!")22+23+.. click:run::24+ invoke(hello, args=['--count', '2',])25+26+Renaming Commands27+------------------28+By default the command is the function name with underscores replaced by dashes. To change this pass the desired name into the first positional argument.29+30+.. click:example::31+ @click.command('say-hello')32+ @click.option('--count', default=1)33+ def hello(count):34+ for x in range(count):35+ click.echo("Hello!")36+37+.. click:run::38+ invoke(hello, args=['--count', '2',])39+40+Deprecating Commands41+---------------------42+To mark a command as deprecated pass in ``deprecated=True``43+44+.. click:example::45+ @click.command('say-hello', deprecated=True)46+ @click.option('--count', default=1)47+ def hello(count):48+ for x in range(count):49+ click.echo("Hello!")50+51+.. click:run::52+ invoke(hello, args=['--count', '2',])53+54+Basic Group Example55+---------------------56+A group wraps one or more commands. After being wrapped, the commands are nested under that group. You can see that on the help pages and in the execution. By default, invoking the group with no command shows the help page.57+58+.. click:example::59+ @click.group()60+ def greeting():61+ click.echo('Starting greeting ...')62+63+ @greeting.command('say-hello')64+ @click.option('--count', default=1)65+ def hello(count):66+ for x in range(count):67+ click.echo("Hello!")68+69+At the top level:70+71+.. click:run::72+73+ invoke(greeting)74+75+At the command level:76+77+.. click:run::78+79+ invoke(greeting, args=['say-hello'])80+ invoke(greeting, args=['say-hello', '--help'])81+82+As you can see from the above example, the function wrapped by the group decorator executes unless it is interrupted (for example by calling the help).83+84+Renaming Groups85+-----------------86+To have a name other than the decorated function name as the group name, pass it in as the first positional argument.87+88+.. click:example::89+ @click.group('greet-someone')90+ def greeting():91+ click.echo('Starting greeting ...')92+93+ @greeting.command('say-hello')94+ @click.option('--count', default=1)95+ def hello(count):96+ for x in range(count):97+ click.echo("Hello!")98+99+.. click:run::100+101+ invoke(greeting, args=['say-hello'])102+103+Group Invocation Without Command104+--------------------------------105+106+By default, if a group is passed without a command, the group is not invoked and a command automatically passes ``--help``. To change this, pass ``invoke_without_command=True`` to the group. The context object also includes information about whether or not the group invocation would go to a command nested under it.107+108+.. click:example::109+110+ @click.group(invoke_without_command=True)111+ @click.pass_context112+ def cli(ctx):113+ if ctx.invoked_subcommand is None:114+ click.echo('I was invoked without subcommand')115+ else:116+ click.echo(f"I am about to invoke {ctx.invoked_subcommand}")117+118+ @cli.command()119+ def sync():120+ click.echo('The subcommand')121+122+.. click:run::123+124+ invoke(cli, prog_name='tool', args=[])125+ invoke(cli, prog_name='tool', args=['sync'])126+127+128+129+Group Separation130+--------------------------131+Command :ref:`parameters` attached to a command belong only to that command.132+133+.. click:example::134+ @click.group()135+ def greeting():136+ pass137+138+ @greeting.command()139+ @click.option('--count', default=1)140+ def hello(count):141+ for x in range(count):142+ click.echo("Hello!")143+144+ @greeting.command()145+ @click.option('--count', default=1)146+ def goodbye(count):147+ for x in range(count):148+ click.echo("Goodbye!")149+150+.. click:run::151+152+ invoke(greeting, args=['hello', '--count', '2'])153+ invoke(greeting, args=['goodbye', '--count', '2'])154+ invoke(greeting)155+156+Additionally parameters for a given group belong only to that group and not to the commands under it. What this means is that options and arguments for a specific command have to be specified *after* the command name itself, but *before* any other command names.157+158+This behavior is observable with the ``--help`` option. Suppose we have a group called ``tool`` containing a command called ``sub``.159+160+- ``tool --help`` returns the help for the whole program (listing subcommands).161+- ``tool sub --help`` returns the help for the ``sub`` subcommand.162+- But ``tool --help sub`` treats ``--help`` as an argument for the main program. Click then invokes the callback for ``--help``, which prints the help and aborts the program before click can process the subcommand.163+164+Arbitrary Nesting165+------------------166+:class:`Commands <Command>` are attached to a :class:`Group`. Multiple groups can be attached to another group. Groups containing multiple groups can be attached to a group, and so on. To invoke a command nested under multiple groups, all the groups under which it is nested must be invoked.167+168+.. click:example::169+170+ @click.group()171+ def cli():172+ pass173+174+ # Not @click so that the group is registered now.175+ @cli.group()176+ def session():177+ click.echo('Starting session')178+179+ @session.command()180+ def initdb():181+ click.echo('Initialized the database')182+183+ @session.command()184+ def dropdb():185+ click.echo('Dropped the database')186+187+.. click:run::188+189+ invoke(cli, args=['session', 'initdb'])190+191+Lazily Attaching Commands192+--------------------------193+Most examples so far have attached the commands to a group immediately, but commands may be registered later. This could be used to split commands into multiple Python modules. Regardless of how they are attached, the commands are invoked identically.194+195+.. click:example::196+197+ @click.group()198+ def cli():199+ pass200+201+ @cli.command()202+ def initdb():203+ click.echo('Initialized the database')204+205+ @click.command()206+ def dropdb():207+ click.echo('Dropped the database')208+209+ cli.add_command(dropdb)210+211+.. click:run::212+213+ invoke(cli, args=['initdb'])214+ invoke(cli, args=['dropdb'])215+216+Context Object217+-------------------218+The :class:`Context` object is how commands and groups communicate.modified:docs/commands.rst+6 added-117 removed
1-Commands and Groups2-===================1+Advanced Groups and Context2+=============================3 4 .. currentmodule:: click5 6-The structure of a Click application is defined with :class:`Command`, which7-defines an individual named command, and :class:`Group`, which defines a nested8-collection of commands (or more groups) under a name.6+In addition to the capabilities covered in the previous section, Groups have more advanced capabilities that leverage the Context.7 8+.. contents::9+ :depth: 110+ :local:11 12 Callback Invocation13 -------------------14 24 unmodified lines39 invoke(cli, prog_name='tool.py')40 println()41 invoke(cli, prog_name='tool.py', args=['--debug', 'sync'])42 42-Passing Parameters43-------------------44-45-Click strictly separates parameters between commands and subcommands. What this46-means is that options and arguments for a specific command have to be specified47-*after* the command name itself, but *before* any other command names.48-49-This behavior is already observable with the predefined ``--help`` option.50-Suppose we have a program called ``tool.py``, containing a subcommand called51-``sub``.52-53-- ``tool.py --help`` will return the help for the whole program (listing54- subcommands).55-56-- ``tool.py sub --help`` will return the help for the ``sub`` subcommand.57-58-- But ``tool.py --help sub`` will treat ``--help`` as an argument for the main59- program. Click then invokes the callback for ``--help``, which prints the60- help and aborts the program before click can process the subcommand.61-43 Nested Handling and Contexts44 ----------------------------45 46 As you can see from the earlier example, the basic command group accepts a77 unmodified lines124 125 This is a very powerful concept that can be used to build very complex126 nested applications; see :ref:`complex-guide` for more information.127 147-148-Group Invocation Without Command149---------------------------------150-151-By default, a group is not invoked unless a subcommand is passed. In fact, not152-providing a command automatically passes ``--help`` by default. This behavior153-can be changed by passing ``invoke_without_command=True`` to a group. In that154-case, the callback is always invoked instead of showing the help page. The155-context object also includes information about whether or not the invocation156-would go to a subcommand.157-158-.. click:example::159-160- @click.group(invoke_without_command=True)161- @click.pass_context162- def cli(ctx):163- if ctx.invoked_subcommand is None:164- click.echo('I was invoked without subcommand')165- else:166- click.echo(f"I am about to invoke {ctx.invoked_subcommand}")167-168- @cli.command()169- def sync():170- click.echo('The subcommand')171-172-.. click:run::173-174- invoke(cli, prog_name='tool', args=[])175- invoke(cli, prog_name='tool', args=['sync'])176-177-178-.. _custom-groups:179-180-Custom Groups181--------------182-183-You can customize the behavior of a group beyond the arguments it accepts by184-subclassing :class:`click.Group`.185-186-The most common methods to override are :meth:`~click.Group.get_command` and187-:meth:`~click.Group.list_commands`.188-189-The following example implements a basic plugin system that loads commands from190-Python files in a folder. The command is lazily loaded to avoid slow startup.191-192-.. code-block:: python193-194- import importlib.util195- import os196- import click197-198- class PluginGroup(click.Group):199- def __init__(self, name=None, plugin_folder="commands", **kwargs):200- super().__init__(name=name, **kwargs)201- self.plugin_folder = plugin_folder202-203- def list_commands(self, ctx):204- rv = []205-206- for filename in os.listdir(self.plugin_folder):207- if filename.endswith(".py"):208- rv.append(filename[:-3])209-210- rv.sort()211- return rv212-213- def get_command(self, ctx, name):214- path = os.path.join(self.plugin_folder, f"{name}.py")215- spec = importlib.util.spec_from_file_location(name, path)216- module = importlib.util.module_from_spec(spec)217- spec.loader.exec_module(module)218- return module.cli219-220- cli = PluginGroup(221- plugin_folder=os.path.join(os.path.dirname(__file__), "commands")222- )223-224- if __name__ == "__main__":225- cli()226-227-Custom classes can also be used with decorators:228-229-.. code-block:: python230-231- @click.group(232- cls=PluginGroup,233- plugin_folder=os.path.join(os.path.dirname(__file__), "commands")234- )235- def cli():236- pass237-238-128 .. _command-chaining:129 130 Command Chaining131 ----------------297 unmodified linesmodified:docs/conf.py+1 added
16 unmodified lines17 "sphinx.ext.intersphinx",18 "sphinx_tabs.tabs",19 "sphinxcontrib.log_cabinet",20 "pallets_sphinx_themes",21+ "myst_parser",22 ]23 autodoc_member_order = "bysource"24 autodoc_typehints = "description"25 autodoc_preserve_defaults = True31 unmodified linesmodified:docs/index.rst+1 added
74 unmodified lines75 parameter-types76 options77 option-decorators78 arguments79+ commands-and-groups80 commands81 documentation82 prompts83 complex28 unmodified linesmodified:docs/parameters.rst+2 added
1+.. _parameters:2+3 Parameters4 ==========5 6 .. currentmodule:: click52 unmodified linesadded:docs/testing.md+198 added
1+# Testing Click Applications2+3+```{eval-rst}4+.. currentmodule:: click.testing5+```6+7+Click provides the {ref}`click.testing <testing>` module to help you invoke command line applications and check their behavior.8+9+These tools should only be used for testing since they change10+the entire interpreter state for simplicity. They are not thread-safe!11+12+The examples use [pytest](https://docs.pytest.org/en/stable/) style tests.13+14+```{contents}15+:depth: 116+:local: true17+```18+19+## Basic Example20+21+The key pieces are:22+ - {class}`CliRunner` - used to invoke commands as command line scripts.23+ - {class}`Result` - returned from {meth}`CliRunner.invoke`. Captures output data, exit code, optional exception, and captures the output as bytes and binary data.24+25+```{code-block} python26+:caption: hello.py27+28+import click29+30+@click.command()31+@click.argument('name')32+def hello(name):33+ click.echo(f'Hello {name}!')34+```35+36+```{code-block} python37+:caption: test_hello.py38+39+from click.testing import CliRunner40+from hello import hello41+42+def test_hello_world():43+ runner = CliRunner()44+ result = runner.invoke(hello, ['Peter'])45+ assert result.exit_code == 046+ assert result.output == 'Hello Peter!\n'47+```48+49+## Subcommands50+51+A subcommand name must be specified in the `args` parameter {meth}`CliRunner.invoke`:52+53+```{code-block} python54+:caption: sync.py55+56+import click57+58+@click.group()59+@click.option('--debug/--no-debug', default=False)60+def cli(debug):61+ click.echo(f"Debug mode is {'on' if debug else 'off'}")62+63+@cli.command()64+def sync():65+ click.echo('Syncing')66+```67+68+```{code-block} python69+:caption: test_sync.py70+71+from click.testing import CliRunner72+from sync import cli73+74+def test_sync():75+ runner = CliRunner()76+ result = runner.invoke(cli, ['--debug', 'sync'])77+ assert result.exit_code == 078+ assert 'Debug mode is on' in result.output79+ assert 'Syncing' in result.output80+```81+82+## Context Settings83+84+Additional keyword arguments passed to {meth}`CliRunner.invoke` will be used to construct the initial {class}`Context object <click.Context>`.85+For example, setting a fixed terminal width equal to 60:86+87+```{code-block} python88+:caption: sync.py89+90+import click91+92+@click.group()93+def cli():94+ pass95+96+@cli.command()97+def sync():98+ click.echo('Syncing')99+```100+101+```{code-block} python102+:caption: test_sync.py103+104+from click.testing import CliRunner105+from sync import cli106+107+def test_sync():108+ runner = CliRunner()109+ result = runner.invoke(cli, ['sync'], terminal_width=60)110+ assert result.exit_code == 0111+ assert 'Debug mode is on' in result.output112+ assert 'Syncing' in result.output113+```114+115+## File System Isolation116+117+The {meth}`CliRunner.isolated_filesystem` context manager sets the current working directory to a new, empty folder.118+119+```{code-block} python120+:caption: cat.py121+122+import click123+124+@click.command()125+@click.argument('f', type=click.File())126+def cat(f):127+ click.echo(f.read())128+```129+130+```{code-block} python131+:caption: test_cat.py132+133+from click.testing import CliRunner134+from cat import cat135+136+def test_cat():137+ runner = CliRunner()138+ with runner.isolated_filesystem():139+ with open('hello.txt', 'w') as f:140+ f.write('Hello World!')141+142+ result = runner.invoke(cat, ['hello.txt'])143+ assert result.exit_code == 0144+ assert result.output == 'Hello World!\n'145+```146+147+Pass in a path to control where the temporary directory is created.148+In this case, the directory will not be removed by Click. Its useful149+to integrate with a framework like Pytest that manages temporary files.150+151+```{code-block} python152+:caption: test_cat.py153+154+from click.testing import CliRunner155+from cat import cat156+157+def test_cat_with_path_specified():158+ runner = CliRunner()159+ with runner.isolated_filesystem('~/test_folder'):160+ with open('hello.txt', 'w') as f:161+ f.write('Hello World!')162+163+ result = runner.invoke(cat, ['hello.txt'])164+ assert result.exit_code == 0165+ assert result.output == 'Hello World!\n'166+```167+168+## Input Streams169+170+The test wrapper can provide input data for the input stream (stdin). This is very useful for testing prompts.171+172+```{code-block} python173+:caption: prompt.py174+175+import click176+177+@click.command()178+@click.option('--foo', prompt=True)179+def prompt(foo):180+ click.echo(f"foo={foo}")181+```182+183+```{code-block} python184+:caption: test_prompt.py185+186+from click.testing import CliRunner187+from prompt import prompt188+189+def test_prompts():190+ runner = CliRunner()191+ result = runner.invoke(prompt, input='wau wau\n')192+ assert not result.exception193+ assert result.output == 'Foo: wau wau\nfoo=wau wau\n'194+```195+196+Prompts will be emulated so they write the input data to197+the output stream as well. If hidden input is expected then this198+does not happen.deleted:docs/testing.rst-158 removed
1-Testing Click Applications2-==========================3-4-.. currentmodule:: click.testing5-6-For basic testing, Click provides the :mod:`click.testing` module which7-provides test functionality that helps you invoke command line8-applications and check their behavior.9-10-These tools should really only be used for testing as they change11-the entire interpreter state for simplicity and are not in any way12-thread-safe!13-14-Basic Testing15--------------16-17-The basic functionality for testing Click applications is the18-:class:`CliRunner` which can invoke commands as command line scripts. The19-:meth:`CliRunner.invoke` method runs the command line script in isolation20-and captures the output as both bytes and binary data.21-22-The return value is a :class:`Result` object, which has the captured output23-data, exit code, and optional exception attached:24-25-.. code-block:: python26- :caption: hello.py27-28- import click29-30- @click.command()31- @click.argument('name')32- def hello(name):33- click.echo(f'Hello {name}!')34-35-.. code-block:: python36- :caption: test_hello.py37-38- from click.testing import CliRunner39- from hello import hello40-41- def test_hello_world():42- runner = CliRunner()43- result = runner.invoke(hello, ['Peter'])44- assert result.exit_code == 045- assert result.output == 'Hello Peter!\n'46-47-For subcommand testing, a subcommand name must be specified in the `args` parameter of :meth:`CliRunner.invoke` method:48-49-.. code-block:: python50- :caption: sync.py51-52- import click53-54- @click.group()55- @click.option('--debug/--no-debug', default=False)56- def cli(debug):57- click.echo(f"Debug mode is {'on' if debug else 'off'}")58-59- @cli.command()60- def sync():61- click.echo('Syncing')62-63-.. code-block:: python64- :caption: test_sync.py65-66- from click.testing import CliRunner67- from sync import cli68-69- def test_sync():70- runner = CliRunner()71- result = runner.invoke(cli, ['--debug', 'sync'])72- assert result.exit_code == 073- assert 'Debug mode is on' in result.output74- assert 'Syncing' in result.output75-76-Additional keyword arguments passed to ``.invoke()`` will be used to construct the initial Context object.77-For example, if you want to run your tests against a fixed terminal width you can use the following::78-79- runner = CliRunner()80- result = runner.invoke(cli, ['--debug', 'sync'], terminal_width=60)81-82-File System Isolation83----------------------84-85-For basic command line tools with file system operations, the86-:meth:`CliRunner.isolated_filesystem` method is useful for setting the87-current working directory to a new, empty folder.88-89-.. code-block:: python90- :caption: cat.py91-92- import click93-94- @click.command()95- @click.argument('f', type=click.File())96- def cat(f):97- click.echo(f.read())98-99-.. code-block:: python100- :caption: test_cat.py101-102- from click.testing import CliRunner103- from cat import cat104-105- def test_cat():106- runner = CliRunner()107- with runner.isolated_filesystem():108- with open('hello.txt', 'w') as f:109- f.write('Hello World!')110-111- result = runner.invoke(cat, ['hello.txt'])112- assert result.exit_code == 0113- assert result.output == 'Hello World!\n'114-115-Pass ``temp_dir`` to control where the temporary directory is created.116-The directory will not be removed by Click in this case. This is useful117-to integrate with a framework like Pytest that manages temporary files.118-119-.. code-block:: python120-121- def test_keep_dir(tmp_path):122- runner = CliRunner()123-124- with runner.isolated_filesystem(temp_dir=tmp_path) as td:125- ...126-127-128-Input Streams129--------------130-131-The test wrapper can also be used to provide input data for the input132-stream (stdin). This is very useful for testing prompts, for instance:133-134-.. code-block:: python135- :caption: prompt.py136-137- import click138-139- @click.command()140- @click.option('--foo', prompt=True)141- def prompt(foo):142- click.echo(f"foo={foo}")143-144-.. code-block:: python145- :caption: test_prompt.py146-147- from click.testing import CliRunner148- from prompt import prompt149-150- def test_prompts():151- runner = CliRunner()152- result = runner.invoke(prompt, input='wau wau\n')153- assert not result.exception154- assert result.output == 'Foo: wau wau\nfoo=wau wau\n'155-156-Note that prompts will be emulated so that they write the input data to157-the output stream as well. If hidden input is expected then this158-obviously does not happen.modified:requirements/dev.in+1 added
1 unmodified line2 -r tests.txt3 -r typing.txt4 pre-commit5 tox6+sphinx-autobuildmodified:requirements/dev.txt+123 added-62 removed
1-#2-# This file is autogenerated by pip-compile with Python 3.133-# by the following command:4-#5-# pip-compile dev.in6-#1+# This file was autogenerated by uv via the following command:2+# uv pip compile -o dev.txt dev.in3 alabaster==1.0.08- # via sphinx4+ # via5+ # -r docs.txt6+ # sphinx7+anyio==4.8.08+ # via9+ # starlette10+ # watchfiles11 babel==2.16.010- # via sphinx11-build==1.2.2.post112- # via pip-tools13-cachetools==5.5.012+ # via13+ # -r docs.txt14+ # sphinx15+cachetools==5.5.116 # via tox17 certifi==2024.8.3016- # via requests18+ # via19+ # -r docs.txt20+ # requests21 cfgv==3.4.022 # via pre-commit23 chardet==5.2.024 # via tox25 charset-normalizer==3.4.022- # via requests23-click==8.1.726 # via25- # pip-compile-multi26- # pip-tools27+ # -r docs.txt28+ # requests29+click==8.1.830+ # via uvicorn31 colorama==0.4.628- # via tox32+ # via33+ # click34+ # pytest35+ # sphinx36+ # sphinx-autobuild37+ # tox38 distlib==0.3.939 # via virtualenv40 docutils==0.21.241 # via42+ # -r docs.txt43 # sphinx44 # sphinx-tabs35-filelock==3.16.145+exceptiongroup==1.2.246 # via47+ # anyio48+ # pytest49+filelock==3.17.050+ # via51 # tox52 # virtualenv53+h11==0.14.054+ # via uvicorn39-identify==2.6.155+identify==2.6.756 # via pre-commit57 idna==3.1042- # via requests58+ # via59+ # -r docs.txt60+ # anyio61+ # requests62 imagesize==1.4.144- # via sphinx63+ # via64+ # -r docs.txt65+ # sphinx66 iniconfig==2.0.046- # via pytest67+ # via68+ # -r tests.txt69+ # pytest70 jinja2==3.1.448- # via sphinx71+ # via72+ # -r docs.txt73+ # sphinx74 markupsafe==3.0.250- # via jinja275+ # via76+ # -r docs.txt77+ # jinja278 mypy==1.13.052- # via -r typing.in79+ # via -r typing.txt80 mypy-extensions==1.0.054- # via mypy81+ # via82+ # -r typing.txt83+ # mypy84 nodeenv==1.9.185 # via86+ # -r typing.txt87 # pre-commit88 # pyright89 packaging==24.190 # via61- # build91+ # -r docs.txt92+ # -r tests.txt93 # pallets-sphinx-themes94 # pyproject-api95 # pytest96 # sphinx97 # tox98 pallets-sphinx-themes==2.3.068- # via -r docs.in69-pip-compile-multi==2.6.470- # via -r dev.in71-pip-tools==7.4.172- # via pip-compile-multi99+ # via -r docs.txt100 platformdirs==4.3.6101 # via102 # tox103 # virtualenv104 pluggy==1.5.0105 # via106+ # -r tests.txt107 # pytest108 # tox81-pre-commit==4.0.1109+pre-commit==4.1.0110 # via -r dev.in111 pygments==2.18.0112 # via113+ # -r docs.txt114 # sphinx115 # sphinx-tabs116 pyproject-api==1.8.0117 # via tox89-pyproject-hooks==1.2.090- # via91- # build92- # pip-tools118 pyright==1.1.38694- # via -r typing.in119+ # via -r typing.txt120 pytest==8.3.396- # via -r tests.in121+ # via -r tests.txt122 pyyaml==6.0.2123 # via pre-commit124 requests==2.32.3100- # via sphinx125+ # via126+ # -r docs.txt127+ # sphinx128+sniffio==1.3.1129+ # via anyio130 snowballstemmer==2.2.0102- # via sphinx131+ # via132+ # -r docs.txt133+ # sphinx134 sphinx==8.1.3135 # via105- # -r docs.in136+ # -r docs.txt137 # pallets-sphinx-themes138+ # sphinx-autobuild139 # sphinx-issues140 # sphinx-notfound-page141 # sphinx-tabs142 # sphinxcontrib-log-cabinet143+sphinx-autobuild==2024.10.3144+ # via -r dev.in145 sphinx-issues==5.0.0112- # via -r docs.in146+ # via -r docs.txt147 sphinx-notfound-page==1.0.4148+ # via149+ # -r docs.txt114- # via pallets-sphinx-themes150+ # pallets-sphinx-themes151 sphinx-tabs==3.4.7116- # via -r docs.in152+ # via -r docs.txt153 sphinxcontrib-applehelp==2.0.0118- # via sphinx154+ # via155+ # -r docs.txt156+ # sphinx157 sphinxcontrib-devhelp==2.0.0120- # via sphinx158+ # via159+ # -r docs.txt160+ # sphinx161 sphinxcontrib-htmlhelp==2.1.0122- # via sphinx162+ # via163+ # -r docs.txt164+ # sphinx165 sphinxcontrib-jsmath==1.0.1124- # via sphinx166+ # via167+ # -r docs.txt168+ # sphinx169 sphinxcontrib-log-cabinet==1.0.1126- # via -r docs.in170+ # via -r docs.txt171 sphinxcontrib-qthelp==2.0.0128- # via sphinx172+ # via173+ # -r docs.txt174+ # sphinx175 sphinxcontrib-serializinghtml==2.0.0130- # via sphinx131-toposort==1.10132- # via pip-compile-multi176+ # via177+ # -r docs.txt178+ # sphinx179+starlette==0.45.3180+ # via sphinx-autobuild181+tomli==2.2.1182+ # via183+ # mypy184+ # pyproject-api185+ # pytest186+ # sphinx187+ # tox188 tox==4.23.2189 # via -r dev.in190 typing-extensions==4.12.2191 # via192+ # -r typing.txt193+ # anyio194 # mypy195 # pyright196+ # tox197+ # uvicorn198 urllib3==2.2.3140- # via requests141-virtualenv==20.27.0199 # via200+ # -r docs.txt201+ # requests202+uvicorn==0.34.0203+ # via sphinx-autobuild204+virtualenv==20.29.2205+ # via206 # pre-commit207 # tox145-wheel==0.44.0146- # via pip-tools147-148-# The following packages are considered to be unsafe in a requirements file:149-# pip150-# setuptools208+watchfiles==1.0.4209+ # via sphinx-autobuild210+websockets==15.0211+ # via sphinx-autobuildmodified:requirements/docs.in+1 added
1 pallets-sphinx-themes2 sphinx3 sphinxcontrib-log-cabinet4 sphinx-tabs5+myst-parsermodified:requirements/docs.txt+23 added-10 removed
1-#2-# This file is autogenerated by pip-compile with Python 3.133-# by the following command:4-#5-# pip-compile docs.in6-#1+# This file was autogenerated by uv via the following command:2+# uv pip compile -o docs.txt docs.in3 alabaster==1.0.04 # via sphinx5 babel==2.16.06 # via sphinx7 certifi==2024.8.308 # via requests9 charset-normalizer==3.4.010 # via requests11+colorama==0.4.612+ # via sphinx13 docutils==0.21.214 # via15+ # myst-parser16 # sphinx17 # sphinx-tabs18 idna==3.1019 # via requests20 imagesize==1.4.121 # via sphinx22 jinja2==3.1.424- # via sphinx23+ # via24+ # myst-parser25+ # sphinx26+markdown-it-py==3.0.027+ # via28+ # mdit-py-plugins29+ # myst-parser30 markupsafe==3.0.231 # via jinja232+mdit-py-plugins==0.4.233+ # via myst-parser34+mdurl==0.1.235+ # via markdown-it-py36+myst-parser==4.0.137+ # via -r docs.in38 packaging==24.139 # via40 # pallets-sphinx-themes41 # sphinx2 unmodified lines44 pygments==2.18.045 # via46 # sphinx47 # sphinx-tabs48+pyyaml==6.0.249+ # via myst-parser50 requests==2.32.351 # via sphinx52 snowballstemmer==2.2.053 # via sphinx54 sphinx==8.1.355 # via56 # -r docs.in57+ # myst-parser58 # pallets-sphinx-themes45- # sphinx-issues59 # sphinx-notfound-page60 # sphinx-tabs61 # sphinxcontrib-log-cabinet49-sphinx-issues==5.0.050- # via -r docs.in62 sphinx-notfound-page==1.0.463 # via pallets-sphinx-themes64 sphinx-tabs==3.4.765 # via -r docs.in10 unmodified lines76 sphinxcontrib-qthelp==2.0.077 # via sphinx78 sphinxcontrib-serializinghtml==2.0.079 # via sphinx80+tomli==2.2.181+ # via sphinx82 urllib3==2.2.383 # via requestsmodified:src/click/__init__.py-1 removed
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 HelpOption22 from .decorators import make_pass_decorator as make_pass_decorator23 from .decorators import option as option24 from .decorators import pass_context as pass_context25 from .decorators import pass_obj as pass_obj98 unmodified linesmodified:src/click/core.py+11 added-15 removed
1012 unmodified lines1013 all_names.difference_update(param.secondary_opts)1014 return list(all_names)1015 1016 def get_help_option(self, ctx: Context) -> Option | None:1017- """Returns the help option object."""1018- help_options = self.get_help_option_names(ctx)1017+ """Returns the help option object.1018 1019+ Skipped if :attr:`add_help_option` is ``False``.1020+ """1021+ help_option_names = self.get_help_option_names(ctx)1022+1020- if not help_options or not self.add_help_option:1023+ if not help_option_names or not self.add_help_option:1024 return None1025 1023- def show_help(ctx: Context, param: Parameter, value: str) -> None:1024- if value and not ctx.resilient_parsing:1025- echo(ctx.get_help(), color=ctx.color)1026- ctx.exit()1026+ # Avoid circular import.1027+ from .decorators import help_option1028 1028- return Option(1029- help_options,1030- is_flag=True,1031- is_eager=True,1032- expose_value=False,1033- callback=show_help,1034- help=_("Show this message and exit."),1035- )1029+ # apply help_option decorator and pop resulting option1030+ help_option(*help_option_names)(self)1031+ return self.params.pop() # type: ignore[return-value]1032 1033 def make_parser(self, ctx: Context) -> _OptionParser:1034 """Creates the underlying option parser for this command."""1035 parser = _OptionParser(ctx)2082 unmodified linesmodified:src/click/decorators.py+12 added-26 removed
1 from __future__ import annotations2 3 import inspect4 import typing as t5-from collections import abc5 from functools import update_wrapper6 from gettext import gettext as _7 8 from .core import Argument514 unmodified lines523 kwargs["callback"] = callback524 return option(*param_decls, **kwargs)525 526 528-class HelpOption(Option):527+def help_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]:528 """Pre-configured ``--help`` option which immediately prints the help page529 and exits the program.530+531+ :param param_decls: One or more option names. Defaults to the single532+ value ``"--help"``.533+ :param kwargs: Extra arguments are passed to :func:`option`.534 """535 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-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-547- super().__init__(param_decls, **kwargs)548-549- @staticmethod536 def show_help(ctx: Context, param: Parameter, value: bool) -> None:537 """Callback that print the help page on ``<stdout>`` and exits."""538 if value and not ctx.resilient_parsing:539 echo(ctx.get_help(), color=ctx.color)540 ctx.exit()541 542+ if not param_decls:543+ param_decls = ("--help",)544 557-def help_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]:558- """Decorator for the pre-configured ``--help`` option defined above.545+ kwargs.setdefault("is_flag", True)546+ kwargs.setdefault("expose_value", False)547+ kwargs.setdefault("is_eager", True)548+ kwargs.setdefault("help", _("Show this message and exit."))549+ kwargs.setdefault("callback", show_help)550 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)551 return option(*param_decls, **kwargs)modified:tests/test_options.py+39 added
722 unmodified lines723 assert "I am a help text" in result.output724 assert "you wont see me" not in result.output725 726 727+@pytest.mark.parametrize("custom_class", (True, False))728+@pytest.mark.parametrize(729+ ("name_specs", "expected"),730+ (731+ (732+ ("-h", "--help"),733+ " -h, --help Show this message and exit.\n",734+ ),735+ (736+ ("-h",),737+ " -h Show this message and exit.\n"738+ " --help Show this message and exit.\n",739+ ),740+ (741+ ("--help",),742+ " --help Show this message and exit.\n",743+ ),744+ ),745+)746+def test_help_option_custom_names_and_class(runner, custom_class, name_specs, expected):747+ class CustomHelpOption(click.Option):748+ pass749+750+ option_attrs = {}751+ if custom_class:752+ option_attrs["cls"] = CustomHelpOption753+754+ @click.command()755+ @click.help_option(*name_specs, **option_attrs)756+ def cmd():757+ pass758+759+ for arg in name_specs:760+ result = runner.invoke(cmd, [arg])761+ assert not result.exception762+ assert result.exit_code == 0763+ assert expected in result.output764+765+766 def test_bool_flag_with_type(runner):767 @click.command()768 @click.option("--shout/--no-shout", default=False, type=bool)769 def cmd(shout):333 unmodified linesmodified:CHANGES.rst+2 added
96 unmodified lines97 - Incorrect ``click.edit`` typing has been corrected. :pr:`2804`98 - ``Choice`` is now generic and supports any iterable value.99 This allows you to use enums and other non-``str`` values. :pr:`2796`100 :issue:`605`101+- Fix setup of help option's defaults when using a custom class on its102+ decorator. Removes ``HelpOption``. :issue:`2832` :pr:`2840`103 104 Version 8.1.8105 -------------106 1117 unmodified lines