Skip to content
Myr

Merge branch 'stable-into-main-2'

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* stable-into-main-2: (23 commits) use global contributing guide release version 8.1.8 Add links to third-party projects Remove some typing hints. remove test pypi update dev dependencies fix typos Fixed missing reset on _compat.should_strip_ansi. add additional issues to changelog Apply suggestions from code review for arguments docs. Use subprocess instead of os.system (#1477) Fix eagerness of help option generated by `help_option_names` (#2811) Fix a typo in File Opening Behaviors. More concisely phrase Environment Variables section. Clarify environment variables section. Cleanup handling files documentation. More robust check of bash version (#2639) Fix broken admonition block. Rewrite arguments docs more nicely. Fix capitalization. ... # Conflicts: # CONTRIBUTING.rst # docs/index.rst # docs/parameters.rst # requirements/dev.txt # requirements/docs.txt # src/click/__init__.py # src/click/_termui_impl.py # src/click/core.py # tests/test_utils.py

authored by Kevin Deldycke · committed by Kevin Deldycke · parents c9f7d9d, d14dee0 · Browse files · 15 files+371 added−190 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+371 added−190 removed

  • tests:+133 added−0 removed
  • other:+238 added−190 removed

15 files+371 added−190 removed

modified:.github/workflows/publish.yaml+1 added-5 removed
modified:docs/arguments.rst+63 added-171 removed
3 unmodified lines
4=========56.. currentmodule:: click78Arguments work similarly to :ref:`options <options>` but are positional.9They also only support a subset of the features of options due to their10syntactical nature. Click will also not attempt to document arguments for11you and wants you to :ref:`document them manually <documenting-arguments>`12in order to avoid ugly help pages.8Arguments are:910* Are positional in nature.11* Similar to a limited version of :ref:`options <options>` that can take an arbitrary number of inputs12* :ref:`Documented manually <documenting-arguments>`.1314Useful and often used kwargs are:1516* ``default``: Passes a default.17* ``nargs``: Sets the number of arguments. Set to -1 to take an arbitrary number.1819Basic Arguments20---------------2117The most basic option is a simple string argument of one value. If no18type is provided, the type of the default value is used, and if no default19value is provided, the type is assumed to be :data:`STRING`.22A minimal :class:`click.Argument` solely takes one string argument: the name of the argument. This will assume the argument is required, has no default, and is of the type ``str``.2324Example:2526.. click:example::2728 @click.command()29 @click.argument('filename')27 def touch(filename):30 def touch(filename: str):31 """Print FILENAME."""32 click.echo(filename)3331And what it looks like:34And from the command line:3536.. click:run::3738 invoke(touch, args=['foo.txt'])3937Variadic Arguments38------------------4040The second most common version is variadic arguments where a specific (or41unlimited) number of arguments is accepted. This can be controlled with42the ``nargs`` parameter. If it is set to ``-1``, then an unlimited number43of arguments is accepted.41An argument may be assigned a :ref:`parameter type <parameter-types>`. If no type is provided, the type of the default value is used. If no default value is provided, the type is assumed to be :data:`STRING`.4245The value is then passed as a tuple. Note that only one argument can be46set to ``nargs=-1``, as it will eat up all arguments.43.. admonition:: Note on Required Arguments4448Example:45 It is possible to make an argument required by setting ``required=True``. It is not recommended since we think command line tools should gracefully degrade into becoming no ops. We think this because command line tools are often invoked with wildcard inputs and they should not error out if the wildcard is empty.4647Multiple Arguments48-----------------------------------4950To set the number of argument use the ``nargs`` kwarg. It can be set to any positive integer and -1. Setting it to -1, makes the number of arguments arbitrary (which is called variadic) and can only be used once. The arguments are then packed as a tuple and passed to the function.5152.. click:example::5354 @click.command()53 @click.argument('src', nargs=-1)54 @click.argument('dst', nargs=1)55 def copy(src, dst):55 @click.argument('src', nargs=1)56 @click.argument('dsts', nargs=-1)57 def copy(src: str, dsts: tuple[str, ...]):58 """Move file SRC to DST."""57 for fn in src:58 click.echo(f"move {fn} to folder {dst}")59 for destination in dsts:60 click.echo(f"Copy {src} to folder {destination}")6160And what it looks like:62And from the command line:6364.. click:run::6564 invoke(copy, args=['foo.txt', 'bar.txt', 'my_folder'])66 invoke(copy, args=['foo.txt', 'usr/david/foo.txt', 'usr/mitsuko/foo.txt'])6766Note that this is not how you would write this application. The reason67for this is that in this particular example the arguments are defined as68strings. Filenames, however, are not strings! They might be on certain69operating systems, but not necessarily on all. For better ways to write70this, see the next sections.68.. admonition:: Note on Handling Files6972.. admonition:: Note on Non-Empty Variadic Arguments70 This is not how you should handle files and files paths. This merely used as a simple example. See :ref:`handling-files` to learn more about how to handle files in parameters.7174 If you come from ``argparse``, you might be missing support for setting75 ``nargs`` to ``+`` to indicate that at least one argument is required.72Argument Escape Sequences73---------------------------7477 This is supported by setting ``required=True``. However, this should78 not be used if you can avoid it as we believe scripts should gracefully79 degrade into becoming noops if a variadic argument is empty. The80 reason for this is that very often, scripts are invoked with wildcard81 inputs from the command line and they should not error out if the82 wildcard is empty.75If you want to process arguments that look like options, like a file named ``-foo.txt`` or ``--foo.txt`` , you must pass the ``--`` separator first. After you pass the ``--``, you may only pass arguments. This is a common feature for POSIX command line tools.7684.. _file-args:77Example usage:7886File Arguments87--------------8889Since all the examples have already worked with filenames, it makes sense90to explain how to deal with files properly. Command line tools are more91fun if they work with files the Unix way, which is to accept ``-`` as a92special file that refers to stdin/stdout.9394Click supports this through the :class:`click.File` type which95intelligently handles files for you. It also deals with Unicode and bytes96correctly for all versions of Python so your script stays very portable.9798Example:9979.. click:example::8081 @click.command()103 @click.argument('input', type=click.File('rb'))104 @click.argument('output', type=click.File('wb'))105 def inout(input, output):106 """Copy contents of INPUT to OUTPUT."""107 while True:108 chunk = input.read(1024)109 if not chunk:110 break111 output.write(chunk)82 @click.argument('files', nargs=-1, type=click.Path())83 def touch(files):84 """Print all FILES file names."""85 for filename in files:86 click.echo(filename)87113And what it does:88And from the command line:8990.. click:run::91117 with isolated_filesystem():118 invoke(inout, args=['-', 'hello.txt'], input=['hello'],119 terminate_input=True)120 invoke(inout, args=['hello.txt', '-'])92 invoke(touch, ['--', '-foo.txt', 'bar.txt'])93122File Path Arguments123-------------------94If you don't like the ``--`` marker, you can set ignore_unknown_options to True to avoid checking unknown options:95125In the previous example, the files were opened immediately. But what if126we just want the filename? The naïve way is to use the default string127argument type. The :class:`Path` type has several checks available which raise nice128errors if they fail, such as existence. Filenames in these error messages are formatted129with :func:`format_filename`, so any undecodable bytes will be printed nicely.130131Example:13296.. click:example::97135 @click.command()136 @click.argument('filename', type=click.Path(exists=True))137 def touch(filename):138 """Print FILENAME if the file exists."""139 click.echo(click.format_filename(filename))98 @click.command(context_settings={"ignore_unknown_options": True})99 @click.argument('files', nargs=-1, type=click.Path())100 def touch(files):101 """Print all FILES file names."""102 for filename in files:103 click.echo(filename)104141And what it does:105And from the command line:106107.. click:run::108145 with isolated_filesystem():146 with open('hello.txt', 'w') as f:147 f.write('Hello World!\n')148 invoke(touch, args=['hello.txt'])109 invoke(touch, ['-foo.txt', 'bar.txt'])149 println()150 invoke(touch, args=['missing.txt'])110111153File Opening Safety154-------------------155156The :class:`FileType` type has one problem it needs to deal with, and that157is to decide when to open a file. The default behavior is to be158"intelligent" about it. What this means is that it will open stdin/stdout159and files opened for reading immediately. This will give the user direct160feedback when a file cannot be opened, but it will only open files161for writing the first time an IO operation is performed by automatically162wrapping the file in a special wrapper.163164This behavior can be forced by passing ``lazy=True`` or ``lazy=False`` to165the constructor. If the file is opened lazily, it will fail its first IO166operation by raising an :exc:`FileError`.167168Since files opened for writing will typically immediately empty the file,169the lazy mode should only be disabled if the developer is absolutely sure170that this is intended behavior.171172Forcing lazy mode is also very useful to avoid resource handling173confusion. If a file is opened in lazy mode, it will receive a174``close_intelligently`` method that can help figure out if the file175needs closing or not. This is not needed for parameters, but is176necessary for manually prompting with the :func:`prompt` function as you177do not know if a stream like stdout was opened (which was already open178before) or a real file that needs closing.179180Starting with Click 2.0, it is also possible to open files in atomic mode by181passing ``atomic=True``. In atomic mode, all writes go into a separate182file 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.185186112.. _environment-variables:113114Environment Variables115---------------------116192Like options, arguments can also grab values from an environment variable.193Unlike options, however, this is only supported for explicitly named194environment variables.117Arguments can use environment variables. To do so, pass the name(s) of the environment variable(s) via `envvar` in ``click.argument``.118196Example usage:119Checking one environment variable:120121.. click:example::122123 @click.command()
6 unmodified lines
130131.. click:run::132133 with isolated_filesystem():134 # Writing the file in the filesystem.135 with open('hello.txt', 'w') as f:136 f.write('Hello World!')137 invoke(echo, env={'SRC': 'hello.txt'})138215In that case, it can also be a list of different environment variables216where the first one is picked.139218Generally, this feature is not recommended because it can cause the user219a lot of confusion.140Checking multiple environment variables:141221Option-Like Arguments222---------------------223224Sometimes, you want to process arguments that look like options. For225instance, imagine you have a file named ``-foo.txt``. If you pass this as226an argument in this manner, Click will treat it as an option.227228To solve this, Click does what any POSIX style command line script does,229and that is to accept the string ``--`` as a separator for options and230arguments. After the ``--`` marker, all further parameters are accepted as231arguments.232233Example usage:234142.. click:example::143144 @click.command()238 @click.argument('files', nargs=-1, type=click.Path())239 def touch(files):240 """Print all FILES file names."""241 for filename in files:242 click.echo(filename)145 @click.argument('src', envvar=['SRC', 'SRC_2'], type=click.File('r'))146 def echo(src):147 """Print value of SRC environment variable."""148 click.echo(src.read())149150And from the command line:151152.. click:run::153248 invoke(touch, ['--', '-foo.txt', 'bar.txt'])249250If you don't like the ``--`` marker, you can set ignore_unknown_options to251True to avoid checking unknown options:252253.. click:example::254255 @click.command(context_settings={"ignore_unknown_options": True})256 @click.argument('files', nargs=-1, type=click.Path())257 def touch(files):258 """Print all FILES file names."""259 for filename in files:260 click.echo(filename)261262And from the command line:263264.. click:run::265266 invoke(touch, ['-foo.txt', 'bar.txt'])154 with isolated_filesystem():155 # Writing the file in the filesystem.156 with open('hello.txt', 'w') as f:157 f.write('Hello World from second variable!')158 invoke(echo, env={'SRC_2': 'hello.txt'})
modified:docs/contrib.rst+37 added
16 unmodified lines
17Please note that the quality and stability of those packages may be different18than Click itself. While published under a common organization, they are still19separate from Click and the Pallets maintainers.202122Third-party projects23--------------------2425Other projects that extend Click's features are available outside of the26click-contrib_ organization.2728Some of the most popular and actively maintained are listed below:2930========================================================== =========================================================================================== ================================================================================================= ======================================================================================================31Project Description Popularity Activity32========================================================== =========================================================================================== ================================================================================================= ======================================================================================================33`Typer <https://github.com/fastapi/typer>`_ Use Python type hints to create CLI apps. .. image:: https://img.shields.io/github/stars/fastapi/typer?label=%20&style=flat-square .. image:: https://img.shields.io/github/last-commit/fastapi/typer?label=%20&style=flat-square34 :alt: GitHub stars :alt: Last commit35`rich-click <https://github.com/ewels/rich-click>`_ Format help outputwith Rich. .. image:: https://img.shields.io/github/stars/ewels/rich-click?label=%20&style=flat-square .. image:: https://img.shields.io/github/last-commit/ewels/rich-click?label=%20&style=flat-square36 :alt: GitHub stars :alt: Last commit37`click-app <https://github.com/simonw/click-app>`_ Cookiecutter template for creating new CLIs. .. image:: https://img.shields.io/github/stars/simonw/click-app?label=%20&style=flat-square .. image:: https://img.shields.io/github/last-commit/simonw/click-app?label=%20&style=flat-square38 :alt: GitHub stars :alt: Last commit39`Cloup <https://github.com/janluke/cloup>`_ Adds option groups, constraints, command aliases, help themes, suggestions and more. .. image:: https://img.shields.io/github/stars/janluke/cloup?label=%20&style=flat-square .. image:: https://img.shields.io/github/last-commit/janluke/cloup?label=%20&style=flat-square40 :alt: GitHub stars :alt: Last commit41`Click Extra <https://github.com/kdeldycke/click-extra>`_ Cloup + colorful ``--help``, ``--config``, ``--show-params``, ``--verbosity`` options, etc. .. image:: https://img.shields.io/github/stars/kdeldycke/click-extra?label=%20&style=flat-square .. image:: https://img.shields.io/github/last-commit/kdeldycke/click-extra?label=%20&style=flat-square42 :alt: GitHub stars :alt: Last commit43========================================================== =========================================================================================== ================================================================================================= ======================================================================================================4445.. note::4647 To make it into the list above, a project:4849 - must be actively maintained (at least one commit in the last year)50 - must have a reasonable number of stars (at least 20)5152 If you have a project that meets these criteria, please open a pull request53 to add it to the list.5455 If a project is no longer maintained or does not meet the criteria above,56 please open a pull request to remove it from the list.5758.. _click-contrib: https://github.com/click-contrib/
added:docs/handling-files.rst+90 added
1.. _handling-files:23Handling Files4================56.. currentmodule:: click78Click has built in features to support file and file path handling. The examples use arguments but the same principle applies to options as well.910.. _file-args:1112File Arguments13-----------------1415Click supports working with files with the :class:`File` type. Some notable features are:1617* Support for ``-`` to mean a special file that refers to stdin when used for reading, and stdout when used for writing. This is a common pattern for POSIX command line utilities.18* Deals with ``str`` and ``bytes`` correctly for all versions of Python.1920Example:2122.. click:example::2324 @click.command()25 @click.argument('input', type=click.File('rb'))26 @click.argument('output', type=click.File('wb'))27 def inout(input, output):28 """Copy contents of INPUT to OUTPUT."""29 while True:30 chunk = input.read(1024)31 if not chunk:32 break33 output.write(chunk)3435And from the command line:3637.. click:run::3839 with isolated_filesystem():40 invoke(inout, args=['-', 'hello.txt'], input=['hello'],41 terminate_input=True)42 invoke(inout, args=['hello.txt', '-'])4344File Path Arguments45----------------------4647For handling paths, the :class:`Path` type is better than a ``str``. Some notable features are:4849* The ``exists`` argument will verify whether the path exists.50* ``readable``, ``writable``, and ``executable`` can perform permission checks.51* ``file_okay`` and ``dir_okay`` allow specifying whether files/directories are accepted.52* Error messages are nicely formatted using :func:`format_filename` so any undecodable bytes will be printed nicely.5354See :class:`Path` for all features.5556Example:5758.. click:example::5960 @click.command()61 @click.argument('filename', type=click.Path(exists=True))62 def touch(filename):63 """Print FILENAME if the file exists."""64 click.echo(click.format_filename(filename))6566And from the command line:6768.. click:run::6970 with isolated_filesystem():71 with open('hello.txt', 'w') as f:72 f.write('Hello World!\n')73 invoke(touch, args=['hello.txt'])74 println()75 invoke(touch, args=['missing.txt'])767778File Opening Behaviors79-----------------------------8081The :class:`File` type attempts to be "intelligent" about when to open a file. Stdin/stdout and files opened for reading will be opened immediately. This will give the user direct feedback when a file cannot be opened. Files opened for writing will only be open on the first IO operation. This is done by automatically wrapping the file in a special wrapper.8283File open behavior can be controlled by the boolean kwarg ``lazy``. If a file is opened lazily:8485* A failure at first IO operation will happen by raising an :exc:`FileError`.86* It can help minimize resource handling confusion. If a file is opened in lazy mode, it will call :meth:`LazyFile.close_intelligently` to help figure out if the file needs closing or not. This is not needed for parameters, but is necessary for manually prompting. For manual prompts with the :func:`prompt` function you do not know if a stream like stdout was opened (which was already open before) or a real file was opened (that needs closing).8788Since files opened for writing will typically empty the file, the lazy mode should only be disabled if the developer is absolutely sure that this is intended behavior.8990It is also possible to open files in atomic mode by passing ``atomic=True``. In atomic mode, all writes go into a separate file in the same folder, and upon completion, the file will be moved over to the original location. This is useful if a file regularly read by other users is modified.
modified:requirements/build.txt+1 added-1 removed
4 unmodified lines
5# pip-compile build.in6#7build==1.2.2.post18 # via -r build.in9packaging==24.19packaging==24.210 # via build11pyproject-hooks==1.2.012 # via build
modified:requirements/tests.txt+2 added-2 removed
4 unmodified lines
5# pip-compile tests.in6#7iniconfig==2.0.08 # via pytest9packaging==24.19packaging==24.210 # via pytest11pluggy==1.5.012 # via pytest13pytest==8.3.313pytest==8.3.414 # via -r tests.in
modified:requirements/typing.txt+1 added-1 removed
8 unmodified lines
9mypy-extensions==1.0.010 # via mypy11nodeenv==1.9.112 # via pyright13pyright==1.1.38613pyright==1.1.39014 # via -r typing.in15typing-extensions==4.12.216 # via17 # mypy
1 unmodified line
modified:src/click/shell_completion.py+11 added-4 removed
301 unmodified lines
302 source_template = _SOURCE_BASH303304 @staticmethod305 def _check_version() -> None:306 import shutil307 import subprocess308308 output = subprocess.run(309 ["bash", "-c", 'echo "${BASH_VERSION}"'], stdout=subprocess.PIPE310 )311 match = re.search(r"^(\d+)\.(\d+)\.\d+", output.stdout.decode())309 bash_exe = shutil.which("bash")310311 if bash_exe is None:312 match = None313 else:314 output = subprocess.run(315 [bash_exe, "--norc", "-c", 'echo "${BASH_VERSION}"'],316 stdout=subprocess.PIPE,317 )318 match = re.search(r"^(\d+)\.(\d+)\.\d+", output.stdout.decode())319320 if match is not None:321 major, minor = match.groups()322323 if major < "4" or major == "4" and minor < "4":
321 unmodified lines
modified:src/click/testing.py+2 added
373 unmodified lines
374 old_visible_prompt_func = termui.visible_prompt_func375 old_hidden_prompt_func = termui.hidden_prompt_func376 old__getchar_func = termui._getchar377 old_should_strip_ansi = utils.should_strip_ansi # type: ignore378 old__compat_should_strip_ansi = _compat.should_strip_ansi379 termui.visible_prompt_func = visible_input380 termui.hidden_prompt_func = hidden_input381 termui._getchar = _getchar382 utils.should_strip_ansi = should_strip_ansi # type: ignore
26 unmodified lines
409 termui.visible_prompt_func = old_visible_prompt_func410 termui.hidden_prompt_func = old_hidden_prompt_func411 termui._getchar = old__getchar_func412 utils.should_strip_ansi = old_should_strip_ansi # type: ignore413 _compat.should_strip_ansi = old__compat_should_strip_ansi414 formatting.FORCED_WIDTH = old_forced_width415416 def invoke(417 self,
140 unmodified lines
modified:src/click/types.py+7 added-4 removed
724 unmodified lines
725 file lazily for reading, it is still opened temporarily for validation, but726 will not be held open until first IO. lazy is mainly useful when opening727 for writing to avoid creating the file until it is needed.728729 Starting with Click 2.0, files can also be opened atomically in which730 case all writes go into a separate file in the same folder and upon731 completion the file will be moved over to the original location. This732 is useful if a file regularly read by other users is modified.729 Files can also be opened atomically in which case all writes go into a730 separate file in the same folder and upon completion the file will731 be moved over to the original location. This is useful if a file732 regularly read by other users is modified.733734 See :ref:`file-args` for more information.735736 .. versionchanged:: 2.0737 Added the ``atomic`` parameter.738 """739740 name = "filename"741 envvar_list_splitter: t.ClassVar[str] = os.path.pathsep
422 unmodified lines
modified:tests/test_commands.py+132 added
299 unmodified lines
300 result = runner.invoke(cli, ["b"], default_map={"b": {"x": 3}})301 assert result.exit_code == 0302303304@pytest.mark.parametrize(305 ("invocation_order", "declaration_order", "expected_order"),306 [307 # Non-eager options.308 ([], ["-a"], ["-a"]),309 (["-a"], ["-a"], ["-a"]),310 ([], ["-a", "-c"], ["-a", "-c"]),311 (["-a"], ["-a", "-c"], ["-a", "-c"]),312 (["-c"], ["-a", "-c"], ["-c", "-a"]),313 ([], ["-c", "-a"], ["-c", "-a"]),314 (["-a"], ["-c", "-a"], ["-a", "-c"]),315 (["-c"], ["-c", "-a"], ["-c", "-a"]),316 (["-a", "-c"], ["-a", "-c"], ["-a", "-c"]),317 (["-c", "-a"], ["-a", "-c"], ["-c", "-a"]),318 # Eager options.319 ([], ["-b"], ["-b"]),320 (["-b"], ["-b"], ["-b"]),321 ([], ["-b", "-d"], ["-b", "-d"]),322 (["-b"], ["-b", "-d"], ["-b", "-d"]),323 (["-d"], ["-b", "-d"], ["-d", "-b"]),324 ([], ["-d", "-b"], ["-d", "-b"]),325 (["-b"], ["-d", "-b"], ["-b", "-d"]),326 (["-d"], ["-d", "-b"], ["-d", "-b"]),327 (["-b", "-d"], ["-b", "-d"], ["-b", "-d"]),328 (["-d", "-b"], ["-b", "-d"], ["-d", "-b"]),329 # Mixed options.330 ([], ["-a", "-b", "-c", "-d"], ["-b", "-d", "-a", "-c"]),331 (["-a"], ["-a", "-b", "-c", "-d"], ["-b", "-d", "-a", "-c"]),332 (["-b"], ["-a", "-b", "-c", "-d"], ["-b", "-d", "-a", "-c"]),333 (["-c"], ["-a", "-b", "-c", "-d"], ["-b", "-d", "-c", "-a"]),334 (["-d"], ["-a", "-b", "-c", "-d"], ["-d", "-b", "-a", "-c"]),335 (["-a", "-b"], ["-a", "-b", "-c", "-d"], ["-b", "-d", "-a", "-c"]),336 (["-b", "-a"], ["-a", "-b", "-c", "-d"], ["-b", "-d", "-a", "-c"]),337 (["-d", "-c"], ["-a", "-b", "-c", "-d"], ["-d", "-b", "-c", "-a"]),338 (["-c", "-d"], ["-a", "-b", "-c", "-d"], ["-d", "-b", "-c", "-a"]),339 (["-a", "-b", "-c", "-d"], ["-a", "-b", "-c", "-d"], ["-b", "-d", "-a", "-c"]),340 (["-b", "-d", "-a", "-c"], ["-a", "-b", "-c", "-d"], ["-b", "-d", "-a", "-c"]),341 ([], ["-b", "-d", "-e", "-a", "-c"], ["-b", "-d", "-e", "-a", "-c"]),342 (["-a", "-d"], ["-b", "-d", "-e", "-a", "-c"], ["-d", "-b", "-e", "-a", "-c"]),343 (["-c", "-d"], ["-b", "-d", "-e", "-a", "-c"], ["-d", "-b", "-e", "-c", "-a"]),344 ],345)346def test_iter_params_for_processing(347 invocation_order, declaration_order, expected_order348):349 parameters = {350 "-a": click.Option(["-a"]),351 "-b": click.Option(["-b"], is_eager=True),352 "-c": click.Option(["-c"]),353 "-d": click.Option(["-d"], is_eager=True),354 "-e": click.Option(["-e"], is_eager=True),355 }356357 invocation_params = [parameters[opt_id] for opt_id in invocation_order]358 declaration_params = [parameters[opt_id] for opt_id in declaration_order]359 expected_params = [parameters[opt_id] for opt_id in expected_order]360361 assert (362 click.core.iter_params_for_processing(invocation_params, declaration_params)363 == expected_params364 )365366367def test_help_param_priority(runner):368 """Cover the edge-case in which the eagerness of help option was not369 respected, because it was internally generated multiple times.370371 See: https://github.com/pallets/click/pull/2811372 """373374 def print_and_exit(ctx, param, value):375 if value:376 click.echo(f"Value of {param.name} is: {value}")377 ctx.exit()378379 @click.command(context_settings={"help_option_names": ("--my-help",)})380 @click.option("-a", is_flag=True, expose_value=False, callback=print_and_exit)381 @click.option(382 "-b", is_flag=True, expose_value=False, callback=print_and_exit, is_eager=True383 )384 def cli():385 pass386387 # --my-help is properly called and stop execution.388 result = runner.invoke(cli, ["--my-help"])389 assert "Value of a is: True" not in result.stdout390 assert "Value of b is: True" not in result.stdout391 assert "--my-help" in result.stdout392 assert result.exit_code == 0393394 # -a is properly called and stop execution.395 result = runner.invoke(cli, ["-a"])396 assert "Value of a is: True" in result.stdout397 assert "Value of b is: True" not in result.stdout398 assert "--my-help" not in result.stdout399 assert result.exit_code == 0400401 # -a takes precedence over -b and stop execution.402 result = runner.invoke(cli, ["-a", "-b"])403 assert "Value of a is: True" not in result.stdout404 assert "Value of b is: True" in result.stdout405 assert "--my-help" not in result.stdout406 assert result.exit_code == 0407408 # --my-help is eager by default so takes precedence over -a and stop409 # execution, whatever the order.410 for args in [["-a", "--my-help"], ["--my-help", "-a"]]:411 result = runner.invoke(cli, args)412 assert "Value of a is: True" not in result.stdout413 assert "Value of b is: True" not in result.stdout414 assert "--my-help" in result.stdout415 assert result.exit_code == 0416417 # Both -b and --my-help are eager so they're called in the order they're418 # invoked by the user.419 result = runner.invoke(cli, ["-b", "--my-help"])420 assert "Value of a is: True" not in result.stdout421 assert "Value of b is: True" in result.stdout422 assert "--my-help" not in result.stdout423 assert result.exit_code == 0424425 # But there was a bug when --my-help is called before -b, because the426 # --my-help option created by click via help_option_names is internally427 # created twice and is not the same object, breaking the priority order428 # produced by iter_params_for_processing.429 result = runner.invoke(cli, ["--my-help", "-b"])430 assert "Value of a is: True" not in result.stdout431 assert "Value of b is: True" not in result.stdout432 assert "--my-help" in result.stdout433 assert result.exit_code == 0434435436def test_unprocessed_options(runner):437 @click.command(context_settings=dict(ignore_unknown_options=True))438 @click.argument("args", nargs=-1, type=click.UNPROCESSED)439 @click.option("--verbose", "-v", count=True)
108 unmodified lines
modified:tests/test_imports.py+1 added
47 unmodified lines
48 "enum",49 "typing",50 "types",51 "gettext",52 "shutil",53}5455if WIN:56 ALLOWED_IMPORTS.update(["ctypes", "ctypes.wintypes", "msvcrt", "time"])
14 unmodified lines
modified:.pre-commit-config.yaml+1 added-1 removed
1repos:2 - repo: https://github.com/astral-sh/ruff-pre-commit3 rev: v0.7.13 rev: v0.8.14 hooks:5 - id: ruff6 - id: ruff-format7 - repo: https://github.com/pre-commit/pre-commit-hooks
7 unmodified lines
modified:CHANGES.rst+14 added-1 removed
102 unmodified lines
103104Version 8.1.8105-------------106107Unreleased107Released 2024-12-19108109- Fix an issue with type hints for ``click.open_file()``. :issue:`2717`110- Fix issue where error message for invalid ``click.Path`` displays on111 multiple lines. :issue:`2697`
4 unmodified lines
116- Show correct value for flag default when using ``default_map``.117 :issue:`2632`118- Fix ``click.echo(color=...)`` passing ``color`` to coloroma so it can be119 forced on Windows. :issue:`2606`.120- More robust bash version check, fixing problem on Windows with git-bash.121 :issue:`2638`122- Cache the help option generated by the ``help_option_names`` setting to123 respect its eagerness. :pr:`2811`124- Replace uses of ``os.system`` with ``subprocess.Popen``. :issue:`1476`125- Exceptions generated during a command will use the context's ``color``126 setting when being displayed. :issue:`2193`127- Error message when defining option with invalid name is more descriptive.128 :issue:`2452`129- Refactor code generating default ``--help`` option to deduplicate code.130 :pr:`2563`131- Test ``CLIRunner`` resets patched ``_compat.should_strip_ansi``.132 :issue:`2732`133134135Version 8.1.7136-------------
1100 unmodified lines
modified:README.md+8 added
48 unmodified lines
49allow the maintainers to devote more time to the projects, [please50donate today][].5152[please donate today]: https://palletsprojects.com/donate5354## Contributing5556See our [detailed contributing documentation][contrib] for many ways to57contribute, including reporting issues, requesting features, asking or answering58questions, and making PRs.5960[contrib]: https://palletsprojects.com/contributing/