Skip to content
Myr

Merge branch 'stable' of https://github.com/Rowlando13/click into trim_args_section

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

authored by unknown · committed by unknown · parents f0f5ce1, 26aa7bf · Browse files · 67 files+925 added−837 removed
This commit

State

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

Diff stats

67 files+925 added−837 removed

  • tests:+87 added−16 removed
  • other:+838 added−821 removed

67 files+925 added−837 removed

added:.devcontainer/devcontainer.json+17 added
added:.devcontainer/on-create-command.sh+7 added
modified:.github/ISSUE_TEMPLATE/bug-report.md+1 added-1 removed
modified:.github/ISSUE_TEMPLATE/config.yml+5 added-8 removed
modified:.github/ISSUE_TEMPLATE/feature-request.md+3 added-3 removed
modified:.github/workflows/lock.yaml+7 added-9 removed
modified:.github/workflows/publish.yaml+16 added-15 removed
modified:.github/workflows/tests.yaml+34 added-39 removed
1name: Tests2on:3 push:4 branches:5 - main6 - '*.x'7 paths-ignore:8 - 'docs/**'9 - '*.md'10 - '*.rst'4 branches: [main, stable]5 paths-ignore: ['docs/**', '*.md', '*.rst']6 pull_request:12 branches:13 - main14 - '*.x'15 paths-ignore:16 - 'docs/**'17 - '*.md'18 - '*.rst'7 paths-ignore: [ 'docs/**', '*.md', '*.rst' ]8jobs:9 tests:21 name: ${{ matrix.name }}22 runs-on: ${{ matrix.os }}10 name: ${{ matrix.name || matrix.python }}11 runs-on: ${{ matrix.os || 'ubuntu-latest' }}12 strategy:13 fail-fast: false14 matrix:15 include:27 - {name: Linux, python: '3.11', os: ubuntu-latest, tox: py311}28 - {name: Windows, python: '3.11', os: windows-latest, tox: py311}29 - {name: Mac, python: '3.11', os: macos-latest, tox: py311}30 - {name: '3.12-dev', python: '3.12-dev', os: ubuntu-latest, tox: py312}31 - {name: '3.10', python: '3.10', os: ubuntu-latest, tox: py310}32 - {name: '3.9', python: '3.9', os: ubuntu-latest, tox: py39}33 - {name: '3.8', python: '3.8', os: ubuntu-latest, tox: py38}34 - {name: '3.7', python: '3.7', os: ubuntu-latest, tox: py37}35 - {name: 'PyPy', python: 'pypy-3.10', os: ubuntu-latest, tox: pypy310}36 - {name: Typing, python: '3.11', os: ubuntu-latest, tox: typing}16 - {python: '3.13'}17 - {python: '3.12'}18 - {name: Windows, python: '3.12', os: windows-latest}19 - {name: Mac, python: '3.12', os: macos-latest}20 - {python: '3.11'}21 - {python: '3.10'}22 - {python: '3.9'}23 - {python: '3.8'}24 - {python: '3.7'}25 - {name: PyPy, python: 'pypy-3.10', tox: pypy310}26 steps:38 - uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c39 - uses: actions/setup-python@5ccb29d8773c3f3f653e1705f474dfaa8a06a91227 - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.228 - uses: actions/setup-python@0b93645e9fea7318ecaed2b359559ac225c90a2b # v5.3.029 with:30 python-version: ${{ matrix.python }}42 cache: 'pip'43 cache-dependency-path: 'requirements/*.txt'44 - name: update pip45 run: |46 pip install -U wheel47 pip install -U setuptools48 python -m pip install -U pip31 allow-prereleases: true32 cache: pip33 cache-dependency-path: requirements*/*.txt34 - run: pip install tox35 - run: tox run -e ${{ matrix.tox || format('py{0}', matrix.python) }}36 typing:37 runs-on: ubuntu-latest38 steps:39 - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.240 - uses: actions/setup-python@0b93645e9fea7318ecaed2b359559ac225c90a2b # v5.3.041 with:42 python-version: '3.x'43 cache: pip44 cache-dependency-path: requirements*/*.txt45 - name: cache mypy50 uses: actions/cache@58c146cc91c5b9e778e71775dfe9bf1442ad9a1246 uses: actions/cache@6849a6489940f00c2f30c0fb92c6274307ccb58a # v4.1.247 with:48 path: ./.mypy_cache53 key: mypy|${{ matrix.python }}|${{ hashFiles('setup.cfg') }}54 if: matrix.tox == 'typing'49 key: mypy|${{ hashFiles('pyproject.toml') }}50 - run: pip install tox56 - run: tox run -e ${{ matrix.tox }}51 - run: tox run -e typing
deleted:.github/dependabot.yml-9 removed
1version: 22updates:3- package-ecosystem: "github-actions"4 directory: "/"5 schedule:6 interval: "monthly"7 day: "monday"8 time: "16:00"9 timezone: "UTC"
modified:.github/pull_request_template.md+10 added-15 removed
1<!--2Before opening a PR, open a ticket describing the issue or feature the3PR will address. Follow the steps in CONTRIBUTING.rst.3PR will address. An issue is not required for fixing typos in4documentation, or other simple non-code changes.56Replace this comment with a description of the change. Describe how it7addresses the linked ticket.8-->910<!--11Link to relevant issues or previous PRs, one per line. Use "fixes" to12automatically close an issue.1314fixes #<issue number>15-->1614- fixes #<issue number>1517<!--17Ensure each step in CONTRIBUTING.rst is complete by adding an "x" to18each box below.18Ensure each step in CONTRIBUTING.rst is complete, especially the following:1920If only docs were changed, these aren't relevant and can be removed.20- Add tests that demonstrate the correct behavior of the change. Tests21 should fail without the change.22- Add or update relevant docs, in the docs folder and in code.23- Add an entry in CHANGES.rst summarizing the change and linking to the issue.24- Add `.. versionchanged::` entries in any relevant code docs.25-->2223Checklist:2425- [ ] Add tests that demonstrate the correct behavior of the change. Tests should fail without the change.26- [ ] Add or update relevant docs, in the docs folder and in code.27- [ ] Add an entry in `CHANGES.rst` summarizing the change and linking to the issue.28- [ ] Add `.. versionchanged::` entries in any relevant code docs.29- [ ] Run `pre-commit` hooks and fix any issues.30- [ ] Run `pytest` and `tox`, no tests failed.
modified:docs/advanced.rst+1 added
433 unmodified lines
434435 def __enter__(self):436 path = os.path.join(self.home, "repo.db")437 self.db = open_database(path)438 return self439440 def __exit__(self, exc_type, exc_value, tb):441 self.db.close()442
47 unmodified lines
modified:docs/arguments.rst+3 added
105 unmodified lines
106.. click:run::107108 invoke(touch, ['-foo.txt', 'bar.txt'])109110111.. _environment-variables:112113Environment Variables114---------------------115116This feature is not recommended since it be confusing to users. Arguments can only pull environment variables from ? explicitly named environment variables. In that case, it can also be a list of different environment variables where the first one is picked. ?
19 unmodified lines
modified:docs/conf.py+12 added-9 removed
8 unmodified lines
9release, version = get_version("Click")1011# General --------------------------------------------------------------1213master_doc = "index"13default_role = "code"14extensions = [15 "sphinx.ext.autodoc",16 "sphinx.ext.extlinks",17 "sphinx.ext.intersphinx",18 "sphinx_tabs.tabs",19 "sphinxcontrib.log_cabinet",20 "pallets_sphinx_themes",19 "sphinx_issues",20 "sphinx_tabs.tabs",21]22autodoc_member_order = "bysource"23autodoc_typehints = "description"23intersphinx_mapping = {"python": ("https://docs.python.org/3/", None)}24issues_github_path = "pallets/click"24autodoc_preserve_defaults = True25extlinks = {26 "issue": ("https://github.com/pallets/click/issues/%s", "#%s"),27 "pr": ("https://github.com/pallets/click/pull/%s", "#%s"),28}29intersphinx_mapping = {30 "python": ("https://docs.python.org/3/", None),31}3233# HTML -----------------------------------------------------------------3435html_theme = "click"
16 unmodified lines
52html_favicon = "_static/click-icon.png"53html_logo = "_static/click-logo-sidebar.png"54html_title = f"Click Documentation ({version})"55html_show_sourcelink = False4950# LaTeX ----------------------------------------------------------------5152latex_documents = [(master_doc, f"Click-{version}.tex", html_title, author, "manual")]
modified:docs/documentation.rst+1 added-1 removed
34 unmodified lines
3536.. _documenting-arguments:3738Documenting Arguments39~~~~~~~~~~~~~~~~~~~~~39----------------------4041:func:`click.argument` does not take a ``help`` parameter. This is to42follow the general convention of Unix tools of using arguments for only43the most necessary things, and to document them in the command help text
224 unmodified lines
modified:docs/index.rst+1 added
66 unmodified lines
67 :maxdepth: 26869 why70 quickstart71 virtualenv72 setuptools73 parameters74 options75 arguments
34 unmodified lines
modified:docs/license.rst+2 added-1 removed
1BSD-3-Clause License2====================34.. include:: ../LICENSE.rst4.. literalinclude:: ../LICENSE.txt5 :language: text
modified:docs/parameters.rst+48 added-54 removed
1 unmodified line
2==========34.. currentmodule:: click56Click supports two types of parameters for scripts: options and arguments.7There is generally some confusion among authors of command line scripts of8when to use which, so here is a quick overview of the differences. As its9name indicates, an option is optional. While arguments can be optional10within reason, they are much more restricted in how optional they can be.6Click supports only two types of parameters for scripts (by design): options and arguments.712To help you decide between options and arguments, the recommendation is13to use arguments exclusively for things like going to subcommands or input14filenames / URLs, and have everything else be an option instead.8Options9----------------1016Differences17-----------11* Are optional.12* Recommended to use for everything except subcommands, urls, or files.13* Can take a fixed number of arguments. The default is 1. They may be specified multiple times using :ref:`multiple-options`.14* Are fully documented by the help page.15* Have automatic prompting for missing input.16* Can act as flags (boolean or otherwise).17* Can be pulled from environment variables.1819Arguments can do less than options. The following features are only20available for options:19Arguments20----------------2122* automatic prompting for missing input23* act as flags (boolean or otherwise)24* option values can be pulled from environment variables, arguments can not25* options are fully documented in the help page, arguments are not26 (:ref:`this is intentional <documenting-arguments>` as arguments27 might be too specific to be automatically documented)22* Are optional with in reason, but not entirely so.23* Recommended to use for subcommands, urls, or files.24* Can take an arbitrary number of arguments.25* Are not fully documented by the help page since they may be too specific to be automatically documented. For more see :ref:`documenting-arguments`.26* Can be pulled from environment variables but only explicitly named ones. For more see :ref:`environment-variables`.2729On the other hand arguments, unlike options, can accept an arbitrary number30of arguments. Options can strictly ever only accept a fixed number of31arguments (defaults to 1), or they may be specified multiple times using32:ref:`multiple-options`.28.. _parameter_names:2930Parameter Names31---------------3233Parameters (options and arguments) have a name that will be used as34the Python argument name when calling the decorated function with35values.3637.. click:example::3839 @click.command()40 @click.argument('filename')41 @click.option('-t', '--times', type=int)42 def multi_echo(filename, times):43 """Print value filename multiple times."""44 for x in range(times):45 click.echo(filename)4647In the above example the argument's name is ``filename``. The name must match the python arg name. To provide a different name for use in help text, see :ref:`doc-meta-variables`.48The option's names are ``-t`` and ``--times``. More names are available for options and are covered in :ref:`options`.4950And what it looks like when run:5152.. click:run::5354 invoke(multi_echo, ['--times=3', 'index.txt'], prog_name='multi_echo')5556Parameter Types57---------------5837Parameters can be of different types. Types can be implemented with38different behavior and some are supported out of the box:59The supported parameter types are:6061``str`` / :data:`click.STRING`:62 The default parameter type which indicates unicode strings.63
30 unmodified lines
9495.. autoclass:: DateTime96 :noindex:9777Custom parameter types can be implemented by subclassing78:class:`click.ParamType`. For simple cases, passing a Python function that79fails with a `ValueError` is also supported, though discouraged.98How to Implement Custom Types99-------------------------------10081.. _parameter_names:101To implement a custom type, you need to subclass the :class:`ParamType` class. For simple cases, passing a Python function that fails with a `ValueError` is also supported, though discouraged. Override the :meth:`~ParamType.convert` method to convert the value from a string to the correct type.10283Parameter Names84---------------8586Parameters (both options and arguments) have a name that will be used as87the Python argument name when calling the decorated function with88values.8990Arguments take only one positional name. To provide a different name for91use in help text, see :ref:`doc-meta-variables`.9293Options can have many names that may be prefixed with one or two dashes.94Names with one dash are parsed as short options, names with two are95parsed as long options. If a name is not prefixed, it is used as the96Python argument name and not parsed as an option name. Otherwise, the97first name with a two dash prefix is used, or the first with a one dash98prefix if there are none with two. The prefix is removed and dashes are99converted to underscores to get the Python argument name.100101102Implementing Custom Types103-------------------------104105To implement a custom type, you need to subclass the :class:`ParamType`106class. Override the :meth:`~ParamType.convert` method to convert the107value from a string to the correct type.108103The following code implements an integer type that accepts hex and octal104numbers in addition to normal integers, and converts them into regular105integers.106
31 unmodified lines
modified:docs/quickstart.rst+15 added-85 removed
1 unmodified line
2==========34.. currentmodule:: click56You can get the library directly from PyPI::6Install7----------------------8Install from PyPI::910 pip install click1110The installation into a :ref:`virtualenv` is heavily recommended.12Installing into a virtual environment is highly recommended. We suggest :ref:`virtualenv-heading`.1312.. _virtualenv:1314virtualenv15----------1617Virtualenv is probably what you want to use for developing Click18applications.1920What problem does virtualenv solve? Chances are that you want to use it21for other projects besides your Click script. But the more projects you22have, the more likely it is that you will be working with different23versions of Python itself, or at least different versions of Python24libraries. Let's face it: quite often libraries break backwards25compatibility, and it's unlikely that any serious application will have26zero dependencies. So what do you do if two or more of your projects have27conflicting dependencies?2829Virtualenv to the rescue! Virtualenv enables multiple side-by-side30installations of Python, one for each project. It doesn't actually31install separate copies of Python, but it does provide a clever way to32keep different project environments isolated.3334Create your project folder, then a virtualenv within it::3536 $ mkdir myproject37 $ cd myproject38 $ python3 -m venv .venv3940Now, whenever you want to work on a project, you only have to activate the41corresponding environment. On OS X and Linux, do the following::4243 $ . .venv/bin/activate44 (venv) $4546If you are a Windows user, the following command is for you::4748 > .venv\scripts\activate49 (venv) >5051Either way, you should now be using your virtualenv (notice how the prompt of52your shell has changed to show the active environment).5354And if you want to stop using the virtualenv, use the following command::5556 $ deactivate5758After doing this, the prompt of your shell should be as familiar as before.5960Now, let's move on. Enter the following command to get Click activated in your61virtualenv::6263 $ pip install click6465A few seconds later and you are good to go.6667Screencast and Examples14Examples15-----------------------1670There is a screencast available which shows the basic API of Click and71how to build simple applications with it. It also explores how to build72commands with subcommands.17Some standalone examples of Click applications are packaged with Click. They are available in the `examples folder <https://github.com/pallets/click/tree/main/examples>`_ of the repo.1874* `Building Command Line Applications with Click75 <https://www.youtube.com/watch?v=kNke39OZ2k0>`_19* `inout <https://github.com/pallets/click/tree/main/examples/inout>`_ : A very simple example of an application that can read from files and write to files and also accept input from stdin or write to stdout.20* `validation <https://github.com/pallets/click/tree/main/examples/validation>`_ : A simple example of an application that performs custom validation of parameters in different ways.21* `naval <https://github.com/pallets/click/tree/main/examples/naval>`_ : Port of the `docopt <http://docopt.org/>`_ naval example.22* `colors <https://github.com/pallets/click/tree/main/examples/colors>`_ : A simple example that colorizes text. Uses colorama on Windows.23* `aliases <https://github.com/pallets/click/tree/main/examples/aliases>`_ : An advanced example that implements :ref:`aliases`.24* `imagepipe <https://github.com/pallets/click/tree/main/examples/imagepipe>`_ : A complex example that implements some :ref:`multi-command-chaining` . It chains together image processing instructions. Requires pillow.25* `repo <https://github.com/pallets/click/tree/main/examples/repo>`_ : An advanced example that implements a Git-/Mercurial-like command line interface.26* `complex <https://github.com/pallets/click/tree/main/examples/complex>`_ : A very advanced example that implements loading subcommands dynamically from a plugin folder.27* `termui <https://github.com/pallets/click/tree/main/examples/termui>`_ : A simple example that showcases terminal UI helpers provided by click.2877Examples of Click applications can be found in the documentation as well78as in the GitHub repository together with readme files:7980* ``inout``: `File input and output81 <https://github.com/pallets/click/tree/main/examples/inout>`_82* ``naval``: `Port of docopt naval example83 <https://github.com/pallets/click/tree/main/examples/naval>`_84* ``aliases``: `Command alias example85 <https://github.com/pallets/click/tree/main/examples/aliases>`_86* ``repo``: `Git-/Mercurial-like command line interface87 <https://github.com/pallets/click/tree/main/examples/repo>`_88* ``complex``: `Complex example with plugin loading89 <https://github.com/pallets/click/tree/main/examples/complex>`_90* ``validation``: `Custom parameter validation example91 <https://github.com/pallets/click/tree/main/examples/validation>`_92* ``colors``: `Color support demo93 <https://github.com/pallets/click/tree/main/examples/colors>`_94* ``termui``: `Terminal UI functions demo95 <https://github.com/pallets/click/tree/main/examples/termui>`_96* ``imagepipe``: `Multi command chaining demo97 <https://github.com/pallets/click/tree/main/examples/imagepipe>`_9829Basic Concepts - Creating a Command30-----------------------------------3132Click is based on declaring commands through decorators. Internally, there
178 unmodified lines
modified:docs/setuptools.rst+6 added-4 removed
79 unmodified lines
80 ],81 },82 )8384The magic is in the ``entry_points`` parameter. Below85``console_scripts``, each line identifies one console script. The first86part before the equals sign (``=``) is the name of the script that should87be generated, the second part is the import path followed by a colon84The magic is in the ``entry_points`` parameter. Read the full85`entry_points <https://packaging.python.org/en/latest/specifications/entry-points/>`_86specification for more details. Below ``console_scripts``, each87line identifies one console script. The first part before the88equals sign (``=``) is the name of the script that should be89generated, the second part is the import path followed by a colon90(``:``) with the Click command.9192That's it.93
62 unmodified lines
modified:docs/shell-completion.rst+14 added-10 removed
26 unmodified lines
27through an entry point, not through the ``python`` command. See28:doc:`/setuptools`. Once the executable is installed, calling it with29a special environment variable will put Click in completion mode.3031In order for completion to be used, the user needs to register a special32function with their shell. The script is different for every shell, and33Click will output it when called with ``_{PROG_NAME}_COMPLETE`` set to34``{shell}_source``. ``{PROG_NAME}`` is the executable name in uppercase35with dashes replaced by underscores. The built-in shells are ``bash``,36``zsh``, and ``fish``.31To enable shell completion, the user needs to register a special32function with their shell. The exact script varies depending on the33shell you are using. Click will output it when called with34``_{FOO_BAR}_COMPLETE`` set to ``{shell}_source``. ``{FOO_BAR}`` is35the executable name in uppercase with dashes replaced by underscores.36It is conventional but not strictly required for environment variable37names to be in upper case. This convention helps distinguish environment38variables from regular shell variables and commands, making scripts39and configuration files more readable and easier to maintain. The40built-in shells are ``bash``, ``zsh``, and ``fish``.4142Provide your users with the following instructions customized to your43program name. This uses ``foo-bar`` as an example.44
152 unmodified lines
197require implementing some smaller parts.198199First, you'll need to figure out how your shell's completion system200works and write a script to integrate it with Click. It must invoke your197program with the environment variable ``_{PROG_NAME}_COMPLETE`` set to201program with the environment variable ``_{FOO_BAR}_COMPLETE`` set to202``{shell}_complete`` and pass the complete args and incomplete value.203How it passes those values, and the format of the completion response204from Click is up to you.205
4 unmodified lines
210- ``complete_func`` - A safe name for the completion function defined211 in the script.212- ``complete_var`` - The environment variable name for passing the213 ``{shell}_complete`` instruction.210- ``prog_name`` - The name of the executable being completed.214- ``foo_bar`` - The name of the executable being completed.215216The example code is for a made up shell "My Shell" or "mysh" for short.217218.. code-block:: python
2 unmodified lines
221 from click.shell_completion import ShellComplete222223 _mysh_source = """\224 %(complete_func)s {221 response=$(%(complete_var)s=mysh_complete %(prog_name)s)225 response=$(%(complete_var)s=mysh_complete %(foo_bar)s)226 # parse response and set completions somehow227 }224 call-on-complete %(prog_name)s %(complete_func)s228 call-on-complete %(foo_bar)s %(complete_func)s229 """230231 @add_completion_class232 class MyshComplete(ShellComplete):
59 unmodified lines
added:docs/virtualenv.rst+54 added
1.. _virtualenv-heading:23Virtualenv4=========================56Why Use Virtualenv?7-------------------------89You should use `Virtualenv <https://virtualenv.pypa.io/en/latest/>`_ because:1011* It allows you to install multiple versions of the same dependency.1213* If you have an operating system version of Python, it prevents you from changing its dependencies and potentially messing up your os.1415How to Use Virtualenv16-----------------------------1718Create your project folder, then a virtualenv within it::1920 $ mkdir myproject21 $ cd myproject22 $ python3 -m venv .venv2324Now, whenever you want to work on a project, you only have to activate the25corresponding environment.2627.. tabs::2829 .. group-tab:: OSX/Linux3031 .. code-block:: text3233 $ . .venv/bin/activate34 (venv) $3536 .. group-tab:: Windows3738 .. code-block:: text3940 > .venv\scripts\activate41 (venv) >424344You are now using your virtualenv (notice how the prompt of your shell has changed to show the active environment).4546To install packages in the virtual environment::4748 $ pip install click4950And if you want to stop using the virtualenv, use the following command::5152 $ deactivate5354After doing this, the prompt of your shell should be as familiar as before.
modified:requirements/build.txt+7 added-8 removed
1# SHA1:80754af91bfb6d1073585b046fe0a474ce8685091#3# This file is autogenerated by pip-compile-multi4# To update, run:2# This file is autogenerated by pip-compile with Python 3.133# by the following command:4#6# pip-compile-multi5# pip-compile build.in6#8build==0.10.09 # via -r requirements/build.in10packaging==23.17build==1.2.2.post18 # via -r build.in9packaging==24.110 # via build12pyproject-hooks==1.0.011pyproject-hooks==1.2.012 # via build
modified:requirements/dev.txt+117 added-29 removed
1# SHA1:54b5b77ec8c7a0064ffa93b2fd16cb0130ba177c1#3# This file is autogenerated by pip-compile-multi4# To update, run:2# This file is autogenerated by pip-compile with Python 3.133# by the following command:4#6# pip-compile-multi5# pip-compile dev.in6#8-r docs.txt9-r tests.txt10-r typing.txt11build==0.10.07alabaster==1.0.08 # via sphinx9babel==2.16.010 # via sphinx11build==1.2.2.post112 # via pip-tools13cachetools==5.3.113cachetools==5.5.014 # via tox15certifi==2024.8.3016 # via requests15cfgv==3.3.117cfgv==3.4.018 # via pre-commit17chardet==5.1.019chardet==5.2.020 # via tox21charset-normalizer==3.4.022 # via requests19click==8.1.323click==8.1.724 # via25 # pip-compile-multi26 # pip-tools27colorama==0.4.628 # via tox25distlib==0.3.629distlib==0.3.930 # via virtualenv27filelock==3.12.231docutils==0.21.232 # via33 # sphinx34 # sphinx-tabs35filelock==3.16.136 # via37 # tox38 # virtualenv31identify==2.5.2439identify==2.6.140 # via pre-commit41idna==3.1042 # via requests43imagesize==1.4.144 # via sphinx45iniconfig==2.0.046 # via pytest47jinja2==3.1.448 # via sphinx49markupsafe==3.0.250 # via jinja251mypy==1.13.052 # via -r typing.in53mypy-extensions==1.0.054 # via mypy55nodeenv==1.9.156 # via57 # pre-commit58 # pyright59packaging==24.160 # via61 # build62 # pallets-sphinx-themes63 # pyproject-api64 # pytest65 # sphinx66 # tox67pallets-sphinx-themes==2.3.068 # via -r docs.in33pip-compile-multi==2.6.334 # via -r requirements/dev.in35pip-tools==6.13.069pip-compile-multi==2.6.470 # via -r dev.in71pip-tools==7.4.172 # via pip-compile-multi37platformdirs==3.8.073platformdirs==4.3.674 # via75 # tox76 # virtualenv41pre-commit==3.3.342 # via -r requirements/dev.in43pyproject-api==1.5.277pluggy==1.5.078 # via79 # pytest80 # tox81pre-commit==4.0.182 # via -r dev.in83pygments==2.18.084 # via85 # sphinx86 # sphinx-tabs87pyproject-api==1.8.088 # via tox45pyproject-hooks==1.0.046 # via build47pyyaml==6.089pyproject-hooks==1.2.090 # via91 # build92 # pip-tools93pyright==1.1.38694 # via -r typing.in95pytest==8.3.396 # via -r tests.in97pyyaml==6.0.298 # via pre-commit99requests==2.32.3100 # via sphinx101snowballstemmer==2.2.0102 # via sphinx103sphinx==8.1.3104 # via105 # -r docs.in106 # pallets-sphinx-themes107 # sphinx-issues108 # sphinx-notfound-page109 # sphinx-tabs110 # sphinxcontrib-log-cabinet111sphinx-issues==5.0.0112 # via -r docs.in113sphinx-notfound-page==1.0.4114 # via pallets-sphinx-themes115sphinx-tabs==3.4.7116 # via -r docs.in117sphinxcontrib-applehelp==2.0.0118 # via sphinx119sphinxcontrib-devhelp==2.0.0120 # via sphinx121sphinxcontrib-htmlhelp==2.1.0122 # via sphinx123sphinxcontrib-jsmath==1.0.1124 # via sphinx125sphinxcontrib-log-cabinet==1.0.1126 # via -r docs.in127sphinxcontrib-qthelp==2.0.0128 # via sphinx129sphinxcontrib-serializinghtml==2.0.0130 # via sphinx131toposort==1.10132 # via pip-compile-multi51tox==4.6.352 # via -r requirements/dev.in53virtualenv==20.23.1133tox==4.23.2134 # via -r dev.in135typing-extensions==4.12.2136 # via137 # mypy138 # pyright139urllib3==2.2.3140 # via requests141virtualenv==20.27.0142 # via143 # pre-commit144 # tox57wheel==0.40.0145wheel==0.44.0146 # via pip-tools147148# The following packages are considered to be unsafe in a requirements file:149# pip
1 unmodified line
modified:requirements/docs.txt+32 added-30 removed
1# SHA1:34fd4ca6516e97c7348e6facdd9c4ebb68209d1c1#3# This file is autogenerated by pip-compile-multi4# To update, run:2# This file is autogenerated by pip-compile with Python 3.133# by the following command:4#6# pip-compile-multi5# pip-compile docs.in6#8alabaster==0.7.137alabaster==1.0.08 # via sphinx10babel==2.12.19babel==2.16.010 # via sphinx12certifi==2023.5.711certifi==2024.8.3012 # via requests14charset-normalizer==3.1.013charset-normalizer==3.4.014 # via requests16docutils==0.18.115docutils==0.21.216 # via17 # sphinx18 # sphinx-tabs20idna==3.419idna==3.1020 # via requests21imagesize==1.4.122 # via sphinx24jinja2==3.1.223jinja2==3.1.424 # via sphinx26markupsafe==2.1.325markupsafe==3.0.226 # via jinja228packaging==23.127packaging==24.128 # via29 # pallets-sphinx-themes30 # sphinx32pallets-sphinx-themes==2.1.133 # via -r requirements/docs.in34pygments==2.15.131pallets-sphinx-themes==2.3.032 # via -r docs.in33pygments==2.18.034 # via35 # sphinx36 # sphinx-tabs38requests==2.31.037requests==2.32.338 # via sphinx39snowballstemmer==2.2.040 # via sphinx42sphinx==7.0.141sphinx==8.1.342 # via44 # -r requirements/docs.in43 # -r docs.in44 # pallets-sphinx-themes45 # sphinx-issues46 # sphinx-notfound-page47 # sphinx-tabs48 # sphinxcontrib-log-cabinet49sphinx-issues==3.0.150 # via -r requirements/docs.in51sphinx-tabs==3.4.152 # via -r requirements/docs.in53sphinxcontrib-applehelp==1.0.449sphinx-issues==5.0.050 # via -r docs.in51sphinx-notfound-page==1.0.452 # via pallets-sphinx-themes53sphinx-tabs==3.4.754 # via -r docs.in55sphinxcontrib-applehelp==2.0.056 # via sphinx55sphinxcontrib-devhelp==1.0.257sphinxcontrib-devhelp==2.0.058 # via sphinx57sphinxcontrib-htmlhelp==2.0.159sphinxcontrib-htmlhelp==2.1.060 # via sphinx61sphinxcontrib-jsmath==1.0.162 # via sphinx63sphinxcontrib-log-cabinet==1.0.162 # via -r requirements/docs.in63sphinxcontrib-qthelp==1.0.364 # via -r docs.in65sphinxcontrib-qthelp==2.0.066 # via sphinx65sphinxcontrib-serializinghtml==1.1.567sphinxcontrib-serializinghtml==2.0.068 # via sphinx67urllib3==2.0.369urllib3==2.2.370 # via requests
modified:requirements/tests.txt+7 added-8 removed
1# SHA1:0eaa389e1fdb3a1917c0f987514bd561be5718ee1#3# This file is autogenerated by pip-compile-multi4# To update, run:2# This file is autogenerated by pip-compile with Python 3.133# by the following command:4#6# pip-compile-multi5# pip-compile tests.in6#7iniconfig==2.0.08 # via pytest10packaging==23.19packaging==24.110 # via pytest12pluggy==1.2.011pluggy==1.5.012 # via pytest14pytest==7.4.015 # via -r requirements/tests.in13pytest==8.3.314 # via -r tests.in
added:requirements/tests37.txt+26 added
1#2# This file is autogenerated by pip-compile with Python 3.73# by the following command:4#5# pip-compile --output-file=tests37.txt tests.in6#7exceptiongroup==1.2.28 # via pytest9importlib-metadata==6.7.010 # via11 # pluggy12 # pytest13iniconfig==2.0.014 # via pytest15packaging==24.016 # via pytest17pluggy==1.2.018 # via pytest19pytest==7.4.420 # via -r tests.in21tomli==2.0.122 # via pytest23typing-extensions==4.7.124 # via importlib-metadata25zipp==3.15.026 # via importlib-metadata
modified:requirements/typing.txt+12 added-14 removed
1# SHA1:0d25c235a98f3c8c55aefb59b91c82834e185f0a1#3# This file is autogenerated by pip-compile-multi4# To update, run:2# This file is autogenerated by pip-compile with Python 3.133# by the following command:4#6# pip-compile-multi5# pip-compile typing.in6#8mypy==1.4.19 # via -r requirements/typing.in7mypy==1.13.08 # via -r typing.in9mypy-extensions==1.0.010 # via mypy12nodeenv==1.8.011nodeenv==1.9.112 # via pyright14pyright==1.1.31715 # via -r requirements/typing.in16typing-extensions==4.6.317 # via mypy1819# The following packages are considered to be unsafe in a requirements file:20# setuptools13pyright==1.1.38614 # via -r typing.in15typing-extensions==4.12.216 # via17 # mypy18 # pyright
modified:src/click/__init__.py+2 added
2 unmodified lines
3writing command line scripts fun. Unlike other modules, it's based4around a simple API that does not come with too much magic and is5composable.6"""78from .core import Argument as Argument9from .core import BaseCommand as BaseCommand10from .core import Command as Command11from .core import CommandCollection as CommandCollection
6 unmodified lines
18from .decorators import command as command19from .decorators import confirmation_option as confirmation_option20from .decorators import group as group21from .decorators import help_option as help_option22from .decorators import HelpOption as HelpOption23from .decorators import make_pass_decorator as make_pass_decorator24from .decorators import option as option25from .decorators import pass_context as pass_context26from .decorators import pass_obj as pass_obj
49 unmodified lines
modified:src/click/_compat.py+1 added-1 removed
514 unmodified lines
515 return locale.getpreferredencoding()516517 _ansi_stream_wrappers: t.MutableMapping[t.TextIO, t.TextIO] = WeakKeyDictionary()518519 def auto_wrap_for_ansi( # noqa: F811519 def auto_wrap_for_ansi(520 stream: t.TextIO, color: t.Optional[bool] = None521 ) -> t.TextIO:522 """Support ANSI color and style codes on Windows by wrapping a523 stream with colorama.
100 unmodified lines
modified:src/click/_termui_impl.py+2 added-1 removed
1 unmodified line
2This module contains implementations for the termui module. To keep the3import time of Click down, some infrequently used functionality is4placed in this module and only imported as needed.5"""67import contextlib8import math9import os10import sys
687 unmodified lines
698 _translate_ch_to_exc(rv)699 return rv700701else:701 import tty702 import termios703 import tty704705 @contextlib.contextmanager706 def raw_terminal() -> t.Iterator[int]:707 f: t.Optional[t.TextIO]
33 unmodified lines
modified:src/click/core.py+45 added-59 removed
37 unmodified lines
38from .utils import PacifyFlushWrapper3940if t.TYPE_CHECKING:41 import typing_extensions as te4243 from .shell_completion import CompletionItem4445F = t.TypeVar("F", bound=t.Callable[..., t.Any])46V = t.TypeVar("V")
336 unmodified lines
383 token_normalize_func = parent.token_normalize_func384385 #: An optional normalization function for tokens. This is386 #: options, choices, commands etc.386 self.token_normalize_func: t.Optional[387 t.Callable[[str], str]388 ] = token_normalize_func387 self.token_normalize_func: t.Optional[t.Callable[[str], str]] = (388 token_normalize_func389 )390391 #: Indicates if resilient parsing is enabled. In that case Click392 #: will do its best to not cause any failures and default values393 #: will be ignored. Useful for completion.
230 unmodified lines
624 return node625626 def find_object(self, object_type: t.Type[V]) -> t.Optional[V]:627 """Finds the closest object of a given type."""627 node: t.Optional["Context"] = self628 node: t.Optional[Context] = self629630 while node is not None:631 if isinstance(node.obj, object_type):632 return node.obj
13 unmodified lines
646647 @t.overload648 def lookup_default(649 self, name: str, call: "te.Literal[True]" = True649 ) -> t.Optional[t.Any]:650 ...650 ) -> t.Optional[t.Any]: ...651652 @t.overload653 def lookup_default(654 self, name: str, call: "te.Literal[False]" = ...655 ) -> t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]]:656 ...655 ) -> t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]]: ...656657 def lookup_default(self, name: str, call: bool = True) -> t.Optional[t.Any]:658 """Get the default for a parameter from :attr:`default_map`.659
51 unmodified lines
711 return type(self)(command, info_name=command.name, parent=self)712713 @t.overload714 def invoke(716 __self, # noqa: B902715 __self,716 __callback: "t.Callable[..., V]",717 *args: t.Any,718 **kwargs: t.Any,720 ) -> V:721 ...719 ) -> V: ...720721 @t.overload722 def invoke(725 __self, # noqa: B902723 __self,724 __callback: "Command",725 *args: t.Any,726 **kwargs: t.Any,729 ) -> t.Any:730 ...727 ) -> t.Any: ...728729 def invoke(733 __self, # noqa: B902730 __self,731 __callback: t.Union["Command", "t.Callable[..., V]"],732 *args: t.Any,733 **kwargs: t.Any,734 ) -> t.Union[t.Any, V]:
43 unmodified lines
778 with augment_usage_errors(__self):779 with ctx:780 return __callback(*args, **kwargs)781785 def forward(786 __self, __cmd: "Command", *args: t.Any, **kwargs: t.Any # noqa: B902787 ) -> t.Any:782 def forward(__self, __cmd: "Command", *args: t.Any, **kwargs: t.Any) -> t.Any:783 """Similar to :meth:`invoke` but fills in default keyword784 arguments from the current context if the other command expects785 it. This cannot invoke callbacks directly, only other commands.786
143 unmodified lines
930 if key not in extra:931 extra[key] = value932933 ctx = self.context_class(939 self, info_name=info_name, parent=parent, **extra # type: ignore934 self, # type: ignore[arg-type]935 info_name=info_name,936 parent=parent,937 **extra,938 )939940 with ctx.scope(cleanup=False):941 self.parse_args(ctx, args)
26 unmodified lines
968 .. versionadded:: 8.0969 """970 from click.shell_completion import CompletionItem971974 results: t.List["CompletionItem"] = []972 results: t.List[CompletionItem] = []973974 while ctx.parent is not None:975 ctx = ctx.parent976
13 unmodified lines
990 prog_name: t.Optional[str] = None,991 complete_var: t.Optional[str] = None,992 standalone_mode: "te.Literal[True]" = True,993 **extra: t.Any,996 ) -> "te.NoReturn":997 ...994 ) -> "te.NoReturn": ...995996 @t.overload997 def main(998 self,
1 unmodified line
1000 prog_name: t.Optional[str] = None,1001 complete_var: t.Optional[str] = None,1002 standalone_mode: bool = ...,1003 **extra: t.Any,1007 ) -> t.Any:1008 ...1004 ) -> t.Any: ...10051006 def main(1007 self,1008 args: t.Optional[t.Sequence[str]] = None,
207 unmodified lines
1216 self.callback = callback1217 #: the list of parameters for this command in the order they1218 #: should show up in the help page and execute. Eager parameters1219 #: will automatically be handled before non eager ones.1224 self.params: t.List["Parameter"] = params or []1220 self.params: t.List[Parameter] = params or []1221 self.help = help1222 self.epilog = epilog1223 self.options_metavar = options_metavar1224 self.short_help = short_help
59 unmodified lines
1284 all_names.difference_update(param.secondary_opts)1285 return list(all_names)12861287 def get_help_option(self, ctx: Context) -> t.Optional["Option"]:1292 """Returns the help option object."""1288 """Returns the help option object.12891290 Unless ``add_help_option`` is ``False``.1291 """1292 help_options = self.get_help_option_names(ctx)12931294 if not help_options or not self.add_help_option:1295 return None12961298 def show_help(ctx: Context, param: "Parameter", value: str) -> None:1299 if value and not ctx.resilient_parsing:1300 echo(ctx.get_help(), color=ctx.color)1301 ctx.exit()1297 # Avoid circular import.1298 from .decorators import HelpOption12991303 return Option(1304 help_options,1305 is_flag=True,1306 is_eager=True,1307 expose_value=False,1308 callback=show_help,1309 help=_("Show this message and exit."),1310 )1300 return HelpOption(help_options)13011302 def make_parser(self, ctx: Context) -> OptionParser:1303 """Creates the underlying option parser for this command."""1304 parser = OptionParser(ctx)
128 unmodified lines
1433 .. versionadded:: 8.01434 """1435 from click.shell_completion import CompletionItem14361447 results: t.List["CompletionItem"] = []1437 results: t.List[CompletionItem] = []14381439 if incomplete and not incomplete[0].isalnum():1440 for param in self.get_params(ctx):1441 if (
151 unmodified lines
1593 inner = old_callback(__value, *args, **kwargs)1594 return f(inner, *args, **kwargs)15951596 self._result_callback = rv = update_wrapper(t.cast(F, function), f)1607 return rv1597 return rv # type: ignore[return-value]15981599 return decorator16001601 def format_commands(self, ctx: Context, formatter: HelpFormatter) -> None:
230 unmodified lines
1832 _check_multicommand(self, name, cmd, register=True)1833 self.commands[name] = cmd18341835 @t.overload1846 def command(self, __func: t.Callable[..., t.Any]) -> Command:1847 ...1836 def command(self, __func: t.Callable[..., t.Any]) -> Command: ...18371838 @t.overload1839 def command(1840 self, *args: t.Any, **kwargs: t.Any1852 ) -> t.Callable[[t.Callable[..., t.Any]], Command]:1853 ...1841 ) -> t.Callable[[t.Callable[..., t.Any]], Command]: ...18421843 def command(1844 self, *args: t.Any, **kwargs: t.Any1845 ) -> t.Union[t.Callable[[t.Callable[..., t.Any]], Command], Command]:
35 unmodified lines
18811882 return decorator18831884 @t.overload1897 def group(self, __func: t.Callable[..., t.Any]) -> "Group":1898 ...1885 def group(self, __func: t.Callable[..., t.Any]) -> "Group": ...18861887 @t.overload1888 def group(1889 self, *args: t.Any, **kwargs: t.Any1903 ) -> t.Callable[[t.Callable[..., t.Any]], "Group"]:1904 ...1890 ) -> t.Callable[[t.Callable[..., t.Any]], "Group"]: ...18911892 def group(1893 self, *args: t.Any, **kwargs: t.Any1894 ) -> t.Union[t.Callable[[t.Callable[..., t.Any]], "Group"], "Group"]:
317 unmodified lines
22122213 @t.overload2214 def get_default(2215 self, ctx: Context, call: "te.Literal[True]" = True2230 ) -> t.Optional[t.Any]:2231 ...2216 ) -> t.Optional[t.Any]: ...22172218 @t.overload2219 def get_default(2220 self, ctx: Context, call: bool = ...2236 ) -> t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]]:2237 ...2221 ) -> t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]]: ...22222223 def get_default(2224 self, ctx: Context, call: bool = True2225 ) -> t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]]:
438 unmodified lines
26642665 if name is None:2666 if not expose_value:2667 return None, opts, secondary_opts2684 raise TypeError("Could not determine name for option")2668 raise TypeError(2669 f"Could not determine name for option with declarations {decls!r}"2670 )26712672 if not opts and not secondary_opts:2673 raise TypeError(2674 f"No options defined but a name was passed ({name})."
120 unmodified lines
2795 elif self.is_bool_flag and self.secondary_opts:2796 # For boolean flags that have distinct True/False opts,2797 # use the opt without prefix instead of the value.2798 default_string = split_opt(2813 (self.opts if self.default else self.secondary_opts)[0]2799 (self.opts if default_value else self.secondary_opts)[0]2800 )[1]2801 elif self.is_bool_flag and not self.secondary_opts and not default_value:2802 default_string = ""2803 elif default_value == "":2804 default_string = '""'2805 else:2806 default_string = str(default_value)28072808 if default_string:
20 unmodified lines
28292830 @t.overload2831 def get_default(2832 self, ctx: Context, call: "te.Literal[True]" = True2845 ) -> t.Optional[t.Any]:2846 ...2833 ) -> t.Optional[t.Any]: ...28342835 @t.overload2836 def get_default(2837 self, ctx: Context, call: bool = ...2851 ) -> t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]]:2852 ...2838 ) -> t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]]: ...28392840 def get_default(2841 self, ctx: Context, call: bool = True2842 ) -> t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]]:
163 unmodified lines
3006 ) -> t.Tuple[t.Optional[str], t.List[str], t.List[str]]:3007 if not decls:3008 if not expose_value:3009 return None, [], []3024 raise TypeError("Could not determine name for argument")3010 raise TypeError("Argument is marked as exposed, but does not have a name.")3011 if len(decls) == 1:3012 name = arg = decls[0]3013 name = name.replace("-", "_").lower()3014 else:
14 unmodified lines
modified:src/click/decorators.py+41 added-40 removed
91 unmodified lines
92 return ctx.invoke(f, obj, *args, **kwargs)9394 return update_wrapper(new_func, f)9596 return decorator # type: ignore[return-value]96 return decorator979899def pass_meta_key(100 key: str, *, doc_description: t.Optional[str] = None
24 unmodified lines
125 decorator.__doc__ = (126 f"Decorator that passes {doc_description} as the first argument"127 " to the decorated function."128 )129 return decorator # type: ignore[return-value]129 return decorator130131132CmdType = t.TypeVar("CmdType", bound=Command)133134135# variant: no call, directly as decorator for a function.136@t.overload137def command(name: _AnyCallable) -> Command:138 ...137def command(name: _AnyCallable) -> Command: ...138139140# variant: with positional name and with positional or keyword cls argument:141# @command(namearg, CommandCls, ...) or @command(namearg, cls=CommandCls, ...)
1 unmodified line
143def command(144 name: t.Optional[str],145 cls: t.Type[CmdType],146 **attrs: t.Any,148) -> t.Callable[[_AnyCallable], CmdType]:149 ...147) -> t.Callable[[_AnyCallable], CmdType]: ...148149150# variant: name omitted, cls _must_ be a keyword argument, @command(cls=CommandCls, ...)151@t.overload
1 unmodified line
153 name: None = None,154 *,155 cls: t.Type[CmdType],156 **attrs: t.Any,159) -> t.Callable[[_AnyCallable], CmdType]:160 ...157) -> t.Callable[[_AnyCallable], CmdType]: ...158159160# variant: with optional string name, no cls argument provided.161@t.overload162def command(163 name: t.Optional[str] = ..., cls: None = None, **attrs: t.Any167) -> t.Callable[[_AnyCallable], Command]:168 ...164) -> t.Callable[[_AnyCallable], Command]: ...165166167def command(168 name: t.Union[t.Optional[str], _AnyCallable] = None,
81 unmodified lines
250251252# variant: no call, directly as decorator for a function.253@t.overload258def group(name: _AnyCallable) -> Group:259 ...254def group(name: _AnyCallable) -> Group: ...255256257# variant: with positional name and with positional or keyword cls argument:258# @group(namearg, GroupCls, ...) or @group(namearg, cls=GroupCls, ...)
1 unmodified line
260def group(261 name: t.Optional[str],262 cls: t.Type[GrpType],263 **attrs: t.Any,269) -> t.Callable[[_AnyCallable], GrpType]:270 ...264) -> t.Callable[[_AnyCallable], GrpType]: ...265266267# variant: name omitted, cls _must_ be a keyword argument, @group(cmd=GroupCls, ...)268@t.overload
1 unmodified line
270 name: None = None,271 *,272 cls: t.Type[GrpType],273 **attrs: t.Any,280) -> t.Callable[[_AnyCallable], GrpType]:281 ...274) -> t.Callable[[_AnyCallable], GrpType]: ...275276277# variant: with optional string name, no cls argument provided.278@t.overload279def group(280 name: t.Optional[str] = ..., cls: None = None, **attrs: t.Any288) -> t.Callable[[_AnyCallable], Group]:289 ...281) -> t.Callable[[_AnyCallable], Group]: ...282283284def group(285 name: t.Union[str, _AnyCallable, None] = None,
200 unmodified lines
486 if version is None and package_name is not None:487 metadata: t.Optional[types.ModuleType]488489 try:498 from importlib import metadata # type: ignore490 from importlib import metadata491 except ImportError:492 # Python < 3.8493 import importlib_metadata as metadata # type: ignore494
26 unmodified lines
521 kwargs["callback"] = callback522 return option(*param_decls, **kwargs)523524533def help_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]:534 """Add a ``--help`` option which immediately prints the help page525class HelpOption(Option):526 """Pre-configured ``--help`` option which immediately prints the help page527 and exits the program.528 """529537 This is usually unnecessary, as the ``--help`` option is added to538 each command automatically unless ``add_help_option=False`` is539 passed.530 def __init__(531 self,532 param_decls: t.Optional[t.Sequence[str]] = None,533 **kwargs: t.Any,534 ) -> None:535 if not param_decls:536 param_decls = ("--help",)537541 :param param_decls: One or more option names. Defaults to the single542 value ``"--help"``.543 :param kwargs: Extra arguments are passed to :func:`option`.544 """538 kwargs.setdefault("is_flag", True)539 kwargs.setdefault("expose_value", False)540 kwargs.setdefault("is_eager", True)541 kwargs.setdefault("help", _("Show this message and exit."))542 kwargs.setdefault("callback", self.show_help)543546 def callback(ctx: Context, param: Parameter, value: bool) -> None:547 if not value or ctx.resilient_parsing:548 return544 super().__init__(param_decls, **kwargs)545546 @staticmethod547 def show_help(ctx: Context, param: Parameter, value: bool) -> None:548 """Callback that print the help page on ``<stdout>`` and exits."""549 if value and not ctx.resilient_parsing:550 echo(ctx.get_help(), color=ctx.color)551 ctx.exit()550 echo(ctx.get_help(), color=ctx.color)551 ctx.exit()552553 if not param_decls:554 param_decls = ("--help",)553556 kwargs.setdefault("is_flag", True)557 kwargs.setdefault("expose_value", False)558 kwargs.setdefault("is_eager", True)559 kwargs.setdefault("help", _("Show this message and exit."))560 kwargs["callback"] = callback554def help_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]:555 """Decorator for the pre-configured ``--help`` option defined above.556557 :param param_decls: One or more option names. Defaults to the single558 value ``"--help"``.559 :param kwargs: Extra arguments are passed to :func:`option`.560 """561 kwargs.setdefault("cls", HelpOption)562 return option(*param_decls, **kwargs)
modified:src/click/exceptions.py+11 added-3 removed
1 unmodified line
2from gettext import gettext as _3from gettext import ngettext45from ._compat import get_text_stderr6from .globals import resolve_color_default7from .utils import echo8from .utils import format_filename910if t.TYPE_CHECKING:
2 unmodified lines
13 from .core import Parameter141516def _join_param_hints(16 param_hint: t.Optional[t.Union[t.Sequence[str], str]]17 param_hint: t.Optional[t.Union[t.Sequence[str], str]],18) -> t.Optional[str]:19 if param_hint is not None and not isinstance(param_hint, str):20 return " / ".join(repr(x) for x in param_hint)21
7 unmodified lines
29 exit_code = 13031 def __init__(self, message: str) -> None:32 super().__init__(message)33 # The context will be removed by the time we print the message, so cache34 # the color settings here to be used later on (in `show`)35 self.show_color: t.Optional[bool] = resolve_color_default()36 self.message = message3738 def format_message(self) -> str:39 return self.message
4 unmodified lines
44 def show(self, file: t.Optional[t.IO[t.Any]] = None) -> None:45 if file is None:46 file = get_text_stderr()4744 echo(_("Error: {message}").format(message=self.format_message()), file=file)48 echo(49 _("Error: {message}").format(message=self.format_message()),50 file=file,51 color=self.show_color,52 )535455class UsageError(ClickException):56 """An internal exception that signals a usage error. This typically
8 unmodified lines
6566 def __init__(self, message: str, ctx: t.Optional["Context"] = None) -> None:67 super().__init__(message)68 self.ctx = ctx61 self.cmd: t.Optional["Command"] = self.ctx.command if self.ctx else None69 self.cmd: t.Optional[Command] = self.ctx.command if self.ctx else None7071 def show(self, file: t.Optional[t.IO[t.Any]] = None) -> None:72 if file is None:73 file = get_text_stderr()
223 unmodified lines
modified:src/click/globals.py+3 added-4 removed
1 unmodified line
2from threading import local34if t.TYPE_CHECKING:5 import typing_extensions as te67 from .core import Context89_local = local()101112@t.overload12def get_current_context(silent: "te.Literal[False]" = False) -> "Context":13 ...13def get_current_context(silent: "te.Literal[False]" = False) -> "Context": ...141516@t.overload17def get_current_context(silent: bool = ...) -> t.Optional["Context"]:18 ...17def get_current_context(silent: bool = ...) -> t.Optional["Context"]: ...181920def get_current_context(silent: bool = False) -> t.Optional["Context"]:21 """Returns the current click context. This can be used as a way to
46 unmodified lines
modified:src/click/parser.py+3 added-1 removed
15 unmodified lines
1617Copyright 2001-2006 Gregory P. Ward. All rights reserved.18Copyright 2002-2006 Python Software Foundation. All rights reserved.19"""2021# This code uses parts of optparse written by Gregory P. Ward and22# maintained by the Python Software Foundation.23# Copyright 2001-2006 Gregory P. Ward24# Copyright 2002-2006 Python Software Foundation
8 unmodified lines
33from .exceptions import UsageError3435if t.TYPE_CHECKING:36 import typing_extensions as te3738 from .core import Argument as CoreArgument39 from .core import Context40 from .core import Option as CoreOption41 from .core import Parameter as CoreParameter
206 unmodified lines
248 def __init__(self, rargs: t.List[str]) -> None:249 self.opts: t.Dict[str, t.Any] = {}250 self.largs: t.List[str] = []251 self.rargs = rargs250 self.order: t.List["CoreParameter"] = []252 self.order: t.List[CoreParameter] = []253254255class OptionParser:256 """The option parser is an internal class that is ultimately used to
275 unmodified lines
modified:src/click/termui.py+1 added-1 removed
171 unmodified lines
172 except UsageError as e:173 if hide_input:174 echo(_("Error: The value you entered was invalid."), err=err)175 else:176 echo(_("Error: {e.message}").format(e=e), err=err) # noqa: B306176 echo(_("Error: {e.message}").format(e=e), err=err)177 continue178 if not confirmation_prompt:179 return result180 while True:
604 unmodified lines
modified:src/click/testing.py+3 added-1 removed
6 unmodified lines
7import tempfile8import typing as t9from types import TracebackType1011from . import _compat12from . import formatting13from . import termui14from . import utils15from ._compat import _find_binary_reader
299 unmodified lines
315 termui.visible_prompt_func = visible_input316 termui.hidden_prompt_func = hidden_input317 termui._getchar = _getchar318 utils.should_strip_ansi = should_strip_ansi # type: ignore319 _compat.should_strip_ansi = should_strip_ansi320321 old_env = {}322 try:323 for key, value in env.items():
152 unmodified lines
476477 if temp_dir is None:478 try:479 shutil.rmtree(dt)478 except OSError: # noqa: B014480 except OSError:481 pass
modified:src/click/types.py+3 added-2 removed
13 unmodified lines
14from .utils import safecall1516if t.TYPE_CHECKING:17 import typing_extensions as te1819 from .core import Context20 from .core import Parameter21 from .shell_completion import CompletionItem22
714 unmodified lines
737 else:738 ctx.call_on_close(safecall(f.flush))739740 return f740 except OSError as e: # noqa: B014741 except OSError as e:742 self.fail(f"'{format_filename(value)}': {e.strerror}", param, ctx)743744 def shell_complete(745 self, ctx: "Context", param: "Parameter", incomplete: str
145 unmodified lines
891 ctx,892 )893 if not self.dir_okay and stat.S_ISDIR(st.st_mode):894 self.fail(894 _("{name} '{filename}' is a directory.").format(895 _("{name} {filename!r} is a directory.").format(896 name=self.name.title(), filename=format_filename(value)897 ),898 param,899 ctx,
191 unmodified lines
modified:src/click/utils.py+5 added-5 removed
154 unmodified lines
155 try:156 rv, self.should_close = open_stream(157 self.name, self.mode, self.encoding, self.errors, atomic=self.atomic158 )159 except OSError as e: # noqa: E402159 except OSError as e:160 from .exceptions import FileError161162 raise FileError(self.name, hint=e.strerror) from e163 self._f = rv
146 unmodified lines
310 if should_strip_ansi(file, color):311 out = strip_ansi(out)312 elif WIN:313 if auto_wrap_for_ansi is not None:314 file = auto_wrap_for_ansi(file) # type: ignore314 file = auto_wrap_for_ansi(file, color) # type: ignore315 elif not color:316 out = strip_ansi(out)317318 file.write(out) # type: ignore
33 unmodified lines
352 return opener(encoding, errors)353354355def open_file(356 filename: str,356 filename: t.Union[str, "os.PathLike[str]"],357 mode: str = "r",358 encoding: t.Optional[str] = None,359 errors: t.Optional[str] = "strict",360 lazy: bool = False,
12 unmodified lines
373374 with open_file(filename) as f:375 ...376377 :param filename: The name of the file to open, or ``'-'`` for377 :param filename: The name or Path of the file to open, or ``'-'`` for378 ``stdin``/``stdout``.379 :param mode: The mode in which to open the file.380 :param encoding: The encoding to decode or encode a file opened in381 text mode.
27 unmodified lines
409 displayed by replacing any invalid bytes or surrogate escapes in the name410 with the replacement character ``�``.411412 Invalid bytes or surrogate escapes will raise an error when written to a413 stream with ``errors="strict". This will typically happen with ``stdout``413 stream with ``errors="strict"``. This will typically happen with ``stdout``414 when the locale is something like ``en_GB.UTF-8``.415416 Many scenarios *are* safe to write surrogates though, due to PEP 538 and417 PEP 540, including:
207 unmodified lines
modified:tests/typing/typing_aliased_group.py+1 added
1"""Example from https://click.palletsprojects.com/en/8.1.x/advanced/#command-aliases"""23from __future__ import annotations45from typing_extensions import assert_type6
40 unmodified lines
modified:tests/typing/typing_confirmation_option.py+1 added
1"""From https://click.palletsprojects.com/en/8.1.x/options/#yes-parameters"""23from typing_extensions import assert_type45import click6
8 unmodified lines
modified:tests/typing/typing_options.py+1 added
1"""From https://click.palletsprojects.com/en/8.1.x/quickstart/#adding-parameters"""23from typing_extensions import assert_type45import click6
10 unmodified lines
modified:tests/typing/typing_simple_example.py+1 added
1"""The simple example from https://github.com/pallets/click#a-simple-example."""23from typing_extensions import assert_type45import click6
11 unmodified lines
modified:tests/typing/typing_version_option.py+1 added
1"""2From https://click.palletsprojects.com/en/8.1.x/options/#callbacks-and-eager-options.3"""45from typing_extensions import assert_type67import click8
8 unmodified lines
modified:tests/test_defaults.py+27 added-2 removed
3 unmodified lines
4def test_basic_defaults(runner):5 @click.command()6 @click.option("--foo", default=42, type=click.FLOAT)7 def cli(foo):8 assert type(foo) is float8 assert type(foo) is float # noqa E7219 click.echo(f"FOO:[{foo}]")1011 result = runner.invoke(cli, [])12 assert not result.exception
4 unmodified lines
17 @click.command()18 @click.option("--foo", default=[23, 42], type=click.FLOAT, multiple=True)19 def cli(foo):20 for item in foo:21 assert type(item) is float21 assert type(item) is float # noqa E72122 click.echo(item)2324 result = runner.invoke(cli, [])25 assert not result.exception
32 unmodified lines
58 assert result.return_value == ((), (), ())5960 result = runner.invoke(cli, ["-y", "-n", "-f", "-v", "-q"], standalone_mode=False)61 assert result.return_value == ((True, False), (True,), (1, -1))626364def test_flag_default_map(runner):65 """test flag with default map"""6667 @click.group()68 def cli():69 pass7071 @cli.command()72 @click.option("--name/--no-name", is_flag=True, show_default=True, help="name flag")73 def foo(name):74 click.echo(name)7576 result = runner.invoke(cli, ["foo"])77 assert "False" in result.output7879 result = runner.invoke(cli, ["foo", "--help"])80 assert "default: no-name" in result.output8182 result = runner.invoke(cli, ["foo"], default_map={"foo": {"name": True}})83 assert "True" in result.output8485 result = runner.invoke(cli, ["foo", "--help"], default_map={"foo": {"name": True}})86 assert "default: name" in result.output
modified:tests/test_imports.py-1 removed
2 unmodified lines
3import sys45from click._compat import WIN677IMPORT_TEST = b"""\8import builtins910found_imports = set()
57 unmodified lines
modified:tests/test_normalization.py-1 removed
1import click233CONTEXT_SETTINGS = dict(token_normalize_func=lambda x: x.lower())456def test_option_normalization(runner):
32 unmodified lines
modified:tests/test_options.py+8 added
784 unmodified lines
785 message = opt.get_help_record(ctx)[1]786 assert "[default: (unlimited)]" in message787788789def test_show_default_with_empty_string(runner):790 """When show_default is True and default is set to an empty string."""791 opt = click.Option(["--limit"], default="", show_default=True)792 ctx = click.Context(click.Command("cli"))793 message = opt.get_help_record(ctx)[1]794 assert '[default: ""]' in message795796797def test_do_not_show_no_default(runner):798 """When show_default is True and no default is set do not show None."""799 opt = click.Option(["--limit"], show_default=True)800 ctx = click.Context(click.Command("cli"))
128 unmodified lines
modified:tests/test_testing.py+22 added-3 removed
3 unmodified lines
45import pytest67import click8from click._compat import WIN8from click.exceptions import ClickException9from click.testing import CliRunner101112def test_runner():
170 unmodified lines
183 result = runner.invoke(cli)184 assert result.exit_code == 1185186187@pytest.mark.skipif(WIN, reason="Test does not make sense on Windows.")187def test_with_color():188 @click.command()189 def cli():190 click.secho("hello world", fg="blue")
8 unmodified lines
199 assert result.output == f"{click.style('hello world', fg='blue')}\n"200 assert not result.exception201202203def test_with_color_errors():204 class CLIError(ClickException):205 def format_message(self) -> str:206 return click.style(self.message, fg="red")207208 @click.command()209 def cli():210 raise CLIError("Red error")211212 runner = CliRunner()213214 result = runner.invoke(cli)215 assert result.output == "Error: Red error\n"216 assert result.exception217218 result = runner.invoke(cli, color=True)219 assert result.output == f"Error: {click.style('Red error', fg='red')}\n"220 assert result.exception221222223def test_with_color_but_pause_not_blocking():224 @click.command()225 def cli():226 click.pause()
112 unmodified lines
339 assert result_mix.output == "stdout\nstderr\n"340 assert result_mix.stdout == "stdout\nstderr\n"341342 with pytest.raises(ValueError):324 result_mix.stderr343 result_mix.stderr # noqa B018344345 @click.command()346 def cli_empty_stderr():347 click.echo("stdout")
92 unmodified lines
modified:tests/test_types.py+12 added
1import os.path2import pathlib3import platform4import tempfile56import pytest7
224 unmodified lines
232233def test_file_error_surrogates():234 message = FileError(filename="\udcff").format_message()235 assert message == "Could not open file '�': unknown error"236237238@pytest.mark.skipif(239 platform.system() == "Windows", reason="Filepath syntax differences."240)241def test_invalid_path_with_esc_sequence():242 with pytest.raises(click.BadParameter) as exc_info:243 with tempfile.TemporaryDirectory(prefix="my\ndir") as tempdir:244 click.Path(dir_okay=False).convert(tempdir, None, None)245246 assert "my\\ndir" in exc_info.value.message
modified:tests/test_utils.py+13 added-9 removed
34 unmodified lines
35 assert outstreams[0].getvalue() == b"\x1b[31mx\x1b[39m"363738def test_echo_custom_file():39 import io4041 f = io.StringIO()39 f = StringIO()40 click.echo("hello", file=f)41 assert f.getvalue() == "hello\n"4243
162 unmodified lines
206 out, err = capfd.readouterr()207 assert out == expected_output208209212@pytest.mark.skipif(WIN, reason="Test does not make sense on Windows.")210def test_echo_color_flag(monkeypatch, capfd):211 isatty = True212 monkeypatch.setattr(click._compat, "isatty", lambda x: isatty)213
14 unmodified lines
228 out, err = capfd.readouterr()229 assert out == f"{styled_text}\n"230231 isatty = False235 click.echo(styled_text)236 out, err = capfd.readouterr()237 assert out == f"{text}\n"232 # Faking isatty() is not enough on Windows;233 # the implementation caches the colorama wrapped stream234 # so we have to use a new stream for each test235 stream = StringIO()236 click.echo(styled_text, file=stream)237 assert stream.getvalue() == f"{text}\n"238239 stream = StringIO()240 click.echo(styled_text, file=stream, color=True)241 assert stream.getvalue() == f"{styled_text}\n"242243244def test_prompt_cast_default(capfd, monkeypatch):245 monkeypatch.setattr(sys, "stdin", StringIO("\n"))246 value = click.prompt("value", default="100", type=int)247 capfd.readouterr()244 assert type(value) is int248 assert type(value) is int # noqa E721249250251@pytest.mark.skipif(WIN, reason="Test too complex to make work windows.")252def test_echo_writing_to_standard_error(capfd, monkeypatch):
214 unmodified lines
467 user = os.path.expanduser("~")468 assert user in click.utils._expand_args(["~"])469 monkeypatch.setenv("CLICK_TEST", "hello")470 assert "hello" in click.utils._expand_args(["$CLICK_TEST"])467 assert "setup.cfg" in click.utils._expand_args(["*.cfg"])471 assert "pyproject.toml" in click.utils._expand_args(["*.toml"])472 assert os.path.join("docs", "conf.py") in click.utils._expand_args(["**/conf.py"])473 assert "*.not-found" in click.utils._expand_args(["*.not-found"])474 # a bad glob pattern, such as a pytest identifier, should return itself475 assert click.utils._expand_args(["test.py::test_bad"])[0] == "test.py::test_bad"
36 unmodified lines
modified:.editorconfig+1 added-1 removed
7 unmodified lines
8end_of_line = lf9charset = utf-810max_line_length = 881112[*.{yml,yaml,json,js,css,html}]12[*.{css,html,js,json,jsx,scss,ts,tsx,yaml,yml}]13indent_size = 2
modified:.gitignore+9 added-15 removed
1/.idea/2/.vscode/3.DS_Store/4/env/5/venv/1.idea/2.vscode/3.venv*/4venv*/5__pycache__/7*.pyc8*.egg-info/9/build/10/dist/11/.pytest_cache/12/.tox/13.coverage14.coverage.*15/htmlcov/16/docs/_build/6dist/7.coverage*8htmlcov/9.tox/10docs/_build/
modified:.pre-commit-config.yaml+7 added-24 removed
1ci:2 autoupdate_branch: "8.1.x"3 autoupdate_schedule: monthly1repos:5 - repo: https://github.com/asottile/pyupgrade6 rev: v3.10.12 - repo: https://github.com/astral-sh/ruff-pre-commit3 rev: v0.7.14 hooks:8 - id: pyupgrade9 args: ["--py37-plus"]10 - repo: https://github.com/asottile/reorder-python-imports11 rev: v3.10.012 hooks:13 - id: reorder-python-imports14 args: ["--application-directories", "src"]15 - repo: https://github.com/psf/black16 rev: 23.7.017 hooks:18 - id: black19 - repo: https://github.com/PyCQA/flake820 rev: 6.1.021 hooks:22 - id: flake823 additional_dependencies:24 - flake8-bugbear25 - flake8-implicit-str-concat5 - id: ruff6 - id: ruff-format7 - repo: https://github.com/pre-commit/pre-commit-hooks27 rev: v4.4.08 rev: v5.0.09 hooks:10 - id: check-merge-conflict11 - id: debug-statements12 - id: fix-byte-order-marker13 - id: trailing-whitespace14 - id: end-of-file-fixer
modified:.readthedocs.yaml+2 added-2 removed
1version: 22build:3 os: ubuntu-20.043 os: ubuntu-22.044 tools:5 python: "3.10"5 python: '3.12'6python:7 install:8 - requirements: requirements/docs.txt9 - method: pip
4 unmodified lines
modified:CHANGES.rst+18 added
1.. currentmodule:: click23Version 8.1.84-------------56Unreleased78- Fix an issue with type hints for ``click.open_file()``. :issue:`2717`9- Fix issue where error message for invalid ``click.Path`` displays on10 multiple lines. :issue:`2697`11- Fixed issue that prevented a default value of ``""`` from being displayed in12 the help for an option. :issue:`2500`13- The test runner handles stripping color consistently on Windows.14 :issue:`2705`15- Show correct value for flag default when using ``default_map``.16 :issue:`2632`17- Fix ``click.echo(color=...)`` passing ``color`` to coloroma so it can be18 forced on Windows. :issue:`2606`.192021Version 8.1.722-------------2324Released 2023-08-17
1100 unmodified lines
deleted:CODE_OF_CONDUCT.md-76 removed
1# Contributor Covenant Code of Conduct23## Our Pledge45In the interest of fostering an open and welcoming environment, we as6contributors and maintainers pledge to making participation in our project and7our community a harassment-free experience for everyone, regardless of age, body8size, disability, ethnicity, sex characteristics, gender identity and expression,9level of experience, education, socio-economic status, nationality, personal10appearance, race, religion, or sexual identity and orientation.1112## Our Standards1314Examples of behavior that contributes to creating a positive environment15include:1617* Using welcoming and inclusive language18* Being respectful of differing viewpoints and experiences19* Gracefully accepting constructive criticism20* Focusing on what is best for the community21* Showing empathy towards other community members2223Examples of unacceptable behavior by participants include:2425* The use of sexualized language or imagery and unwelcome sexual attention or26 advances27* Trolling, insulting/derogatory comments, and personal or political attacks28* Public or private harassment29* Publishing others' private information, such as a physical or electronic30 address, without explicit permission31* Other conduct which could reasonably be considered inappropriate in a32 professional setting3334## Our Responsibilities3536Project maintainers are responsible for clarifying the standards of acceptable37behavior and are expected to take appropriate and fair corrective action in38response to any instances of unacceptable behavior.3940Project maintainers have the right and responsibility to remove, edit, or41reject comments, commits, code, wiki edits, issues, and other contributions42that are not aligned to this Code of Conduct, or to ban temporarily or43permanently any contributor for other behaviors that they deem inappropriate,44threatening, offensive, or harmful.4546## Scope4748This Code of Conduct applies both within project spaces and in public spaces49when an individual is representing the project or its community. Examples of50representing a project or community include using an official project e-mail51address, posting via an official social media account, or acting as an appointed52representative at an online or offline event. Representation of a project may be53further defined and clarified by project maintainers.5455## Enforcement5657Instances of abusive, harassing, or otherwise unacceptable behavior may be58reported by contacting the project team at report@palletsprojects.com. All59complaints will be reviewed and investigated and will result in a response that60is deemed necessary and appropriate to the circumstances. The project team is61obligated to maintain confidentiality with regard to the reporter of an incident.62Further details of specific enforcement policies may be posted separately.6364Project maintainers who do not follow or enforce the Code of Conduct in good65faith may face temporary or permanent repercussions as determined by other66members of the project's leadership.6768## Attribution6970This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,71available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html7273[homepage]: https://www.contributor-covenant.org7475For answers to common questions about this code of conduct, see76https://www.contributor-covenant.org/faq
modified:CONTRIBUTING.rst+1 added-1 removed
142 unmodified lines
143144 .. code-block:: text145146 $ git fetch origin147 $ git checkout -b your-branch-name origin/8.0.x147 $ git checkout -b your-branch-name origin/8.1.x148149 If you're submitting a feature addition or change, branch off of the150 "main" branch.151
71 unmodified lines
deleted:LICENSE.rst-28 removed
1Copyright 2014 Pallets23Redistribution and use in source and binary forms, with or without4modification, are permitted provided that the following conditions are5met:671. Redistributions of source code must retain the above copyright8 notice, this list of conditions and the following disclaimer.9102. Redistributions in binary form must reproduce the above copyright11 notice, this list of conditions and the following disclaimer in the12 documentation and/or other materials provided with the distribution.13143. Neither the name of the copyright holder nor the names of its15 contributors may be used to endorse or promote products derived from16 this software without specific prior written permission.1718THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS19"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT20LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A21PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT22HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,23SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED24TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR25PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF26LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING27NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS28SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
added:LICENSE.txt+28 added
1Copyright 2014 Pallets23Redistribution and use in source and binary forms, with or without4modification, are permitted provided that the following conditions are5met:671. Redistributions of source code must retain the above copyright8 notice, this list of conditions and the following disclaimer.9102. Redistributions in binary form must reproduce the above copyright11 notice, this list of conditions and the following disclaimer in the12 documentation and/or other materials provided with the distribution.13143. Neither the name of the copyright holder nor the names of its15 contributors may be used to endorse or promote products derived from16 this software without specific prior written permission.1718THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS19"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT20LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A21PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT22HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,23SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED24TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR25PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF26LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING27NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS28SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
deleted:MANIFEST.in-10 removed
1include CHANGES.rst2include tox.ini3include requirements/*.txt4graft artwork5graft docs6prune docs/_build7graft examples8graft tests9include src/click/py.typed10global-exclude *.pyc
added:pyproject.toml+103 added
1[project]2name = "click"3description = "Composable command line interface toolkit"4readme = "README.md"5license = {file = "LICENSE.txt"}6maintainers = [{name = "Pallets", email = "contact@palletsprojects.com"}]7classifiers = [8 "Development Status :: 5 - Production/Stable",9 "Intended Audience :: Developers",10 "License :: OSI Approved :: BSD License",11 "Operating System :: OS Independent",12 "Programming Language :: Python",13 "Typing :: Typed",14]15requires-python = ">=3.7"16dependencies = [17 "colorama; platform_system == 'Windows'",18 "importlib-metadata; python_version < '3.8'",19]20dynamic = ["version"]2122[project.urls]23Donate = "https://palletsprojects.com/donate"24Documentation = "https://click.palletsprojects.com/"25Changes = "https://click.palletsprojects.com/changes/"26Source = "https://github.com/pallets/click/"27Chat = "https://discord.gg/pallets"2829[build-system]30requires = ["flit_core<4"]31build-backend = "flit_core.buildapi"3233[tool.flit.module]34name = "click"3536[tool.flit.sdist]37include = [38 "docs/",39 "requirements/",40 "tests/",41 "CHANGES.rst",42 "tox.ini",43]44exclude = [45 "docs/_build/",46]4748[tool.pytest.ini_options]49testpaths = ["tests"]50filterwarnings = [51 "error",52]5354[tool.coverage.run]55branch = true56source = ["click", "tests"]5758[tool.coverage.paths]59source = ["src", "*/site-packages"]6061[tool.mypy]62python_version = "3.8"63files = ["src/click", "tests/typing"]64show_error_codes = true65pretty = true66strict = true6768[[tool.mypy.overrides]]69module = [70 "colorama.*",71]72ignore_missing_imports = true7374[tool.pyright]75pythonVersion = "3.8"76include = ["src/click", "tests/typing"]77typeCheckingMode = "basic"7879[tool.ruff]80extend-exclude = ["examples/"]81src = ["src"]82fix = true83show-fixes = true84output-format = "full"8586[tool.ruff.lint]87select = [88 "B", # flake8-bugbear89 "E", # pycodestyle error90 "F", # pyflakes91 "I", # isort92 "UP", # pyupgrade93 "W", # pycodestyle warning94]9596[tool.ruff.lint.isort]97force-single-line = true98order-by-type = false99100[tool.gha-update]101tag-only = [102 "slsa-framework/slsa-github-generator",103]
added:README.md+52 added
1# $ click_23Click is a Python package for creating beautiful command line interfaces4in a composable way with as little code as necessary. It's the "Command5Line Interface Creation Kit". It's highly configurable but comes with6sensible defaults out of the box.78It aims to make the process of writing command line tools quick and fun9while also preventing any frustration caused by the inability to10implement an intended CLI API.1112Click in three points:1314- Arbitrary nesting of commands15- Automatic help page generation16- Supports lazy loading of subcommands at runtime171819## A Simple Example2021```python22import click2324@click.command()25@click.option("--count", default=1, help="Number of greetings.")26@click.option("--name", prompt="Your name", help="The person to greet.")27def hello(count, name):28 """Simple program that greets NAME for a total of COUNT times."""29 for _ in range(count):30 click.echo(f"Hello, {name}!")3132if __name__ == '__main__':33 hello()34```3536```37$ python hello.py --count=338Your name: Click39Hello, Click!40Hello, Click!41Hello, Click!42```434445## Donate4647The Pallets organization develops and supports Click and other popular48packages. In order to grow the community of contributors and users, and49allow the maintainers to devote more time to the projects, [please50donate today][].5152[please donate today]: https://palletsprojects.com/donate
deleted:README.rst-78 removed
1\$ click\_2==========34Click is a Python package for creating beautiful command line interfaces5in a composable way with as little code as necessary. It's the "Command6Line Interface Creation Kit". It's highly configurable but comes with7sensible defaults out of the box.89It aims to make the process of writing command line tools quick and fun10while also preventing any frustration caused by the inability to11implement an intended CLI API.1213Click in three points:1415- Arbitrary nesting of commands16- Automatic help page generation17- Supports lazy loading of subcommands at runtime181920Installing21----------2223Install and update using `pip`_:2425.. code-block:: text2627 $ pip install -U click2829.. _pip: https://pip.pypa.io/en/stable/getting-started/303132A Simple Example33----------------3435.. code-block:: python3637 import click3839 @click.command()40 @click.option("--count", default=1, help="Number of greetings.")41 @click.option("--name", prompt="Your name", help="The person to greet.")42 def hello(count, name):43 """Simple program that greets NAME for a total of COUNT times."""44 for _ in range(count):45 click.echo(f"Hello, {name}!")4647 if __name__ == '__main__':48 hello()4950.. code-block:: text5152 $ python hello.py --count=353 Your name: Click54 Hello, Click!55 Hello, Click!56 Hello, Click!575859Donate60------6162The Pallets organization develops and supports Click and other popular63packages. In order to grow the community of contributors and users, and64allow the maintainers to devote more time to the projects, `please65donate today`_.6667.. _please donate today: https://palletsprojects.com/donate686970Links71-----7273- Documentation: https://click.palletsprojects.com/74- Changes: https://click.palletsprojects.com/changes/75- PyPI Releases: https://pypi.org/project/click/76- Source Code: https://github.com/pallets/click77- Issue Tracker: https://github.com/pallets/click/issues78- Chat: https://discord.gg/pallets
deleted:setup.cfg-104 removed
1[metadata]2name = click3version = attr: click.__version__4url = https://palletsprojects.com/p/click/5project_urls =6 Donate = https://palletsprojects.com/donate7 Documentation = https://click.palletsprojects.com/8 Changes = https://click.palletsprojects.com/changes/9 Source Code = https://github.com/pallets/click/10 Issue Tracker = https://github.com/pallets/click/issues/11 Chat = https://discord.gg/pallets12license = BSD-3-Clause13license_files = LICENSE.rst14maintainer = Pallets15maintainer_email = contact@palletsprojects.com16description = Composable command line interface toolkit17long_description = file: README.rst18long_description_content_type = text/x-rst19classifiers =20 Development Status :: 5 - Production/Stable21 Intended Audience :: Developers22 License :: OSI Approved :: BSD License23 Operating System :: OS Independent24 Programming Language :: Python2526[options]27packages = find:28package_dir = = src29include_package_data = True30python_requires = >= 3.731# Dependencies are in setup.py for GitHub's dependency graph.3233[options.packages.find]34where = src3536[tool:pytest]37testpaths = tests38filterwarnings =39 error4041[coverage:run]42branch = True43source =44 click45 tests4647[coverage:paths]48source =49 src50 */site-packages5152[flake8]53# B = bugbear54# E = pycodestyle errors55# F = flake8 pyflakes56# W = pycodestyle warnings57# B9 = bugbear opinions58# ISC = implicit str concat59select = B, E, F, W, B9, ISC60ignore =61 # slice notation whitespace, invalid62 E20363 # line length, handled by bugbear B95064 E50165 # bare except, handled by bugbear B00166 E72267 # bin op line break, invalid68 W50369 # zip with strict=, requires python >= 3.1070 B90571 # string formatting opinion, B028 renamed to B90772 B02873 B90774# up to 88 allowed by bugbear B95075max-line-length = 8076per-file-ignores =77 # __init__ exports names78 src/click/__init__.py: F4017980[mypy]81files = src/click, tests/typing82python_version = 3.783show_error_codes = True84disallow_subclassing_any = True85disallow_untyped_calls = True86disallow_untyped_defs = True87disallow_incomplete_defs = True88disallow_any_generics = True89check_untyped_defs = True90no_implicit_optional = True91local_partial_types = True92no_implicit_reexport = True93strict_equality = True94warn_redundant_casts = True95warn_unused_configs = True96warn_unused_ignores = True97warn_return_any = True98warn_unreachable = True99100[mypy-colorama.*]101ignore_missing_imports = True102103[mypy-importlib_metadata.*]104ignore_missing_imports = True
deleted:setup.py-9 removed
1from setuptools import setup23setup(4 name="click",5 install_requires=[6 "colorama; platform_system == 'Windows'",7 "importlib-metadata; python_version < '3.8'",8 ],9)
modified:tox.ini+39 added-3 removed
1[tox]2envlist =3 py3{12,11,10,9,8,7}3 py3{13,12,11,10,9,8,7}4 pypy3105 style6 typing7 docs
1 unmodified line
910[testenv]11package = wheel12wheel_build_env = .pkg13constrain_package_deps = true14use_frozen_constraints = true15deps = -r requirements/tests.txt16commands = pytest -v --tb=short --basetemp={envtmpdir} {posargs}1718[testenv:py37,py3.7]19deps = -r requirements/tests37.txt2021[testenv:style]22deps = pre-commit23skip_install = true24commands = pre-commit run --all-files
1 unmodified line
26[testenv:typing]27deps = -r requirements/typing.txt28commands =29 mypy25 pyright --verifytypes click30 pyright tests/typing31 pyright --verifytypes click --ignoreexternal3233[testenv:docs]34deps = -r requirements/docs.txt30commands = sphinx-build -W -b html -d {envtmpdir}/doctrees docs {envtmpdir}/html35commands = sphinx-build -E -W -b dirhtml docs docs/_build/dirhtml3637[testenv:update-actions]38labels = update39deps = gha-update40commands = gha-update4142[testenv:update-pre_commit]43labels = update44deps = pre-commit45skip_install = true46commands = pre-commit autoupdate -j44748[testenv:update-requirements]49labels = update50deps = pip-tools51skip_install = true52change_dir = requirements53commands =54 pip-compile build.in -q {posargs:-U}55 pip-compile docs.in -q {posargs:-U}56 pip-compile tests.in -q {posargs:-U}57 pip-compile typing.in -q {posargs:-U}58 pip-compile dev.in -q {posargs:-U}5960[testenv:update-requirements37]61base_python = 3.762labels = update63deps = pip-tools64skip_install = true65change_dir = requirements66commands = pip-compile tests.in -q -o tests37.txt {posargs:-U}