Merge `stable` into `main`; Release 8.2.0 (#2873)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Massive reconciliation of stable and main.
authored by Rowlando13 · committed by GitHub · parents ab21233, c9b96fe · Browse files · 26 files·+541 added−482 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
26 files+541 added−482 removed
- tests:+163 added−25 removed
- other:+378 added−457 removed
Provenance
- Commit
b7c0ab4- Tree
39c3ce5- Author
Rowlando13 <67291205+Rowlando13@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent 1
ab21233- Parent 2
c9b96fe
26 files changed+541 added−482 removed
modified:.github/workflows/publish.yaml+1 added-5 removed
62 unmodified lines63646566676768696971727362 unmodified lines permissions: id-token: write steps: - uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8 - uses: pypa/gh-action-pypi-publish@f7600683efdcb7656dec5b29656edb7bc586e597 # v1.10.3 - uses: pypa/gh-action-pypi-publish@15c56dba361d8335944d31a2ecd17d700fc7bcbc # v1.12.2 with: repository-url: https://test.pypi.org/legacy/ packages-dir: artifact/ - uses: pypa/gh-action-pypi-publish@f7600683efdcb7656dec5b29656edb7bc586e597 # v1.10.3 with: packages-dir: artifact/modified:docs/arguments.rst+63 added-171 removed
3 unmodified lines4 =========5 6 .. currentmodule:: click7 8-Arguments work similarly to :ref:`options <options>` but are positional.9-They also only support a subset of the features of options due to their10-syntactical nature. Click will also not attempt to document arguments for11-you and wants you to :ref:`document them manually <documenting-arguments>`12-in order to avoid ugly help pages.8+Arguments are:9 10+* 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>`.13+14+Useful and often used kwargs are:15+16+* ``default``: Passes a default.17+* ``nargs``: Sets the number of arguments. Set to -1 to take an arbitrary number.18+19 Basic Arguments20 ---------------21 17-The most basic option is a simple string argument of one value. If no18-type is provided, the type of the default value is used, and if no default19-value is provided, the type is assumed to be :data:`STRING`.22+A 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``.23 24 Example:25 26 .. click:example::27 28 @click.command()29 @click.argument('filename')27- def touch(filename):30+ def touch(filename: str):31 """Print FILENAME."""32 click.echo(filename)33 31-And what it looks like:34+And from the command line:35 36 .. click:run::37 38 invoke(touch, args=['foo.txt'])39 37-Variadic Arguments38-------------------40 40-The second most common version is variadic arguments where a specific (or41-unlimited) number of arguments is accepted. This can be controlled with42-the ``nargs`` parameter. If it is set to ``-1``, then an unlimited number43-of arguments is accepted.41+An 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`.42 45-The value is then passed as a tuple. Note that only one argument can be46-set to ``nargs=-1``, as it will eat up all arguments.43+.. admonition:: Note on Required Arguments44 48-Example: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.46 47+Multiple Arguments48+-----------------------------------49+50+To 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.51+52 .. click:example::53 54 @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}")61 60-And what it looks like:62+And from the command line:63 64 .. click:run::65 64- invoke(copy, args=['foo.txt', 'bar.txt', 'my_folder'])66+ invoke(copy, args=['foo.txt', 'usr/david/foo.txt', 'usr/mitsuko/foo.txt'])67 66-Note that this is not how you would write this application. The reason67-for this is that in this particular example the arguments are defined as68-strings. Filenames, however, are not strings! They might be on certain69-operating systems, but not necessarily on all. For better ways to write70-this, see the next sections.68+.. admonition:: Note on Handling Files69 72-.. 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.71 74- If you come from ``argparse``, you might be missing support for setting75- ``nargs`` to ``+`` to indicate that at least one argument is required.72+Argument Escape Sequences73+---------------------------74 77- 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.75+If 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.76 84-.. _file-args:77+Example usage:78 86-File Arguments87---------------88-89-Since all the examples have already worked with filenames, it makes sense90-to explain how to deal with files properly. Command line tools are more91-fun if they work with files the Unix way, which is to accept ``-`` as a92-special file that refers to stdin/stdout.93-94-Click supports this through the :class:`click.File` type which95-intelligently handles files for you. It also deals with Unicode and bytes96-correctly for all versions of Python so your script stays very portable.97-98-Example:99-79 .. click:example::80 81 @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)87 113-And what it does:88+And from the command line:89 90 .. click:run::91 117- 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'])93 122-File Path Arguments123--------------------94+If you don't like the ``--`` marker, you can set ignore_unknown_options to True to avoid checking unknown options:95 125-In the previous example, the files were opened immediately. But what if126-we just want the filename? The naïve way is to use the default string127-argument type. The :class:`Path` type has several checks available which raise nice128-errors if they fail, such as existence. Filenames in these error messages are formatted129-with :func:`format_filename`, so any undecodable bytes will be printed nicely.130-131-Example:132-96 .. click:example::97 135- @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)104 141-And what it does:105+And from the command line:106 107 .. click:run::108 145- 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'])110 111 153-File Opening Safety154--------------------155-156-The :class:`FileType` type has one problem it needs to deal with, and that157-is 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/stdout159-and files opened for reading immediately. This will give the user direct160-feedback when a file cannot be opened, but it will only open files161-for writing the first time an IO operation is performed by automatically162-wrapping the file in a special wrapper.163-164-This behavior can be forced by passing ``lazy=True`` or ``lazy=False`` to165-the constructor. If the file is opened lazily, it will fail its first IO166-operation by raising an :exc:`FileError`.167-168-Since files opened for writing will typically immediately empty the file,169-the lazy mode should only be disabled if the developer is absolutely sure170-that this is intended behavior.171-172-Forcing lazy mode is also very useful to avoid resource handling173-confusion. If a file is opened in lazy mode, it will receive a174-``close_intelligently`` method that can help figure out if the file175-needs closing or not. This is not needed for parameters, but is176-necessary for manually prompting with the :func:`prompt` function as you177-do not know if a stream like stdout was opened (which was already open178-before) or a real file that needs closing.179-180-Starting with Click 2.0, it is also possible to open files in atomic mode by181-passing ``atomic=True``. In atomic mode, all writes go into a separate182-file in the same folder, and upon completion, the file will be moved over to183-the original location. This is useful if a file regularly read by other184-users is modified.185-186-112 .. _environment-variables:113 114 Environment Variables115 ---------------------116 192-Like options, arguments can also grab values from an environment variable.193-Unlike options, however, this is only supported for explicitly named194-environment variables.117+Arguments can use environment variables. To do so, pass the name(s) of the environment variable(s) via `envvar` in ``click.argument``.118 196-Example usage:119+Checking one environment variable:120 121 .. click:example::122 123 @click.command()6 unmodified lines130 131 .. click:run::132 133 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'})138 215-In that case, it can also be a list of different environment variables216-where the first one is picked.139 218-Generally, this feature is not recommended because it can cause the user219-a lot of confusion.140+Checking multiple environment variables:141 221-Option-Like Arguments222----------------------223-224-Sometimes, you want to process arguments that look like options. For225-instance, imagine you have a file named ``-foo.txt``. If you pass this as226-an argument in this manner, Click will treat it as an option.227-228-To solve this, Click does what any POSIX style command line script does,229-and that is to accept the string ``--`` as a separator for options and230-arguments. After the ``--`` marker, all further parameters are accepted as231-arguments.232-233-Example usage:234-142 .. click:example::143 144 @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())149 150 And from the command line:151 152 .. click:run::153 248- invoke(touch, ['--', '-foo.txt', 'bar.txt'])249-250-If you don't like the ``--`` marker, you can set ignore_unknown_options to251-True to avoid checking unknown options:252-253-.. click:example::254-255- @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)261-262-And from the command line:263-264-.. click:run::265-266- 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 lines17 Please note that the quality and stability of those packages may be different18 than Click itself. While published under a common organization, they are still19 separate from Click and the Pallets maintainers.20 21+22+Third-party projects23+--------------------24+25+Other projects that extend Click's features are available outside of the26+click-contrib_ organization.27+28+Some of the most popular and actively maintained are listed below:29+30+========================================================== =========================================================================================== ================================================================================================= ======================================================================================================31+Project 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+========================================================== =========================================================================================== ================================================================================================= ======================================================================================================44+45+.. note::46+47+ To make it into the list above, a project:48+49+ - must be actively maintained (at least one commit in the last year)50+ - must have a reasonable number of stars (at least 20)51+52+ If you have a project that meets these criteria, please open a pull request53+ to add it to the list.54+55+ 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.57+58 .. _click-contrib: https://github.com/click-contrib/added:docs/handling-files.rst+90 added
1+.. _handling-files:2+3+Handling Files4+================5+6+.. currentmodule:: click7+8+Click has built in features to support file and file path handling. The examples use arguments but the same principle applies to options as well.9+10+.. _file-args:11+12+File Arguments13+-----------------14+15+Click supports working with files with the :class:`File` type. Some notable features are:16+17+* 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.19+20+Example:21+22+.. click:example::23+24+ @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)34+35+And from the command line:36+37+.. click:run::38+39+ with isolated_filesystem():40+ invoke(inout, args=['-', 'hello.txt'], input=['hello'],41+ terminate_input=True)42+ invoke(inout, args=['hello.txt', '-'])43+44+File Path Arguments45+----------------------46+47+For handling paths, the :class:`Path` type is better than a ``str``. Some notable features are:48+49+* 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.53+54+See :class:`Path` for all features.55+56+Example:57+58+.. click:example::59+60+ @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))65+66+And from the command line:67+68+.. click:run::69+70+ 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'])76+77+78+File Opening Behaviors79+-----------------------------80+81+The :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.82+83+File open behavior can be controlled by the boolean kwarg ``lazy``. If a file is opened lazily:84+85+* 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).87+88+Since 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.89+90+It 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:docs/index.rst+1 added
78 unmodified lines79 commands-and-groups80 commands81 documentation82 prompts83+ handling-files84 complex85 advanced86 testing87 utils25 unmodified linesmodified:requirements/build.txt+1 added-1 removed
4 unmodified lines5 # pip-compile build.in6 #7 build==1.2.2.post18 # via -r build.in9-packaging==24.19+packaging==24.210 # via build11 pyproject-hooks==1.2.012 # via buildmodified:requirements/dev.txt+3 added-3 removed
84 unmodified lines85 # via86 # -r typing.txt87 # pre-commit88 # pyright89-packaging==24.189+packaging==24.290 # via91 # -r docs.txt92 # -r tests.txt93 # pallets-sphinx-themes20 unmodified lines114 # sphinx115 # sphinx-tabs116 pyproject-api==1.8.0117 # via tox118-pyright==1.1.386118+pyright==1.1.390119 # via -r typing.txt120-pytest==8.3.3120+pytest==8.3.4121 # via -r tests.txt122 pyyaml==6.0.2123 # via pre-commit124 requests==2.32.387 unmodified linesmodified:requirements/docs.txt+1 added-1 removed
33 unmodified lines34 mdurl==0.1.235 # via markdown-it-py36 myst-parser==4.0.137 # via -r docs.in38-packaging==24.138+packaging==24.239 # via40 # pallets-sphinx-themes41 # sphinx42 pallets-sphinx-themes==2.3.041 unmodified linesmodified:requirements/tests.txt+2 added-2 removed
4 unmodified lines5 # pip-compile tests.in6 #7 iniconfig==2.0.08 # via pytest9-packaging==24.19+packaging==24.210 # via pytest11 pluggy==1.5.012 # via pytest13-pytest==8.3.313+pytest==8.3.414 # via -r tests.inmodified:requirements/typing.txt+1 added-1 removed
8 unmodified lines9 mypy-extensions==1.0.010 # via mypy11 nodeenv==1.9.112 # via pyright13-pyright==1.1.38613+pyright==1.1.39014 # via -r typing.in15 typing-extensions==4.12.216 # via17 # mypy1 unmodified linemodified:src/click/_termui_impl.py+108 added-38 removed
8 unmodified lines9 import collections.abc as cabc10 import contextlib11 import math12 import os13+import shlex14 import sys15 import time16 import typing as t17 from gettext import gettext as _18 from io import StringIO19+from pathlib import Path20+from shutil import which21 from types import TracebackType22 23 from ._compat import _default_text_stdout24 from ._compat import CYGWIN352 unmodified lines377 stdout = StringIO()378 379 if not isatty(sys.stdin) or not isatty(stdout):380 return _nullpager(stdout, generator, color)378- pager_cmd = (os.environ.get("PAGER", None) or "").strip()379- if pager_cmd:381+382+ # Split and normalize the pager command into parts.383+ pager_cmd_parts = shlex.split(os.environ.get("PAGER", ""), posix=False)384+ if pager_cmd_parts:385 if WIN:381- return _tempfilepager(generator, pager_cmd, color)382- return _pipepager(generator, pager_cmd, color)386+ if _tempfilepager(generator, pager_cmd_parts, color):387+ return388+ elif _pipepager(generator, pager_cmd_parts, color):389+ return390+391 if os.environ.get("TERM") in ("dumb", "emacs"):392 return _nullpager(stdout, generator, color)385- if WIN or sys.platform.startswith("os2"):386- return _tempfilepager(generator, "more <", color)387- if hasattr(os, "system") and os.system("(less) 2>/dev/null") == 0:388- return _pipepager(generator, "less", color)393+ if (WIN or sys.platform.startswith("os2")) and _tempfilepager(394+ generator, ["more"], color395+ ):396+ return397+ if _pipepager(generator, ["less"], color):398+ return399 400 import tempfile401 402 fd, filename = tempfile.mkstemp()403 os.close(fd)404 try:395- if hasattr(os, "system") and os.system(f'more "{filename}"') == 0:396- return _pipepager(generator, "more", color)405+ if _pipepager(generator, ["more"], color):406+ return407 return _nullpager(stdout, generator, color)408 finally:409 os.unlink(filename)410 411 402-def _pipepager(generator: cabc.Iterable[str], cmd: str, color: bool | None) -> None:403- """Page through text by feeding it to another program. Invoking a412+def _pipepager(413+ generator: cabc.Iterable[str], cmd_parts: list[str], color: bool | None414+) -> bool:415+ """Page through text by feeding it to another program. Invoking a416 pager through this might support colors.417+418+ Returns `True` if the command was found, `False` otherwise and thus another419+ pager should be attempted.420 """421+ # Split the command into the invoked CLI and its parameters.422+ if not cmd_parts:423+ return False424+ cmd = cmd_parts[0]425+ cmd_params = cmd_parts[1:]426+427+ cmd_filepath = which(cmd)428+ if not cmd_filepath:429+ return False430+ # Resolves symlinks and produces a normalized absolute path string.431+ cmd_path = Path(cmd_filepath).resolve()432+ cmd_name = cmd_path.name433+434 import subprocess435 436+ # Make a local copy of the environment to not affect the global one.437 env = dict(os.environ)438 410- # If we're piping to less we might support colors under the411- # condition that412- cmd_detail = cmd.rsplit("/", 1)[-1].split()413- if color is None and cmd_detail[0] == "less":414- less_flags = f"{os.environ.get('LESS', '')}{' '.join(cmd_detail[1:])}"439+ # If we're piping to less and the user hasn't decided on colors, we enable440+ # them by default we find the -R flag in the command line arguments.441+ if color is None and cmd_name == "less":442+ less_flags = f"{os.environ.get('LESS', '')}{' '.join(cmd_params)}"443 if not less_flags:444 env["LESS"] = "-R"445 color = True446 elif "r" in less_flags or "R" in less_flags:447 color = True448 421- c = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, env=env)422- stdin = t.cast(t.BinaryIO, c.stdin)423- encoding = get_best_encoding(stdin)449+ c = subprocess.Popen(450+ [str(cmd_path)] + cmd_params,451+ shell=True,452+ stdin=subprocess.PIPE,453+ env=env,454+ errors="replace",455+ text=True,456+ )457+ assert c.stdin is not None458 try:459 for text in generator:460 if not color:461 text = strip_ansi(text)462 429- stdin.write(text.encode(encoding, "replace"))463+ c.stdin.write(text)464 except BrokenPipeError:465 # In case the pager exited unexpectedly, ignore the broken pipe error.466 pass467 except Exception as e:5 unmodified lines473 raise e474 finally:475 # We must close stdin and wait for the pager to exit before we continue476 try:443- stdin.close()477+ c.stdin.close()478 # Close implies flush, so it might throw a BrokenPipeError if the pager479 # process exited already.480 except BrokenPipeError:481 pass13 unmodified lines495 pass496 else:497 break498 499+ return True500 466-def _tempfilepager(generator: cabc.Iterable[str], cmd: str, color: bool | None) -> None:467- """Page through text by invoking a program on a temporary file."""501+502+def _tempfilepager(503+ generator: cabc.Iterable[str], cmd_parts: list[str], color: bool | None504+) -> bool:505+ """Page through text by invoking a program on a temporary file.506+507+ Returns `True` if the command was found, `False` otherwise and thus another508+ pager should be attempted.509+ """510+ # Split the command into the invoked CLI and its parameters.511+ if not cmd_parts:512+ return False513+ cmd = cmd_parts[0]514+515+ cmd_filepath = which(cmd)516+ if not cmd_filepath:517+ return False518+ # Resolves symlinks and produces a normalized absolute path string.519+ cmd_path = Path(cmd_filepath).resolve()520+521+ import subprocess522 import tempfile523 524 fd, filename = tempfile.mkstemp()525 # TODO: This never terminates if the passed generator never terminates.3 unmodified lines529 encoding = get_best_encoding(sys.stdout)530 with open_stream(filename, "wb")[0] as f:531 f.write(text.encode(encoding))532 try:479- os.system(f'{cmd} "{filename}"')533+ subprocess.call([str(cmd_path), filename])534+ except OSError:535+ # Command not found536+ pass537 finally:538 os.close(fd)539 os.unlink(filename)540 541+ return True542 543+544 def _nullpager(545 stream: t.TextIO, generator: cabc.Iterable[str], color: bool | None546 ) -> None:547 """Simply print unformatted text. This is the ultimate fallback."""25 unmodified lines573 return rv574 if WIN:575 return "notepad"576 for editor in "sensible-editor", "vim", "nano":518- if os.system(f"which {editor} >/dev/null 2>&1") == 0:577+ if which(editor) is not None:578 return editor579 return "vi"580 581 def edit_files(self, filenames: cabc.Iterable[str]) -> None:102 unmodified lines684 finally:685 null.close()686 elif WIN:687 if locate:629- url = _unquote_file(url.replace('"', ""))630- args = f'explorer /select,"{url}"'688+ url = _unquote_file(url)689+ args = ["explorer", f"/select,{url}"]690 else:632- url = url.replace('"', "")633- wait_str = "/WAIT" if wait else ""634- args = f'start {wait_str} "" "{url}"'635- return os.system(args)691+ args = ["start"]692+ if wait:693+ args.append("/WAIT")694+ args.append("")695+ args.append(url)696+ try:697+ return subprocess.call(args)698+ except OSError:699+ # Command not found700+ return 127701 elif CYGWIN:702 if locate:638- url = os.path.dirname(_unquote_file(url).replace('"', ""))639- args = f'cygstart "{url}"'703+ url = _unquote_file(url)704+ args = ["cygstart", os.path.dirname(url)]705 else:641- url = url.replace('"', "")642- wait_str = "-w" if wait else ""643- args = f'cygstart {wait_str} "{url}"'644- return os.system(args)706+ args = ["cygstart"]707+ if wait:708+ args.append("-w")709+ args.append(url)710+ try:711+ return subprocess.call(args)712+ except OSError:713+ # Command not found714+ return 127715 716 try:717 if locate:718 url = os.path.dirname(_unquote_file(url)) or "."121 unmodified linesmodified:src/click/core.py+26 added-8 removed
114 unmodified lines115 def iter_params_for_processing(116 invocation_order: cabc.Sequence[Parameter],117 declaration_order: cabc.Sequence[Parameter],118 ) -> list[Parameter]:119- """Given a sequence of parameters in the order as should be considered120- for processing and an iterable of parameters that exist, this returns121- a list in the correct order as they should be processed.119+ """Returns all declared parameters in the order they should be processed.120+121+ The declared parameters are re-shuffled depending on the order in which122+ they were invoked, as well as the eagerness of each parameters.123+124+ The invocation order takes precedence over the declaration order. I.e. the125+ order in which the user provided them to the CLI is respected.126+127+ This behavior and its effect on callback evaluation is detailed at:128+ https://click.palletsprojects.com/en/stable/advanced/#callback-evaluation-order129 """130 131 def sort_key(item: Parameter) -> tuple[bool, float]:132 try:807 unmodified lines940 self.epilog = epilog941 self.options_metavar = options_metavar942 self.short_help = short_help943 self.add_help_option = add_help_option944+ self._help_option = None945 self.no_args_is_help = no_args_is_help946 self.hidden = hidden947 self.deprecated = deprecated948 75 unmodified lines1024 def get_help_option(self, ctx: Context) -> Option | None:1025 """Returns the help option object.1026 1027 Skipped if :attr:`add_help_option` is ``False``.1028+1029+ .. versionchanged:: 8.1.81030+ The help option is now cached to avoid creating it multiple times.1031 """1032 help_option_names = self.get_help_option_names(ctx)1033 1034 if not help_option_names or not self.add_help_option:1035 return None1036 1037+ # Cache the help option object in private _help_option attribute to1038+ # avoid creating it multiple times. Not doing this will break the1039+ # callback odering by iter_params_for_processing(), which relies on1040+ # object comparison.1041+ if self._help_option is None:1026- # Avoid circular import.1027- from .decorators import help_option1042+ # Avoid circular import.1043+ from .decorators import help_option1044 1029- # apply help_option decorator and pop resulting option1030- help_option(*help_option_names)(self)1031- return self.params.pop() # type: ignore[return-value]1045+ # Apply help_option decorator and pop resulting option1046+ help_option(*help_option_names)(self)1047+ self._help_option = self.params.pop() # type: ignore[assignment]1048 1049+ return self._help_option1050+1051 def make_parser(self, ctx: Context) -> _OptionParser:1052 """Creates the underlying option parser for this command."""1053 parser = _OptionParser(ctx)1054 for param in self.get_params(ctx):2081 unmodified linesmodified:src/click/shell_completion.py+11 added-4 removed
301 unmodified lines302 source_template = _SOURCE_BASH303 304 @staticmethod305 def _check_version() -> None:306+ import shutil307 import subprocess308 308- 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")310 311+ 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())319+320 if match is not None:321 major, minor = match.groups()322 323 if major < "4" or major == "4" and minor < "4":321 unmodified linesmodified:src/click/testing.py+2 added
373 unmodified lines374 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: ignore26 unmodified lines409 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_width415 416 def invoke(417 self,140 unmodified linesmodified:src/click/types.py+7 added-4 removed
724 unmodified lines725 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.728 729- 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.733 734 See :ref:`file-args` for more information.735+736+ .. versionchanged:: 2.0737+ Added the ``atomic`` parameter.738 """739 740 name = "filename"741 envvar_list_splitter: t.ClassVar[str] = os.path.pathsep422 unmodified linesmodified:tests/typing/typing_aliased_group.py+1 added-1 removed
1-"""Example from https://click.palletsprojects.com/en/8.1.x/advanced/#command-aliases"""1+"""Example from https://click.palletsprojects.com/en/stable/advanced/#command-aliases"""2 3 from __future__ import annotations4 5 from typing_extensions import assert_type41 unmodified linesmodified:tests/typing/typing_confirmation_option.py+1 added-1 removed
1-"""From https://click.palletsprojects.com/en/8.1.x/options/#yes-parameters"""1+"""From https://click.palletsprojects.com/en/stable/options/#yes-parameters"""2 3 from typing_extensions import assert_type4 5 import click9 unmodified linesmodified:tests/typing/typing_options.py+1 added-1 removed
1-"""From https://click.palletsprojects.com/en/8.1.x/quickstart/#adding-parameters"""1+"""From https://click.palletsprojects.com/en/stable/quickstart/#adding-parameters"""2 3 from typing_extensions import assert_type4 5 import click11 unmodified linesmodified:tests/typing/typing_version_option.py+1 added-1 removed
1 """2-From https://click.palletsprojects.com/en/8.1.x/options/#callbacks-and-eager-options.2+From https://click.palletsprojects.com/en/stable/options/#callbacks-and-eager-options.3 """4 5 from typing_extensions import assert_type6 10 unmodified linesmodified:tests/test_commands.py+132 added
299 unmodified lines300 result = runner.invoke(cli, ["b"], default_map={"b": {"x": 3}})301 assert result.exit_code == 0302 303 304+@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+)346+def 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+ }356+357+ 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]360+361+ assert (362+ click.core.iter_params_for_processing(invocation_params, declaration_params)363+ == expected_params364+ )365+366+367+def 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.370+371+ See: https://github.com/pallets/click/pull/2811372+ """373+374+ def print_and_exit(ctx, param, value):375+ if value:376+ click.echo(f"Value of {param.name} is: {value}")377+ ctx.exit()378+379+ @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+ pass386+387+ # --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 == 0393+394+ # -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 == 0400+401+ # -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 == 0407+408+ # --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 == 0416+417+ # 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 == 0424+425+ # 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 == 0434+435+436 def 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 linesmodified:tests/test_imports.py+1 added
47 unmodified lines48 "enum",49 "typing",50 "types",51 "gettext",52+ "shutil",53 }54 55 if WIN:56 ALLOWED_IMPORTS.update(["ctypes", "ctypes.wintypes", "msvcrt", "time"])14 unmodified linesmodified:tests/test_utils.py+26 added-21 removed
1 import os2 import pathlib3 import stat4+import subprocess5 import sys6 from collections import namedtuple7+from contextlib import nullcontext8+from functools import partial9 from io import StringIO10+from pathlib import Path11 from tempfile import tempdir12+from unittest.mock import patch13 14 import pytest15 16 import click._termui_impl199 unmodified lines216 217 218 @pytest.mark.skipif(WIN, reason="Different behavior on windows.")219 @pytest.mark.parametrize(220+ "pager_cmd", ["cat", "cat ", " cat ", "less", " less", " less "]221+)222+@pytest.mark.parametrize(223 "test",224 [225 # We need to pass a parameter function instead of a plain param226 # as pytest.mark.parametrize will reuse the parameters causing the42 unmodified lines269 description="Exception in generator function argument",270 test_input=lambda: _test_gen_func_fails,271 # Because generator throws early on, the pager did not have272 # a chance yet to write the file.265- expected_pager=None,273+ expected_pager="",274 expected_stdout="",275 expected_stderr="",276 expected_error=RuntimeError,277 ),1 unmodified line279 description="Exception in generator argument",280 test_input=lambda: _test_gen_func_fails,281 # Because generator throws early on, the pager did not have a282 # chance yet to write the file.275- expected_pager=None,283+ expected_pager="",284 expected_stdout="",285 expected_stderr="",286 expected_error=RuntimeError,287 ),26 unmodified lines314 expected_error=None,315 ),316 ],317 )310-def test_echo_via_pager(monkeypatch, capfd, test):311- pager_out_tmp = f"{tempdir}/pager_out.txt"312-313- if os.path.exists(pager_out_tmp):314- os.remove(pager_out_tmp)315-316- monkeypatch.setitem(os.environ, "PAGER", f"cat > {pager_out_tmp}")318+def test_echo_via_pager(monkeypatch, capfd, pager_cmd, test):319+ monkeypatch.setitem(os.environ, "PAGER", pager_cmd)320 monkeypatch.setattr(click._termui_impl, "isatty", lambda x: True)321 322 test_input = test.test_input()323 expected_pager = test.expected_pager324 expected_stdout = test.expected_stdout325 expected_stderr = test.expected_stderr326 expected_error = test.expected_error327 325- if expected_error:326- with pytest.raises(expected_error):327- click.echo_via_pager(test_input)328- else:329- click.echo_via_pager(test_input)328+ check_raise = pytest.raises(expected_error) if expected_error else nullcontext()329 330+ pager_out_tmp = Path(tempdir) / "pager_out.txt"331+ pager_out_tmp.unlink(missing_ok=True)332+ with pager_out_tmp.open("w") as f:333+ force_subprocess_stdout = patch.object(334+ subprocess,335+ "Popen",336+ partial(subprocess.Popen, stdout=f),337+ )338+ with force_subprocess_stdout:339+ with check_raise:340+ click.echo_via_pager(test_input)341+342 out, err = capfd.readouterr()343 333- if os.path.exists(pager_out_tmp):334- with open(pager_out_tmp) as f:335- pager = f.read()336- else:337- # The pager process was not started or has been338- # terminated before it could finish writing339- pager = None344+ pager = pager_out_tmp.read_text()345 346 assert (347 pager == expected_pager348 ), f"Unexpected pager output in test case '{test.description}'"310 unmodified linesmodified:CHANGES.rst+15 added-2 removed
1 unmodified line2 3 Version 8.2.04 -------------5 6-Unreleased6+Released 2025-03-267 8 - Drop support for Python 3.7. :pr:`2588`9 - Use modern packaging metadata with ``pyproject.toml`` instead of ``setup.cfg``.10 :pr:`2438`92 unmodified lines103 104 Version 8.1.8105 -------------106 107-Unreleased107+Released 2024-12-19108 109 - 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 lines116 - 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`133 134 135 Version 8.1.7136 -------------1100 unmodified linesdeleted:CONTRIBUTING.rst-216 removed
1-How to contribute to Click2-==========================3-4-Thank you for considering contributing to Click!5-6-7-Support questions8------------------9-10-Please don't use the issue tracker for this. The issue tracker is a tool11-to address bugs and feature requests in Click itself. Use one of the12-following resources for questions about using Click or issues with your13-own code:14-15-- The ``#get-help`` channel on our Discord chat:16- https://discord.gg/pallets17-- The mailing list flask@python.org for long term discussion or larger18- issues.19-- Ask on `Stack Overflow`_. Search with Google first using:20- ``site:stackoverflow.com python click {search term, exception message, etc.}``21-22-.. _Stack Overflow: https://stackoverflow.com/questions/tagged/python-click?tab=Frequent23-24-25-Reporting issues26-----------------27-28-Include the following information in your post:29-30-- Describe what you expected to happen.31-- If possible, include a `minimal reproducible example`_ to help us32- identify the issue. This also helps check that the issue is not with33- your own code.34-- Describe what actually happened. Include the full traceback if there35- was an exception.36-- List your Python and Click versions. If possible, check if this37- issue is already fixed in the latest releases or the latest code in38- the repository.39-40-.. _minimal reproducible example: https://stackoverflow.com/help/minimal-reproducible-example41-42-43-Submitting patches44-------------------45-46-If there is not an open issue for what you want to submit, prefer47-opening one for discussion before working on a PR. You can work on any48-issue that doesn't have an open PR linked to it or a maintainer assigned49-to it. These show up in the sidebar. No need to ask if you can work on50-an issue that interests you.51-52-Include the following in your patch:53-54-- Use `Black`_ to format your code. This and other tools will run55- automatically if you install `pre-commit`_ using the instructions56- below.57-- Include tests if your patch adds or changes code. Make sure the test58- fails without your patch.59-- Update any relevant docs pages and docstrings. Docs pages and60- docstrings should be wrapped at 72 characters.61-- Add an entry in ``CHANGES.rst``. Use the same style as other62- entries. Also include ``.. versionchanged::`` inline changelogs in63- relevant docstrings.64-65-.. _Black: https://black.readthedocs.io66-.. _pre-commit: https://pre-commit.com67-68-69-First time setup70-~~~~~~~~~~~~~~~~71-72-- Download and install the `latest version of git`_.73-- Configure git with your `username`_ and `email`_.74-75- .. code-block:: text76-77- $ git config --global user.name 'your name'78- $ git config --global user.email 'your email'79-80-- Make sure you have a `GitHub account`_.81-- Fork Click to your GitHub account by clicking the `Fork`_ button.82-- `Clone`_ the main repository locally.83-84- .. code-block:: text85-86- $ git clone https://github.com/pallets/click87- $ cd click88-89-- Add your fork as a remote to push your work to. Replace90- ``{username}`` with your username. This names the remote "fork", the91- default Pallets remote is "origin".92-93- .. code-block:: text94-95- $ git remote add fork https://github.com/{username}/click96-97-- Create a virtualenv.98-99- .. code-block:: text100-101- $ python3 -m venv env102- $ . env/bin/activate103-104- On Windows, activating is different.105-106- .. code-block:: text107-108- > env\Scripts\activate109-110-- Install the development dependencies, then install Click in111- editable mode.112-113- .. code-block:: text114-115- $ pip install -r requirements/dev.txt && pip install -e .116-117-- Install the pre-commit hooks.118-119- .. code-block:: text120-121- $ pre-commit install122-123-.. _latest version of git: https://git-scm.com/downloads124-.. _username: https://docs.github.com/en/github/using-git/setting-your-username-in-git125-.. _email: https://docs.github.com/en/github/setting-up-and-managing-your-github-user-account/setting-your-commit-email-address126-.. _GitHub account: https://github.com/join127-.. _Fork: https://github.com/pallets/click/fork128-.. _Clone: https://docs.github.com/en/github/getting-started-with-github/fork-a-repo#step-2-create-a-local-clone-of-your-fork129-130-131-Start coding132-~~~~~~~~~~~~133-134-- Create a branch to identify the issue you would like to work on. If135- you're submitting a bug or documentation fix, branch off of the136- latest ".x" branch.137-138- .. code-block:: text139-140- $ git fetch origin141- $ git checkout -b your-branch-name origin/8.1.x142-143- If you're submitting a feature addition or change, branch off of the144- "main" branch.145-146- .. code-block:: text147-148- $ git fetch origin149- $ git checkout -b your-branch-name origin/main150-151-- Using your favorite editor, make your changes,152- `committing as you go`_.153-- Include tests that cover any code changes you make. Make sure the154- test fails without your patch. Run the tests as described below.155-- Push your commits to your fork on GitHub and156- `create a pull request`_. Link to the issue being addressed with157- ``fixes #123`` in the pull request.158-159- .. code-block:: text160-161- $ git push --set-upstream fork your-branch-name162-163-.. _committing as you go: https://dont-be-afraid-to-commit.readthedocs.io/en/latest/git/commandlinegit.html#commit-your-changes164-.. _create a pull request: https://docs.github.com/en/github/collaborating-with-issues-and-pull-requests/creating-a-pull-request165-166-167-Running the tests168-~~~~~~~~~~~~~~~~~169-170-Run the basic test suite with pytest.171-172-.. code-block:: text173-174- $ pytest175-176-This runs the tests for the current environment, which is usually177-sufficient. CI will run the full suite when you submit your pull178-request. You can run the full test suite with tox if you don't want to179-wait.180-181-.. code-block:: text182-183- $ tox184-185-186-Running test coverage187-~~~~~~~~~~~~~~~~~~~~~188-189-Generating a report of lines that do not have test coverage can indicate190-where to start contributing. Run ``pytest`` using ``coverage`` and191-generate a report.192-193-.. code-block:: text194-195- $ pip install coverage196- $ coverage run -m pytest197- $ coverage html198-199-Open ``htmlcov/index.html`` in your browser to explore the report.200-201-Read more about `coverage <https://coverage.readthedocs.io>`__.202-203-204-Building the docs205-~~~~~~~~~~~~~~~~~206-207-Build the docs in the ``docs`` directory using Sphinx.208-209-.. code-block:: text210-211- $ cd docs212- $ make html213-214-Open ``_build/html/index.html`` in your browser to view the docs.215-216-Read more about `Sphinx <https://www.sphinx-doc.org/en/stable/>`__.modified:pyproject.toml+1 added-1 removed
1 [project]2 name = "click"3-version = "8.2.0.dev"3+version = "8.2.0"4 description = "Composable command line interface toolkit"5 readme = "README.md"6 license = {file = "LICENSE.txt"}7 maintainers = [{name = "Pallets", email = "contact@palletsprojects.com"}]95 unmodified linesmodified:README.md+8 added
48 unmodified lines49 allow the maintainers to devote more time to the projects, [please50 donate today][].51 52 [please donate today]: https://palletsprojects.com/donate53+54+## Contributing55+56+See our [detailed contributing documentation][contrib] for many ways to57+contribute, including reporting issues, requesting features, asking or answering58+questions, and making PRs.59+60+[contrib]: https://palletsprojects.com/contributing/