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
Provenance
- Commit
82ffa4b- Tree
a23cae1- Author
unknown <edward.g2013@gmail.com>- Committer
unknown <edward.g2013@gmail.com>- Parent 1
f0f5ce1- Parent 2
26aa7bf
67 files changed+925 added−837 removed
added:.devcontainer/devcontainer.json+17 added
1234567891011121314151617{ "name": "pallets/click", "image": "mcr.microsoft.com/devcontainers/python:3", "customizations": { "vscode": { "settings": { "python.defaultInterpreterPath": "${workspaceFolder}/.venv", "python.terminal.activateEnvInCurrentTerminal": true, "python.terminal.launchArgs": [ "-X", "dev" ] } } }, "onCreateCommand": ".devcontainer/on-create-command.sh"}added:.devcontainer/on-create-command.sh+7 added
1234567#!/bin/bashset -epython3 -m venv --upgrade-deps .venv. .venv/bin/activatepip install -r requirements/dev.txtpip install -e .pre-commit install --install-hooksmodified:.github/ISSUE_TEMPLATE/bug-report.md+1 added-1 removed
3 unmodified lines456788910111215 unmodified lines3 unmodified lines---
<!--This issue tracker is a tool to address bugs in Click itself. Please usePallets Discord or Stack Overflow for questions about your own code.GitHub Discussions or the Pallets Discord for questions about your own code.
Replace this comment with a clear outline of what the bug is.-->
15 unmodified linesmodified:.github/ISSUE_TEMPLATE/config.yml+5 added-8 removed
12345678934567118blank_issues_enabled: falsecontact_links: - name: Security issue url: security@palletsprojects.com about: Do not report security issues publicly. Email our security contact. - name: Questions url: https://stackoverflow.com/questions/tagged/python-click?tab=Frequent about: Search for and ask questions about your code on Stack Overflow. - name: Questions and discussions - name: Questions on Discussions url: https://github.com/pallets/click/discussions/ about: Ask questions about your own code on the Discussions tab. - name: Questions on Chat url: https://discord.gg/pallets about: Discuss questions about your code on our Discord chat. about: Ask questions about your own code on our Discord chat.modified:.github/ISSUE_TEMPLATE/feature-request.md+3 added-3 removed
3 unmodified lines456788910111213141314153 unmodified lines---
<!--Replace this comment with a description of what the feature should do.Include details such as links relevant specs or previous discussions.Include details such as links to relevant specs or previous discussions.-->
<!--Replace this comment with an example of the problem which this featurewould resolve. Is this problem solvable without changes to Click,such as by subclassing or using an extension?would resolve. Is this problem solvable without changes to Click, suchas by subclassing or using an extension?-->modified:.github/workflows/lock.yaml+7 added-9 removed
12345123456789101011121413141715161718221920212223name: 'Lock threads'# Lock closed issues that have not received any further activity for# two weeks. This does not close open issues, only humans may do that.# We find that it is easier to respond to new issues with fresh examples# rather than continuing discussions on old issues.name: Lock inactive closed issues# Lock closed issues that have not received any further activity for two weeks.# This does not close open issues, only humans may do that. It is easier to# respond to new issues with fresh examples rather than continuing discussions# on old issues.
on: schedule: - cron: '0 0 * * *'
permissions: issues: write pull-requests: write
concurrency: group: lock
jobs: lock: runs-on: ubuntu-latest steps: - uses: dessant/lock-threads@c1b35aecc5cdb1a34539d14196df55838bb2f836 - uses: dessant/lock-threads@1bf7ec25051fe7c00bdd17e6a7cf3d7bfb7dc771 # v5.0.1 with: issue-inactive-days: 14 pr-inactive-days: 14 discussion-inactive-days: 14modified:.github/workflows/publish.yaml+16 added-15 removed
7 unmodified lines89101112131213141516171617181920212223242526262728293030313233343536363738394041424243444546474748495051525354555656575859596061626364656465666667686970707172737 unmodified lines runs-on: ubuntu-latest outputs: hash: ${{ steps.hash.outputs.hash }} steps: - uses: actions/checkout@8f4b7f84864484a7bf31766abe9204da3cbe65b3 - uses: actions/setup-python@d27e3f3d7c64b4bbf8e4abfb9b63b83e846e0435 - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - uses: actions/setup-python@0b93645e9fea7318ecaed2b359559ac225c90a2b # v5.3.0 with: python-version: '3.x' cache: 'pip' cache-dependency-path: 'requirements/*.txt' cache: pip cache-dependency-path: requirements*/*.txt - run: pip install -r requirements/build.txt # Use the commit date instead of the current date during the build. - run: echo "SOURCE_DATE_EPOCH=$(git log -1 --pretty=%ct)" >> $GITHUB_ENV - run: python -m build # Generate hashes used for provenance. - name: generate hash id: hash run: cd dist && echo "hash=$(sha256sum * | base64 -w0)" >> $GITHUB_OUTPUT - uses: actions/upload-artifact@0b7f8abb1508181956e8e162db84b466c27e18ce - uses: actions/upload-artifact@b4b15b8c7c6ac21ea08fcf65892d2ee8f75cf882 # v4.4.3 with: path: ./dist provenance: needs: ['build'] needs: [build] permissions: actions: read id-token: write contents: write # Can't pin with hash due to how this workflow works. uses: slsa-framework/slsa-github-generator/.github/workflows/generator_generic_slsa3.yml@v1.7.0 uses: slsa-framework/slsa-github-generator/.github/workflows/generator_generic_slsa3.yml@v2.0.0 with: base64-subjects: ${{ needs.build.outputs.hash }} create-release: # Upload the sdist, wheels, and provenance to a GitHub release. They remain # available as build artifacts for a while as well. needs: ['provenance'] needs: [provenance] runs-on: ubuntu-latest permissions: contents: write steps: - uses: actions/download-artifact@9bc31d5ccc31df68ecc42ccf4149144866c47d8a - uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8 - name: create release run: > gh release create --draft --repo ${{ github.repository }} ${{ github.ref_name }} *.intoto.jsonl/* artifact/* env: GH_TOKEN: ${{ github.token }} publish-pypi: needs: ['provenance'] needs: [provenance] # Wait for approval before attempting to upload to PyPI. This allows reviewing the # files in the draft release. environment: 'publish' environment: name: publish url: https://pypi.org/project/click/${{ github.ref_name }} runs-on: ubuntu-latest permissions: id-token: write steps: - uses: actions/download-artifact@9bc31d5ccc31df68ecc42ccf4149144866c47d8a # Try uploading to Test PyPI first, in case something fails. - uses: pypa/gh-action-pypi-publish@29930c9cf57955dc1b98162d0d8bc3ec80d9e75c - uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8 - uses: pypa/gh-action-pypi-publish@f7600683efdcb7656dec5b29656edb7bc586e597 # v1.10.3 with: repository-url: https://test.pypi.org/legacy/ packages-dir: artifact/ - uses: pypa/gh-action-pypi-publish@29930c9cf57955dc1b98162d0d8bc3ec80d9e75c - uses: pypa/gh-action-pypi-publish@f7600683efdcb7656dec5b29656edb7bc586e597 # v1.10.3 with: packages-dir: artifact/modified:.github/workflows/tests.yaml+34 added-39 removed
1 name: Tests2 on: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' ]8 jobs: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 typingdeleted:.github/dependabot.yml-9 removed
1-version: 22-updates: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 <!--2 Before opening a PR, open a ticket describing the issue or feature the3-PR will address. Follow the steps in CONTRIBUTING.rst.3+PR will address. An issue is not required for fixing typos in4+documentation, or other simple non-code changes.5 6 Replace this comment with a description of the change. Describe how it7 addresses the linked ticket.8 -->9 10 <!--11 Link to relevant issues or previous PRs, one per line. Use "fixes" to12 automatically close an issue.13+14+fixes #<issue number>15 -->16 14-- fixes #<issue number>15-17 <!--17-Ensure each step in CONTRIBUTING.rst is complete by adding an "x" to18-each box below.18+Ensure each step in CONTRIBUTING.rst is complete, especially the following:19 20-If 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 -->22-23-Checklist:24-25-- [ ] 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 lines434 435 def __enter__(self):436 path = os.path.join(self.home, "repo.db")437 self.db = open_database(path)438+ return self439 440 def __exit__(self, exc_type, exc_value, tb):441 self.db.close()442 47 unmodified linesmodified:docs/arguments.rst+3 added
105 unmodified lines106 .. click:run::107 108 invoke(touch, ['-foo.txt', 'bar.txt'])109 110+111+.. _environment-variables:112+113 Environment Variables114 ---------------------115 116 This 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 linesmodified:docs/conf.py+12 added-9 removed
8 unmodified lines9 release, version = get_version("Click")10 11 # General --------------------------------------------------------------12 13-master_doc = "index"13+default_role = "code"14 extensions = [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 ]22+autodoc_member_order = "bysource"23 autodoc_typehints = "description"23-intersphinx_mapping = {"python": ("https://docs.python.org/3/", None)}24-issues_github_path = "pallets/click"24+autodoc_preserve_defaults = True25+extlinks = {26+ "issue": ("https://github.com/pallets/click/issues/%s", "#%s"),27+ "pr": ("https://github.com/pallets/click/pull/%s", "#%s"),28+}29+intersphinx_mapping = {30+ "python": ("https://docs.python.org/3/", None),31+}32 33 # HTML -----------------------------------------------------------------34 35 html_theme = "click"16 unmodified lines52 html_favicon = "_static/click-icon.png"53 html_logo = "_static/click-logo-sidebar.png"54 html_title = f"Click Documentation ({version})"55 html_show_sourcelink = False49-50-# LaTeX ----------------------------------------------------------------51-52-latex_documents = [(master_doc, f"Click-{version}.tex", html_title, author, "manual")]modified:docs/documentation.rst+1 added-1 removed
34 unmodified lines35 36 .. _documenting-arguments:37 38 Documenting Arguments39-~~~~~~~~~~~~~~~~~~~~~39+----------------------40 41 :func:`click.argument` does not take a ``help`` parameter. This is to42 follow the general convention of Unix tools of using arguments for only43 the most necessary things, and to document them in the command help text224 unmodified linesmodified:docs/index.rst+1 added
66 unmodified lines67 :maxdepth: 268 69 why70 quickstart71+ virtualenv72 setuptools73 parameters74 options75 arguments34 unmodified linesmodified:docs/license.rst+2 added-1 removed
1 BSD-3-Clause License2 ====================3 4-.. include:: ../LICENSE.rst4+.. literalinclude:: ../LICENSE.txt5+ :language: textmodified:docs/parameters.rst+48 added-54 removed
1 unmodified line2 ==========3 4 .. currentmodule:: click5 6-Click supports two types of parameters for scripts: options and arguments.7-There is generally some confusion among authors of command line scripts of8-when to use which, so here is a quick overview of the differences. As its9-name indicates, an option is optional. While arguments can be optional10-within reason, they are much more restricted in how optional they can be.6+Click supports only two types of parameters for scripts (by design): options and arguments.7 12-To help you decide between options and arguments, the recommendation is13-to use arguments exclusively for things like going to subcommands or input14-filenames / URLs, and have everything else be an option instead.8+Options9+----------------10 16-Differences17------------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.18 19-Arguments can do less than options. The following features are only20-available for options:19+Arguments20+----------------21 22-* 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`.27 29-On the other hand arguments, unlike options, can accept an arbitrary number30-of arguments. Options can strictly ever only accept a fixed number of31-arguments (defaults to 1), or they may be specified multiple times using32-:ref:`multiple-options`.28+.. _parameter_names:29 30+Parameter Names31+---------------32+33+Parameters (options and arguments) have a name that will be used as34+the Python argument name when calling the decorated function with35+values.36+37+.. click:example::38+39+ @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)46+47+In 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`.48+The option's names are ``-t`` and ``--times``. More names are available for options and are covered in :ref:`options`.49+50+And what it looks like when run:51+52+.. click:run::53+54+ invoke(multi_echo, ['--times=3', 'index.txt'], prog_name='multi_echo')55+56 Parameter Types57 ---------------58 37-Parameters can be of different types. Types can be implemented with38-different behavior and some are supported out of the box:59+The supported parameter types are:60 61 ``str`` / :data:`click.STRING`:62 The default parameter type which indicates unicode strings.63 30 unmodified lines94 95 .. autoclass:: DateTime96 :noindex:97 77-Custom parameter types can be implemented by subclassing78-:class:`click.ParamType`. For simple cases, passing a Python function that79-fails with a `ValueError` is also supported, though discouraged.98+How to Implement Custom Types99+-------------------------------100 81-.. _parameter_names:101+To 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.102 83-Parameter Names84----------------85-86-Parameters (both options and arguments) have a name that will be used as87-the Python argument name when calling the decorated function with88-values.89-90-Arguments take only one positional name. To provide a different name for91-use in help text, see :ref:`doc-meta-variables`.92-93-Options can have many names that may be prefixed with one or two dashes.94-Names with one dash are parsed as short options, names with two are95-parsed as long options. If a name is not prefixed, it is used as the96-Python argument name and not parsed as an option name. Otherwise, the97-first name with a two dash prefix is used, or the first with a one dash98-prefix if there are none with two. The prefix is removed and dashes are99-converted to underscores to get the Python argument name.100-101-102-Implementing Custom Types103--------------------------104-105-To implement a custom type, you need to subclass the :class:`ParamType`106-class. Override the :meth:`~ParamType.convert` method to convert the107-value from a string to the correct type.108-103 The following code implements an integer type that accepts hex and octal104 numbers in addition to normal integers, and converts them into regular105 integers.106 31 unmodified linesmodified:docs/quickstart.rst+15 added-85 removed
1 unmodified line2 ==========3 4 .. currentmodule:: click5 6-You can get the library directly from PyPI::6+Install7+----------------------8+Install from PyPI::9 10 pip install click11 10-The installation into a :ref:`virtualenv` is heavily recommended.12+Installing into a virtual environment is highly recommended. We suggest :ref:`virtualenv-heading`.13 12-.. _virtualenv:13-14-virtualenv15-----------16-17-Virtualenv is probably what you want to use for developing Click18-applications.19-20-What problem does virtualenv solve? Chances are that you want to use it21-for other projects besides your Click script. But the more projects you22-have, the more likely it is that you will be working with different23-versions of Python itself, or at least different versions of Python24-libraries. Let's face it: quite often libraries break backwards25-compatibility, and it's unlikely that any serious application will have26-zero dependencies. So what do you do if two or more of your projects have27-conflicting dependencies?28-29-Virtualenv to the rescue! Virtualenv enables multiple side-by-side30-installations of Python, one for each project. It doesn't actually31-install separate copies of Python, but it does provide a clever way to32-keep different project environments isolated.33-34-Create your project folder, then a virtualenv within it::35-36- $ mkdir myproject37- $ cd myproject38- $ python3 -m venv .venv39-40-Now, whenever you want to work on a project, you only have to activate the41-corresponding environment. On OS X and Linux, do the following::42-43- $ . .venv/bin/activate44- (venv) $45-46-If you are a Windows user, the following command is for you::47-48- > .venv\scripts\activate49- (venv) >50-51-Either way, you should now be using your virtualenv (notice how the prompt of52-your shell has changed to show the active environment).53-54-And if you want to stop using the virtualenv, use the following command::55-56- $ deactivate57-58-After doing this, the prompt of your shell should be as familiar as before.59-60-Now, let's move on. Enter the following command to get Click activated in your61-virtualenv::62-63- $ pip install click64-65-A few seconds later and you are good to go.66-67-Screencast and Examples14+Examples15 -----------------------16 70-There is a screencast available which shows the basic API of Click and71-how to build simple applications with it. It also explores how to build72-commands with subcommands.17+Some 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.18 74-* `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.28 77-Examples of Click applications can be found in the documentation as well78-as in the GitHub repository together with readme files:79-80-* ``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>`_98-29 Basic Concepts - Creating a Command30 -----------------------------------31 32 Click is based on declaring commands through decorators. Internally, there178 unmodified linesmodified:docs/setuptools.rst+6 added-4 removed
79 unmodified lines80 ],81 },82 )83 84-The magic is in the ``entry_points`` parameter. Below85-``console_scripts``, each line identifies one console script. The first86-part before the equals sign (``=``) is the name of the script that should87-be generated, the second part is the import path followed by a colon84+The magic is in the ``entry_points`` parameter. Read the full85+`entry_points <https://packaging.python.org/en/latest/specifications/entry-points/>`_86+specification for more details. Below ``console_scripts``, each87+line identifies one console script. The first part before the88+equals sign (``=``) is the name of the script that should be89+generated, the second part is the import path followed by a colon90 (``:``) with the Click command.91 92 That's it.93 62 unmodified linesmodified:docs/shell-completion.rst+14 added-10 removed
26 unmodified lines27 through an entry point, not through the ``python`` command. See28 :doc:`/setuptools`. Once the executable is installed, calling it with29 a special environment variable will put Click in completion mode.30 31-In order for completion to be used, the user needs to register a special32-function with their shell. The script is different for every shell, and33-Click will output it when called with ``_{PROG_NAME}_COMPLETE`` set to34-``{shell}_source``. ``{PROG_NAME}`` is the executable name in uppercase35-with dashes replaced by underscores. The built-in shells are ``bash``,36-``zsh``, and ``fish``.31+To enable shell completion, the user needs to register a special32+function with their shell. The exact script varies depending on the33+shell you are using. Click will output it when called with34+``_{FOO_BAR}_COMPLETE`` set to ``{shell}_source``. ``{FOO_BAR}`` is35+the executable name in uppercase with dashes replaced by underscores.36+It is conventional but not strictly required for environment variable37+names to be in upper case. This convention helps distinguish environment38+variables from regular shell variables and commands, making scripts39+and configuration files more readable and easier to maintain. The40+built-in shells are ``bash``, ``zsh``, and ``fish``.41 42 Provide your users with the following instructions customized to your43 program name. This uses ``foo-bar`` as an example.44 152 unmodified lines197 require implementing some smaller parts.198 199 First, you'll need to figure out how your shell's completion system200 works and write a script to integrate it with Click. It must invoke your197-program with the environment variable ``_{PROG_NAME}_COMPLETE`` set to201+program with the environment variable ``_{FOO_BAR}_COMPLETE`` set to202 ``{shell}_complete`` and pass the complete args and incomplete value.203 How it passes those values, and the format of the completion response204 from Click is up to you.205 4 unmodified lines210 - ``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.215 216 The example code is for a made up shell "My Shell" or "mysh" for short.217 218 .. code-block:: python2 unmodified lines221 from click.shell_completion import ShellComplete222 223 _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 """230 231 @add_completion_class232 class MyshComplete(ShellComplete):59 unmodified linesadded:docs/virtualenv.rst+54 added
1+.. _virtualenv-heading:2+3+Virtualenv4+=========================5+6+Why Use Virtualenv?7+-------------------------8+9+You should use `Virtualenv <https://virtualenv.pypa.io/en/latest/>`_ because:10+11+* It allows you to install multiple versions of the same dependency.12+13+* If you have an operating system version of Python, it prevents you from changing its dependencies and potentially messing up your os.14+15+How to Use Virtualenv16+-----------------------------17+18+Create your project folder, then a virtualenv within it::19+20+ $ mkdir myproject21+ $ cd myproject22+ $ python3 -m venv .venv23+24+Now, whenever you want to work on a project, you only have to activate the25+corresponding environment.26+27+.. tabs::28+29+ .. group-tab:: OSX/Linux30+31+ .. code-block:: text32+33+ $ . .venv/bin/activate34+ (venv) $35+36+ .. group-tab:: Windows37+38+ .. code-block:: text39+40+ > .venv\scripts\activate41+ (venv) >42+43+44+You are now using your virtualenv (notice how the prompt of your shell has changed to show the active environment).45+46+To install packages in the virtual environment::47+48+ $ pip install click49+50+And if you want to stop using the virtualenv, use the following command::51+52+ $ deactivate53+54+After 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 #8-build==0.10.09- # via -r requirements/build.in10-packaging==23.17+build==1.2.2.post18+ # via -r build.in9+packaging==24.110 # via build12-pyproject-hooks==1.0.011+pyproject-hooks==1.2.012 # via buildmodified: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.txt11-build==0.10.07+alabaster==1.0.08+ # via sphinx9+babel==2.16.010+ # via sphinx11+build==1.2.2.post112 # via pip-tools13-cachetools==5.3.113+cachetools==5.5.014 # via tox15+certifi==2024.8.3016+ # via requests15-cfgv==3.3.117+cfgv==3.4.018 # via pre-commit17-chardet==5.1.019+chardet==5.2.020 # via tox21+charset-normalizer==3.4.022+ # via requests19-click==8.1.323+click==8.1.724 # via25 # pip-compile-multi26 # pip-tools27 colorama==0.4.628 # via tox25-distlib==0.3.629+distlib==0.3.930 # via virtualenv27-filelock==3.12.231+docutils==0.21.232 # via33+ # sphinx34+ # sphinx-tabs35+filelock==3.16.136+ # via37 # tox38 # virtualenv31-identify==2.5.2439+identify==2.6.140 # via pre-commit41+idna==3.1042+ # via requests43+imagesize==1.4.144+ # via sphinx45+iniconfig==2.0.046+ # via pytest47+jinja2==3.1.448+ # via sphinx49+markupsafe==3.0.250+ # via jinja251+mypy==1.13.052+ # via -r typing.in53+mypy-extensions==1.0.054+ # via mypy55+nodeenv==1.9.156+ # via57+ # pre-commit58+ # pyright59+packaging==24.160+ # via61+ # build62+ # pallets-sphinx-themes63+ # pyproject-api64+ # pytest65+ # sphinx66+ # tox67+pallets-sphinx-themes==2.3.068+ # via -r docs.in33-pip-compile-multi==2.6.334- # via -r requirements/dev.in35-pip-tools==6.13.069+pip-compile-multi==2.6.470+ # via -r dev.in71+pip-tools==7.4.172 # via pip-compile-multi37-platformdirs==3.8.073+platformdirs==4.3.674 # via75 # tox76 # virtualenv41-pre-commit==3.3.342- # via -r requirements/dev.in43-pyproject-api==1.5.277+pluggy==1.5.078+ # via79+ # pytest80+ # tox81+pre-commit==4.0.182+ # via -r dev.in83+pygments==2.18.084+ # via85+ # sphinx86+ # sphinx-tabs87+pyproject-api==1.8.088 # via tox45-pyproject-hooks==1.0.046- # via build47-pyyaml==6.089+pyproject-hooks==1.2.090+ # via91+ # build92+ # pip-tools93+pyright==1.1.38694+ # via -r typing.in95+pytest==8.3.396+ # via -r tests.in97+pyyaml==6.0.298 # via pre-commit99+requests==2.32.3100+ # via sphinx101+snowballstemmer==2.2.0102+ # via sphinx103+sphinx==8.1.3104+ # via105+ # -r docs.in106+ # pallets-sphinx-themes107+ # sphinx-issues108+ # sphinx-notfound-page109+ # sphinx-tabs110+ # sphinxcontrib-log-cabinet111+sphinx-issues==5.0.0112+ # via -r docs.in113+sphinx-notfound-page==1.0.4114+ # via pallets-sphinx-themes115+sphinx-tabs==3.4.7116+ # via -r docs.in117+sphinxcontrib-applehelp==2.0.0118+ # via sphinx119+sphinxcontrib-devhelp==2.0.0120+ # via sphinx121+sphinxcontrib-htmlhelp==2.1.0122+ # via sphinx123+sphinxcontrib-jsmath==1.0.1124+ # via sphinx125+sphinxcontrib-log-cabinet==1.0.1126+ # via -r docs.in127+sphinxcontrib-qthelp==2.0.0128+ # via sphinx129+sphinxcontrib-serializinghtml==2.0.0130+ # via sphinx131 toposort==1.10132 # via pip-compile-multi51-tox==4.6.352- # via -r requirements/dev.in53-virtualenv==20.23.1133+tox==4.23.2134+ # via -r dev.in135+typing-extensions==4.12.2136 # via137+ # mypy138+ # pyright139+urllib3==2.2.3140+ # via requests141+virtualenv==20.27.0142+ # via143 # pre-commit144 # tox57-wheel==0.40.0145+wheel==0.44.0146 # via pip-tools147 148 # The following packages are considered to be unsafe in a requirements file:149 # pip1 unmodified linemodified: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 #8-alabaster==0.7.137+alabaster==1.0.08 # via sphinx10-babel==2.12.19+babel==2.16.010 # via sphinx12-certifi==2023.5.711+certifi==2024.8.3012 # via requests14-charset-normalizer==3.1.013+charset-normalizer==3.4.014 # via requests16-docutils==0.18.115+docutils==0.21.216 # via17 # sphinx18 # sphinx-tabs20-idna==3.419+idna==3.1020 # via requests21 imagesize==1.4.122 # via sphinx24-jinja2==3.1.223+jinja2==3.1.424 # via sphinx26-markupsafe==2.1.325+markupsafe==3.0.226 # via jinja228-packaging==23.127+packaging==24.128 # via29 # pallets-sphinx-themes30 # sphinx32-pallets-sphinx-themes==2.1.133- # via -r requirements/docs.in34-pygments==2.15.131+pallets-sphinx-themes==2.3.032+ # via -r docs.in33+pygments==2.18.034 # via35 # sphinx36 # sphinx-tabs38-requests==2.31.037+requests==2.32.338 # via sphinx39 snowballstemmer==2.2.040 # via sphinx42-sphinx==7.0.141+sphinx==8.1.342 # via44- # -r requirements/docs.in43+ # -r docs.in44 # pallets-sphinx-themes45 # sphinx-issues46+ # sphinx-notfound-page47 # sphinx-tabs48 # sphinxcontrib-log-cabinet49-sphinx-issues==3.0.150- # via -r requirements/docs.in51-sphinx-tabs==3.4.152- # via -r requirements/docs.in53-sphinxcontrib-applehelp==1.0.449+sphinx-issues==5.0.050+ # via -r docs.in51+sphinx-notfound-page==1.0.452+ # via pallets-sphinx-themes53+sphinx-tabs==3.4.754+ # via -r docs.in55+sphinxcontrib-applehelp==2.0.056 # via sphinx55-sphinxcontrib-devhelp==1.0.257+sphinxcontrib-devhelp==2.0.058 # via sphinx57-sphinxcontrib-htmlhelp==2.0.159+sphinxcontrib-htmlhelp==2.1.060 # via sphinx61 sphinxcontrib-jsmath==1.0.162 # via sphinx63 sphinxcontrib-log-cabinet==1.0.162- # via -r requirements/docs.in63-sphinxcontrib-qthelp==1.0.364+ # via -r docs.in65+sphinxcontrib-qthelp==2.0.066 # via sphinx65-sphinxcontrib-serializinghtml==1.1.567+sphinxcontrib-serializinghtml==2.0.068 # via sphinx67-urllib3==2.0.369+urllib3==2.2.370 # via requestsmodified: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 #7 iniconfig==2.0.08 # via pytest10-packaging==23.19+packaging==24.110 # via pytest12-pluggy==1.2.011+pluggy==1.5.012 # via pytest14-pytest==7.4.015- # via -r requirements/tests.in13+pytest==8.3.314+ # via -r tests.inadded: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+#7+exceptiongroup==1.2.28+ # via pytest9+importlib-metadata==6.7.010+ # via11+ # pluggy12+ # pytest13+iniconfig==2.0.014+ # via pytest15+packaging==24.016+ # via pytest17+pluggy==1.2.018+ # via pytest19+pytest==7.4.420+ # via -r tests.in21+tomli==2.0.122+ # via pytest23+typing-extensions==4.7.124+ # via importlib-metadata25+zipp==3.15.026+ # via importlib-metadatamodified: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 #8-mypy==1.4.19- # via -r requirements/typing.in7+mypy==1.13.08+ # via -r typing.in9 mypy-extensions==1.0.010 # via mypy12-nodeenv==1.8.011+nodeenv==1.9.112 # via pyright14-pyright==1.1.31715- # via -r requirements/typing.in16-typing-extensions==4.6.317- # via mypy18-19-# The following packages are considered to be unsafe in a requirements file:20-# setuptools13+pyright==1.1.38614+ # via -r typing.in15+typing-extensions==4.12.216+ # via17+ # mypy18+ # pyrightmodified:src/click/__init__.py+2 added
2 unmodified lines3 writing command line scripts fun. Unlike other modules, it's based4 around a simple API that does not come with too much magic and is5 composable.6 """7+8 from .core import Argument as Argument9 from .core import BaseCommand as BaseCommand10 from .core import Command as Command11 from .core import CommandCollection as CommandCollection6 unmodified lines18 from .decorators import command as command19 from .decorators import confirmation_option as confirmation_option20 from .decorators import group as group21 from .decorators import help_option as help_option22+from .decorators import HelpOption as HelpOption23 from .decorators import make_pass_decorator as make_pass_decorator24 from .decorators import option as option25 from .decorators import pass_context as pass_context26 from .decorators import pass_obj as pass_obj49 unmodified linesmodified:src/click/_compat.py+1 added-1 removed
514 unmodified lines515 return locale.getpreferredencoding()516 517 _ansi_stream_wrappers: t.MutableMapping[t.TextIO, t.TextIO] = WeakKeyDictionary()518 519- 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 linesmodified:src/click/_termui_impl.py+2 added-1 removed
1 unmodified line2 This module contains implementations for the termui module. To keep the3 import time of Click down, some infrequently used functionality is4 placed in this module and only imported as needed.5 """6+7 import contextlib8 import math9 import os10 import sys687 unmodified lines698 _translate_ch_to_exc(rv)699 return rv700 701 else:701- import tty702 import termios703+ import tty704 705 @contextlib.contextmanager706 def raw_terminal() -> t.Iterator[int]:707 f: t.Optional[t.TextIO]33 unmodified linesmodified:src/click/core.py+45 added-59 removed
37 unmodified lines38 from .utils import PacifyFlushWrapper39 40 if t.TYPE_CHECKING:41 import typing_extensions as te42+43 from .shell_completion import CompletionItem44 45 F = t.TypeVar("F", bound=t.Callable[..., t.Any])46 V = t.TypeVar("V")336 unmodified lines383 token_normalize_func = parent.token_normalize_func384 385 #: 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+ )390 391 #: 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 lines624 return node625 626 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] = self629 630 while node is not None:631 if isinstance(node.obj, object_type):632 return node.obj13 unmodified lines646 647 @t.overload648 def lookup_default(649 self, name: str, call: "te.Literal[True]" = True649- ) -> t.Optional[t.Any]:650- ...650+ ) -> t.Optional[t.Any]: ...651 652 @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]]]: ...656 657 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 lines711 return type(self)(command, info_name=command.name, parent=self)712 713 @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: ...720 721 @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: ...728 729 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 lines778 with augment_usage_errors(__self):779 with ctx:780 return __callback(*args, **kwargs)781 785- 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 lines930 if key not in extra:931 extra[key] = value932 933 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 )939 940 with ctx.scope(cleanup=False):941 self.parse_args(ctx, args)26 unmodified lines968 .. versionadded:: 8.0969 """970 from click.shell_completion import CompletionItem971 974- results: t.List["CompletionItem"] = []972+ results: t.List[CompletionItem] = []973 974 while ctx.parent is not None:975 ctx = ctx.parent976 13 unmodified lines990 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": ...995 996 @t.overload997 def main(998 self,1 unmodified line1000 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: ...1005 1006 def main(1007 self,1008 args: t.Optional[t.Sequence[str]] = None,207 unmodified lines1216 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_help59 unmodified lines1284 all_names.difference_update(param.secondary_opts)1285 return list(all_names)1286 1287 def get_help_option(self, ctx: Context) -> t.Optional["Option"]:1292- """Returns the help option object."""1288+ """Returns the help option object.1289+1290+ Unless ``add_help_option`` is ``False``.1291+ """1292 help_options = self.get_help_option_names(ctx)1293 1294 if not help_options or not self.add_help_option:1295 return None1296 1298- 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 HelpOption1299 1303- 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)1301 1302 def make_parser(self, ctx: Context) -> OptionParser:1303 """Creates the underlying option parser for this command."""1304 parser = OptionParser(ctx)128 unmodified lines1433 .. versionadded:: 8.01434 """1435 from click.shell_completion import CompletionItem1436 1447- results: t.List["CompletionItem"] = []1437+ results: t.List[CompletionItem] = []1438 1439 if incomplete and not incomplete[0].isalnum():1440 for param in self.get_params(ctx):1441 if (151 unmodified lines1593 inner = old_callback(__value, *args, **kwargs)1594 return f(inner, *args, **kwargs)1595 1596 self._result_callback = rv = update_wrapper(t.cast(F, function), f)1607- return rv1597+ return rv # type: ignore[return-value]1598 1599 return decorator1600 1601 def format_commands(self, ctx: Context, formatter: HelpFormatter) -> None:230 unmodified lines1832 _check_multicommand(self, name, cmd, register=True)1833 self.commands[name] = cmd1834 1835 @t.overload1846- def command(self, __func: t.Callable[..., t.Any]) -> Command:1847- ...1836+ def command(self, __func: t.Callable[..., t.Any]) -> Command: ...1837 1838 @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]: ...1842 1843 def command(1844 self, *args: t.Any, **kwargs: t.Any1845 ) -> t.Union[t.Callable[[t.Callable[..., t.Any]], Command], Command]:35 unmodified lines1881 1882 return decorator1883 1884 @t.overload1897- def group(self, __func: t.Callable[..., t.Any]) -> "Group":1898- ...1885+ def group(self, __func: t.Callable[..., t.Any]) -> "Group": ...1886 1887 @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"]: ...1891 1892 def group(1893 self, *args: t.Any, **kwargs: t.Any1894 ) -> t.Union[t.Callable[[t.Callable[..., t.Any]], "Group"], "Group"]:317 unmodified lines2212 2213 @t.overload2214 def get_default(2215 self, ctx: Context, call: "te.Literal[True]" = True2230- ) -> t.Optional[t.Any]:2231- ...2216+ ) -> t.Optional[t.Any]: ...2217 2218 @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]]]: ...2222 2223 def get_default(2224 self, ctx: Context, call: bool = True2225 ) -> t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]]:438 unmodified lines2664 2665 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+ )2671 2672 if not opts and not secondary_opts:2673 raise TypeError(2674 f"No options defined but a name was passed ({name})."120 unmodified lines2795 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)2807 2808 if default_string:20 unmodified lines2829 2830 @t.overload2831 def get_default(2832 self, ctx: Context, call: "te.Literal[True]" = True2845- ) -> t.Optional[t.Any]:2846- ...2833+ ) -> t.Optional[t.Any]: ...2834 2835 @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]]]: ...2839 2840 def get_default(2841 self, ctx: Context, call: bool = True2842 ) -> t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]]:163 unmodified lines3006 ) -> 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 linesmodified:src/click/decorators.py+41 added-40 removed
91 unmodified lines92 return ctx.invoke(f, obj, *args, **kwargs)93 94 return update_wrapper(new_func, f)95 96- return decorator # type: ignore[return-value]96+ return decorator97 98 99 def pass_meta_key(100 key: str, *, doc_description: t.Optional[str] = None24 unmodified lines125 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 decorator130 131 132 CmdType = t.TypeVar("CmdType", bound=Command)133 134 135 # variant: no call, directly as decorator for a function.136 @t.overload137-def command(name: _AnyCallable) -> Command:138- ...137+def command(name: _AnyCallable) -> Command: ...138 139 140 # variant: with positional name and with positional or keyword cls argument:141 # @command(namearg, CommandCls, ...) or @command(namearg, cls=CommandCls, ...)1 unmodified line143 def 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]: ...148 149 150 # variant: name omitted, cls _must_ be a keyword argument, @command(cls=CommandCls, ...)151 @t.overload1 unmodified line153 name: None = None,154 *,155 cls: t.Type[CmdType],156 **attrs: t.Any,159-) -> t.Callable[[_AnyCallable], CmdType]:160- ...157+) -> t.Callable[[_AnyCallable], CmdType]: ...158 159 160 # variant: with optional string name, no cls argument provided.161 @t.overload162 def command(163 name: t.Optional[str] = ..., cls: None = None, **attrs: t.Any167-) -> t.Callable[[_AnyCallable], Command]:168- ...164+) -> t.Callable[[_AnyCallable], Command]: ...165 166 167 def command(168 name: t.Union[t.Optional[str], _AnyCallable] = None,81 unmodified lines250 251 252 # variant: no call, directly as decorator for a function.253 @t.overload258-def group(name: _AnyCallable) -> Group:259- ...254+def group(name: _AnyCallable) -> Group: ...255 256 257 # variant: with positional name and with positional or keyword cls argument:258 # @group(namearg, GroupCls, ...) or @group(namearg, cls=GroupCls, ...)1 unmodified line260 def 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]: ...265 266 267 # variant: name omitted, cls _must_ be a keyword argument, @group(cmd=GroupCls, ...)268 @t.overload1 unmodified line270 name: None = None,271 *,272 cls: t.Type[GrpType],273 **attrs: t.Any,280-) -> t.Callable[[_AnyCallable], GrpType]:281- ...274+) -> t.Callable[[_AnyCallable], GrpType]: ...275 276 277 # variant: with optional string name, no cls argument provided.278 @t.overload279 def group(280 name: t.Optional[str] = ..., cls: None = None, **attrs: t.Any288-) -> t.Callable[[_AnyCallable], Group]:289- ...281+) -> t.Callable[[_AnyCallable], Group]: ...282 283 284 def group(285 name: t.Union[str, _AnyCallable, None] = None,200 unmodified lines486 if version is None and package_name is not None:487 metadata: t.Optional[types.ModuleType]488 489 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 lines521 kwargs["callback"] = callback522 return option(*param_decls, **kwargs)523 524 533-def help_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]:534- """Add a ``--help`` option which immediately prints the help page525+class HelpOption(Option):526+ """Pre-configured ``--help`` option which immediately prints the help page527 and exits the program.528+ """529 537- 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",)537 541- :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)543 546- def callback(ctx: Context, param: Parameter, value: bool) -> None:547- if not value or ctx.resilient_parsing:548- return544+ super().__init__(param_decls, **kwargs)545 546+ @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()552 553- if not param_decls:554- param_decls = ("--help",)553 556- 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"] = callback554+def help_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]:555+ """Decorator for the pre-configured ``--help`` option defined above.556+557+ :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 line2 from gettext import gettext as _3 from gettext import ngettext4 5 from ._compat import get_text_stderr6+from .globals import resolve_color_default7 from .utils import echo8 from .utils import format_filename9 10 if t.TYPE_CHECKING:2 unmodified lines13 from .core import Parameter14 15 16 def _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 lines29 exit_code = 130 31 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 = message37 38 def format_message(self) -> str:39 return self.message4 unmodified lines44 def show(self, file: t.Optional[t.IO[t.Any]] = None) -> None:45 if file is None:46 file = get_text_stderr()47 44- 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+ )53 54 55 class UsageError(ClickException):56 """An internal exception that signals a usage error. This typically8 unmodified lines65 66 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 None70 71 def show(self, file: t.Optional[t.IO[t.Any]] = None) -> None:72 if file is None:73 file = get_text_stderr()223 unmodified linesmodified:src/click/globals.py+3 added-4 removed
1 unmodified line2 from threading import local3 4 if t.TYPE_CHECKING:5 import typing_extensions as te6+7 from .core import Context8 9 _local = local()10 11 12 @t.overload12-def get_current_context(silent: "te.Literal[False]" = False) -> "Context":13- ...13+def get_current_context(silent: "te.Literal[False]" = False) -> "Context": ...14 15 16 @t.overload17-def get_current_context(silent: bool = ...) -> t.Optional["Context"]:18- ...17+def get_current_context(silent: bool = ...) -> t.Optional["Context"]: ...18 19 20 def get_current_context(silent: bool = False) -> t.Optional["Context"]:21 """Returns the current click context. This can be used as a way to46 unmodified linesmodified:src/click/parser.py+3 added-1 removed
15 unmodified lines16 17 Copyright 2001-2006 Gregory P. Ward. All rights reserved.18 Copyright 2002-2006 Python Software Foundation. All rights reserved.19 """20+21 # 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 Foundation8 unmodified lines33 from .exceptions import UsageError34 35 if t.TYPE_CHECKING:36 import typing_extensions as te37+38 from .core import Argument as CoreArgument39 from .core import Context40 from .core import Option as CoreOption41 from .core import Parameter as CoreParameter206 unmodified lines248 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] = []253 254 255 class OptionParser:256 """The option parser is an internal class that is ultimately used to275 unmodified linesmodified:src/click/termui.py+1 added-1 removed
171 unmodified lines172 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 linesmodified:src/click/testing.py+3 added-1 removed
6 unmodified lines7 import tempfile8 import typing as t9 from types import TracebackType10 11+from . import _compat12 from . import formatting13 from . import termui14 from . import utils15 from ._compat import _find_binary_reader299 unmodified lines315 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_ansi320 321 old_env = {}322 try:323 for key, value in env.items():152 unmodified lines476 477 if temp_dir is None:478 try:479 shutil.rmtree(dt)478- except OSError: # noqa: B014480+ except OSError:481 passmodified:src/click/types.py+3 added-2 removed
13 unmodified lines14 from .utils import safecall15 16 if t.TYPE_CHECKING:17 import typing_extensions as te18+19 from .core import Context20 from .core import Parameter21 from .shell_completion import CompletionItem22 714 unmodified lines737 else:738 ctx.call_on_close(safecall(f.flush))739 740 return f740- except OSError as e: # noqa: B014741+ except OSError as e:742 self.fail(f"'{format_filename(value)}': {e.strerror}", param, ctx)743 744 def shell_complete(745 self, ctx: "Context", param: "Parameter", incomplete: str145 unmodified lines891 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 linesmodified:src/click/utils.py+5 added-5 removed
154 unmodified lines155 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 FileError161 162 raise FileError(self.name, hint=e.strerror) from e163 self._f = rv146 unmodified lines310 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)317 318 file.write(out) # type: ignore33 unmodified lines352 return opener(encoding, errors)353 354 355 def 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 lines373 374 with open_file(filename) as f:375 ...376 377- :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 lines409 displayed by replacing any invalid bytes or surrogate escapes in the name410 with the replacement character ``�``.411 412 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``.415 416 Many scenarios *are* safe to write surrogates though, due to PEP 538 and417 PEP 540, including:207 unmodified linesmodified:tests/typing/typing_aliased_group.py+1 added
1 """Example from https://click.palletsprojects.com/en/8.1.x/advanced/#command-aliases"""2+3 from __future__ import annotations4 5 from typing_extensions import assert_type6 40 unmodified linesmodified:tests/typing/typing_confirmation_option.py+1 added
1 """From https://click.palletsprojects.com/en/8.1.x/options/#yes-parameters"""2+3 from typing_extensions import assert_type4 5 import click6 8 unmodified linesmodified:tests/typing/typing_options.py+1 added
1 """From https://click.palletsprojects.com/en/8.1.x/quickstart/#adding-parameters"""2+3 from typing_extensions import assert_type4 5 import click6 10 unmodified linesmodified:tests/typing/typing_simple_example.py+1 added
1 """The simple example from https://github.com/pallets/click#a-simple-example."""2+3 from typing_extensions import assert_type4 5 import click6 11 unmodified linesmodified:tests/typing/typing_version_option.py+1 added
1 """2 From https://click.palletsprojects.com/en/8.1.x/options/#callbacks-and-eager-options.3 """4+5 from typing_extensions import assert_type6 7 import click8 8 unmodified linesmodified:tests/test_defaults.py+27 added-2 removed
3 unmodified lines4 def 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}]")10 11 result = runner.invoke(cli, [])12 assert not result.exception4 unmodified lines17 @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)23 24 result = runner.invoke(cli, [])25 assert not result.exception32 unmodified lines58 assert result.return_value == ((), (), ())59 60 result = runner.invoke(cli, ["-y", "-n", "-f", "-v", "-q"], standalone_mode=False)61 assert result.return_value == ((True, False), (True,), (1, -1))62+63+64+def test_flag_default_map(runner):65+ """test flag with default map"""66+67+ @click.group()68+ def cli():69+ pass70+71+ @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)75+76+ result = runner.invoke(cli, ["foo"])77+ assert "False" in result.output78+79+ result = runner.invoke(cli, ["foo", "--help"])80+ assert "default: no-name" in result.output81+82+ result = runner.invoke(cli, ["foo"], default_map={"foo": {"name": True}})83+ assert "True" in result.output84+85+ result = runner.invoke(cli, ["foo", "--help"], default_map={"foo": {"name": True}})86+ assert "default: name" in result.outputmodified:tests/test_imports.py-1 removed
2 unmodified lines3 import sys4 5 from click._compat import WIN6 7-7 IMPORT_TEST = b"""\8 import builtins9 10 found_imports = set()57 unmodified linesmodified:tests/test_normalization.py-1 removed
1 import click2 3-3 CONTEXT_SETTINGS = dict(token_normalize_func=lambda x: x.lower())4 5 6 def test_option_normalization(runner):32 unmodified linesmodified:tests/test_options.py+8 added
784 unmodified lines785 message = opt.get_help_record(ctx)[1]786 assert "[default: (unlimited)]" in message787 788 789+def 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 message795+796+797 def 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 linesmodified:tests/test_testing.py+22 added-3 removed
3 unmodified lines4 5 import pytest6 7 import click8-from click._compat import WIN8+from click.exceptions import ClickException9 from click.testing import CliRunner10 11 12 def test_runner():170 unmodified lines183 result = runner.invoke(cli)184 assert result.exit_code == 1185 186 187-@pytest.mark.skipif(WIN, reason="Test does not make sense on Windows.")187 def test_with_color():188 @click.command()189 def cli():190 click.secho("hello world", fg="blue")8 unmodified lines199 assert result.output == f"{click.style('hello world', fg='blue')}\n"200 assert not result.exception201 202 203+def test_with_color_errors():204+ class CLIError(ClickException):205+ def format_message(self) -> str:206+ return click.style(self.message, fg="red")207+208+ @click.command()209+ def cli():210+ raise CLIError("Red error")211+212+ runner = CliRunner()213+214+ result = runner.invoke(cli)215+ assert result.output == "Error: Red error\n"216+ assert result.exception217+218+ result = runner.invoke(cli, color=True)219+ assert result.output == f"Error: {click.style('Red error', fg='red')}\n"220+ assert result.exception221+222+223 def test_with_color_but_pause_not_blocking():224 @click.command()225 def cli():226 click.pause()112 unmodified lines339 assert result_mix.output == "stdout\nstderr\n"340 assert result_mix.stdout == "stdout\nstderr\n"341 342 with pytest.raises(ValueError):324- result_mix.stderr343+ result_mix.stderr # noqa B018344 345 @click.command()346 def cli_empty_stderr():347 click.echo("stdout")92 unmodified linesmodified:tests/test_types.py+12 added
1 import os.path2 import pathlib3+import platform4 import tempfile5 6 import pytest7 224 unmodified lines232 233 def test_file_error_surrogates():234 message = FileError(filename="\udcff").format_message()235 assert message == "Could not open file '�': unknown error"236+237+238+@pytest.mark.skipif(239+ platform.system() == "Windows", reason="Filepath syntax differences."240+)241+def 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)245+246+ assert "my\\ndir" in exc_info.value.messagemodified:tests/test_utils.py+13 added-9 removed
34 unmodified lines35 assert outstreams[0].getvalue() == b"\x1b[31mx\x1b[39m"36 37 38 def test_echo_custom_file():39- import io40-41- f = io.StringIO()39+ f = StringIO()40 click.echo("hello", file=f)41 assert f.getvalue() == "hello\n"42 43 162 unmodified lines206 out, err = capfd.readouterr()207 assert out == expected_output208 209 212-@pytest.mark.skipif(WIN, reason="Test does not make sense on Windows.")210 def test_echo_color_flag(monkeypatch, capfd):211 isatty = True212 monkeypatch.setattr(click._compat, "isatty", lambda x: isatty)213 14 unmodified lines228 out, err = capfd.readouterr()229 assert out == f"{styled_text}\n"230 231 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"238 239+ stream = StringIO()240+ click.echo(styled_text, file=stream, color=True)241+ assert stream.getvalue() == f"{styled_text}\n"242 243+244 def 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 E721249 250 251 @pytest.mark.skipif(WIN, reason="Test too complex to make work windows.")252 def test_echo_writing_to_standard_error(capfd, monkeypatch):214 unmodified lines467 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 linesmodified:.editorconfig+1 added-1 removed
7 unmodified lines8 end_of_line = lf9 charset = utf-810 max_line_length = 8811 12-[*.{yml,yaml,json,js,css,html}]12+[*.{css,html,js,json,jsx,scss,ts,tsx,yaml,yml}]13 indent_size = 2modified:.gitignore+9 added-15 removed
1-/.idea/2-/.vscode/3-.DS_Store/4-/env/5-/venv/1+.idea/2+.vscode/3+.venv*/4+venv*/5 __pycache__/7-*.pyc8-*.egg-info/9-/build/10-/dist/11-/.pytest_cache/12-/.tox/13-.coverage14-.coverage.*15-/htmlcov/16-/docs/_build/6+dist/7+.coverage*8+htmlcov/9+.tox/10+docs/_build/modified:.pre-commit-config.yaml+7 added-24 removed
1-ci:2- autoupdate_branch: "8.1.x"3- autoupdate_schedule: monthly1 repos: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-fixermodified:.readthedocs.yaml+2 added-2 removed
1 version: 22 build:3- os: ubuntu-20.043+ os: ubuntu-22.044 tools:5- python: "3.10"5+ python: '3.12'6 python:7 install:8 - requirements: requirements/docs.txt9 - method: pip4 unmodified linesmodified:CHANGES.rst+18 added
1 .. currentmodule:: click2 3+Version 8.1.84+-------------5+6+Unreleased7+8+- 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`.19+20+21 Version 8.1.722 -------------23 24 Released 2023-08-171100 unmodified linesdeleted:CODE_OF_CONDUCT.md-76 removed
1-# Contributor Covenant Code of Conduct2-3-## Our Pledge4-5-In the interest of fostering an open and welcoming environment, we as6-contributors and maintainers pledge to making participation in our project and7-our community a harassment-free experience for everyone, regardless of age, body8-size, disability, ethnicity, sex characteristics, gender identity and expression,9-level of experience, education, socio-economic status, nationality, personal10-appearance, race, religion, or sexual identity and orientation.11-12-## Our Standards13-14-Examples of behavior that contributes to creating a positive environment15-include:16-17-* 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 members22-23-Examples of unacceptable behavior by participants include:24-25-* 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 setting33-34-## Our Responsibilities35-36-Project maintainers are responsible for clarifying the standards of acceptable37-behavior and are expected to take appropriate and fair corrective action in38-response to any instances of unacceptable behavior.39-40-Project maintainers have the right and responsibility to remove, edit, or41-reject comments, commits, code, wiki edits, issues, and other contributions42-that are not aligned to this Code of Conduct, or to ban temporarily or43-permanently any contributor for other behaviors that they deem inappropriate,44-threatening, offensive, or harmful.45-46-## Scope47-48-This Code of Conduct applies both within project spaces and in public spaces49-when an individual is representing the project or its community. Examples of50-representing a project or community include using an official project e-mail51-address, posting via an official social media account, or acting as an appointed52-representative at an online or offline event. Representation of a project may be53-further defined and clarified by project maintainers.54-55-## Enforcement56-57-Instances of abusive, harassing, or otherwise unacceptable behavior may be58-reported by contacting the project team at report@palletsprojects.com. All59-complaints will be reviewed and investigated and will result in a response that60-is deemed necessary and appropriate to the circumstances. The project team is61-obligated to maintain confidentiality with regard to the reporter of an incident.62-Further details of specific enforcement policies may be posted separately.63-64-Project maintainers who do not follow or enforce the Code of Conduct in good65-faith may face temporary or permanent repercussions as determined by other66-members of the project's leadership.67-68-## Attribution69-70-This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,71-available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html72-73-[homepage]: https://www.contributor-covenant.org74-75-For answers to common questions about this code of conduct, see76-https://www.contributor-covenant.org/faqmodified:CONTRIBUTING.rst+1 added-1 removed
142 unmodified lines143 144 .. code-block:: text145 146 $ git fetch origin147- $ git checkout -b your-branch-name origin/8.0.x147+ $ git checkout -b your-branch-name origin/8.1.x148 149 If you're submitting a feature addition or change, branch off of the150 "main" branch.151 71 unmodified linesdeleted:LICENSE.rst-28 removed
1-Copyright 2014 Pallets2-3-Redistribution and use in source and binary forms, with or without4-modification, are permitted provided that the following conditions are5-met:6-7-1. Redistributions of source code must retain the above copyright8- notice, this list of conditions and the following disclaimer.9-10-2. 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.13-14-3. 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.17-18-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS19-"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT20-LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A21-PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT22-HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,23-SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED24-TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR25-PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF26-LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING27-NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS28-SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.added:LICENSE.txt+28 added
1+Copyright 2014 Pallets2+3+Redistribution and use in source and binary forms, with or without4+modification, are permitted provided that the following conditions are5+met:6+7+1. Redistributions of source code must retain the above copyright8+ notice, this list of conditions and the following disclaimer.9+10+2. 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.13+14+3. 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.17+18+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS19+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT20+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A21+PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT22+HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,23+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED24+TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR25+PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF26+LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING27+NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS28+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.deleted:MANIFEST.in-10 removed
1-include CHANGES.rst2-include tox.ini3-include requirements/*.txt4-graft artwork5-graft docs6-prune docs/_build7-graft examples8-graft tests9-include src/click/py.typed10-global-exclude *.pycadded:pyproject.toml+103 added
1+[project]2+name = "click"3+description = "Composable command line interface toolkit"4+readme = "README.md"5+license = {file = "LICENSE.txt"}6+maintainers = [{name = "Pallets", email = "contact@palletsprojects.com"}]7+classifiers = [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+]15+requires-python = ">=3.7"16+dependencies = [17+ "colorama; platform_system == 'Windows'",18+ "importlib-metadata; python_version < '3.8'",19+]20+dynamic = ["version"]21+22+[project.urls]23+Donate = "https://palletsprojects.com/donate"24+Documentation = "https://click.palletsprojects.com/"25+Changes = "https://click.palletsprojects.com/changes/"26+Source = "https://github.com/pallets/click/"27+Chat = "https://discord.gg/pallets"28+29+[build-system]30+requires = ["flit_core<4"]31+build-backend = "flit_core.buildapi"32+33+[tool.flit.module]34+name = "click"35+36+[tool.flit.sdist]37+include = [38+ "docs/",39+ "requirements/",40+ "tests/",41+ "CHANGES.rst",42+ "tox.ini",43+]44+exclude = [45+ "docs/_build/",46+]47+48+[tool.pytest.ini_options]49+testpaths = ["tests"]50+filterwarnings = [51+ "error",52+]53+54+[tool.coverage.run]55+branch = true56+source = ["click", "tests"]57+58+[tool.coverage.paths]59+source = ["src", "*/site-packages"]60+61+[tool.mypy]62+python_version = "3.8"63+files = ["src/click", "tests/typing"]64+show_error_codes = true65+pretty = true66+strict = true67+68+[[tool.mypy.overrides]]69+module = [70+ "colorama.*",71+]72+ignore_missing_imports = true73+74+[tool.pyright]75+pythonVersion = "3.8"76+include = ["src/click", "tests/typing"]77+typeCheckingMode = "basic"78+79+[tool.ruff]80+extend-exclude = ["examples/"]81+src = ["src"]82+fix = true83+show-fixes = true84+output-format = "full"85+86+[tool.ruff.lint]87+select = [88+ "B", # flake8-bugbear89+ "E", # pycodestyle error90+ "F", # pyflakes91+ "I", # isort92+ "UP", # pyupgrade93+ "W", # pycodestyle warning94+]95+96+[tool.ruff.lint.isort]97+force-single-line = true98+order-by-type = false99+100+[tool.gha-update]101+tag-only = [102+ "slsa-framework/slsa-github-generator",103+]added:README.md+52 added
1+# $ click_2+3+Click is a Python package for creating beautiful command line interfaces4+in a composable way with as little code as necessary. It's the "Command5+Line Interface Creation Kit". It's highly configurable but comes with6+sensible defaults out of the box.7+8+It aims to make the process of writing command line tools quick and fun9+while also preventing any frustration caused by the inability to10+implement an intended CLI API.11+12+Click in three points:13+14+- Arbitrary nesting of commands15+- Automatic help page generation16+- Supports lazy loading of subcommands at runtime17+18+19+## A Simple Example20+21+```python22+import click23+24+@click.command()25+@click.option("--count", default=1, help="Number of greetings.")26+@click.option("--name", prompt="Your name", help="The person to greet.")27+def 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}!")31+32+if __name__ == '__main__':33+ hello()34+```35+36+```37+$ python hello.py --count=338+Your name: Click39+Hello, Click!40+Hello, Click!41+Hello, Click!42+```43+44+45+## Donate46+47+The Pallets organization develops and supports Click and other popular48+packages. In order to grow the community of contributors and users, and49+allow the maintainers to devote more time to the projects, [please50+donate today][].51+52+[please donate today]: https://palletsprojects.com/donatedeleted:README.rst-78 removed
1-\$ click\_2-==========3-4-Click is a Python package for creating beautiful command line interfaces5-in a composable way with as little code as necessary. It's the "Command6-Line Interface Creation Kit". It's highly configurable but comes with7-sensible defaults out of the box.8-9-It aims to make the process of writing command line tools quick and fun10-while also preventing any frustration caused by the inability to11-implement an intended CLI API.12-13-Click in three points:14-15-- Arbitrary nesting of commands16-- Automatic help page generation17-- Supports lazy loading of subcommands at runtime18-19-20-Installing21-----------22-23-Install and update using `pip`_:24-25-.. code-block:: text26-27- $ pip install -U click28-29-.. _pip: https://pip.pypa.io/en/stable/getting-started/30-31-32-A Simple Example33-----------------34-35-.. code-block:: python36-37- import click38-39- @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}!")46-47- if __name__ == '__main__':48- hello()49-50-.. code-block:: text51-52- $ python hello.py --count=353- Your name: Click54- Hello, Click!55- Hello, Click!56- Hello, Click!57-58-59-Donate60-------61-62-The Pallets organization develops and supports Click and other popular63-packages. In order to grow the community of contributors and users, and64-allow the maintainers to devote more time to the projects, `please65-donate today`_.66-67-.. _please donate today: https://palletsprojects.com/donate68-69-70-Links71------72-73-- 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/palletsdeleted:setup.cfg-104 removed
1-[metadata]2-name = click3-version = attr: click.__version__4-url = https://palletsprojects.com/p/click/5-project_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/pallets12-license = BSD-3-Clause13-license_files = LICENSE.rst14-maintainer = Pallets15-maintainer_email = contact@palletsprojects.com16-description = Composable command line interface toolkit17-long_description = file: README.rst18-long_description_content_type = text/x-rst19-classifiers =20- Development Status :: 5 - Production/Stable21- Intended Audience :: Developers22- License :: OSI Approved :: BSD License23- Operating System :: OS Independent24- Programming Language :: Python25-26-[options]27-packages = find:28-package_dir = = src29-include_package_data = True30-python_requires = >= 3.731-# Dependencies are in setup.py for GitHub's dependency graph.32-33-[options.packages.find]34-where = src35-36-[tool:pytest]37-testpaths = tests38-filterwarnings =39- error40-41-[coverage:run]42-branch = True43-source =44- click45- tests46-47-[coverage:paths]48-source =49- src50- */site-packages51-52-[flake8]53-# B = bugbear54-# E = pycodestyle errors55-# F = flake8 pyflakes56-# W = pycodestyle warnings57-# B9 = bugbear opinions58-# ISC = implicit str concat59-select = B, E, F, W, B9, ISC60-ignore =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 B95075-max-line-length = 8076-per-file-ignores =77- # __init__ exports names78- src/click/__init__.py: F40179-80-[mypy]81-files = src/click, tests/typing82-python_version = 3.783-show_error_codes = True84-disallow_subclassing_any = True85-disallow_untyped_calls = True86-disallow_untyped_defs = True87-disallow_incomplete_defs = True88-disallow_any_generics = True89-check_untyped_defs = True90-no_implicit_optional = True91-local_partial_types = True92-no_implicit_reexport = True93-strict_equality = True94-warn_redundant_casts = True95-warn_unused_configs = True96-warn_unused_ignores = True97-warn_return_any = True98-warn_unreachable = True99-100-[mypy-colorama.*]101-ignore_missing_imports = True102-103-[mypy-importlib_metadata.*]104-ignore_missing_imports = Truedeleted:setup.py-9 removed
1-from setuptools import setup2-3-setup(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]2 envlist =3- py3{12,11,10,9,8,7}3+ py3{13,12,11,10,9,8,7}4 pypy3105 style6 typing7 docs1 unmodified line9 10 [testenv]11 package = wheel12 wheel_build_env = .pkg13+constrain_package_deps = true14+use_frozen_constraints = true15 deps = -r requirements/tests.txt16 commands = pytest -v --tb=short --basetemp={envtmpdir} {posargs}17 18+[testenv:py37,py3.7]19+deps = -r requirements/tests37.txt20+21 [testenv:style]22 deps = pre-commit23 skip_install = true24 commands = pre-commit run --all-files1 unmodified line26 [testenv:typing]27 deps = -r requirements/typing.txt28 commands =29 mypy25- pyright --verifytypes click30 pyright tests/typing31+ pyright --verifytypes click --ignoreexternal32 33 [testenv:docs]34 deps = -r requirements/docs.txt30-commands = sphinx-build -W -b html -d {envtmpdir}/doctrees docs {envtmpdir}/html35+commands = sphinx-build -E -W -b dirhtml docs docs/_build/dirhtml36+37+[testenv:update-actions]38+labels = update39+deps = gha-update40+commands = gha-update41+42+[testenv:update-pre_commit]43+labels = update44+deps = pre-commit45+skip_install = true46+commands = pre-commit autoupdate -j447+48+[testenv:update-requirements]49+labels = update50+deps = pip-tools51+skip_install = true52+change_dir = requirements53+commands =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}59+60+[testenv:update-requirements37]61+base_python = 3.762+labels = update63+deps = pip-tools64+skip_install = true65+change_dir = requirements66+commands = pip-compile tests.in -q -o tests37.txt {posargs:-U}