pax_global_header00006660000000000000000000000064150714076140014517gustar00rootroot0000000000000052 comment=1fa5b380d84e7cc0bddf0ea027050b8fa8420add asyncclick-8.3.0.5-async/000077500000000000000000000000001507140761400151305ustar00rootroot00000000000000asyncclick-8.3.0.5-async/.devcontainer/000077500000000000000000000000001507140761400176675ustar00rootroot00000000000000asyncclick-8.3.0.5-async/.devcontainer/devcontainer.json000066400000000000000000000006621507140761400232470ustar00rootroot00000000000000{ "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" } asyncclick-8.3.0.5-async/.devcontainer/on-create-command.sh000077500000000000000000000002451507140761400235200ustar00rootroot00000000000000#!/bin/bash set -e python3 -m venv --upgrade-deps .venv . .venv/bin/activate pip install -r requirements/dev.txt pip install -e . pre-commit install --install-hooks asyncclick-8.3.0.5-async/.editorconfig000066400000000000000000000003511507140761400176040ustar00rootroot00000000000000root = true [*] indent_style = space indent_size = 4 insert_final_newline = true trim_trailing_whitespace = true end_of_line = lf charset = utf-8 max_line_length = 88 [*.{css,html,js,json,jsx,scss,ts,tsx,yaml,yml}] indent_size = 2 asyncclick-8.3.0.5-async/.github/000077500000000000000000000000001507140761400164705ustar00rootroot00000000000000asyncclick-8.3.0.5-async/.github/ISSUE_TEMPLATE/000077500000000000000000000000001507140761400206535ustar00rootroot00000000000000asyncclick-8.3.0.5-async/.github/ISSUE_TEMPLATE/bug-report.md000066400000000000000000000011471507140761400232660ustar00rootroot00000000000000--- name: Bug report about: Report a bug in Click (not other projects which depend on Click) --- Environment: - Python version: - Click version: asyncclick-8.3.0.5-async/.github/ISSUE_TEMPLATE/config.yml000066400000000000000000000005141507140761400226430ustar00rootroot00000000000000blank_issues_enabled: false contact_links: - 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: Ask questions about your own code on our Discord chat. asyncclick-8.3.0.5-async/.github/ISSUE_TEMPLATE/feature-request.md000066400000000000000000000006401507140761400243160ustar00rootroot00000000000000--- name: Feature request about: Suggest a new feature for Click --- asyncclick-8.3.0.5-async/.github/pull_request_template.md000066400000000000000000000014661507140761400234400ustar00rootroot00000000000000 asyncclick-8.3.0.5-async/.github/workflows/000077500000000000000000000000001507140761400205255ustar00rootroot00000000000000asyncclick-8.3.0.5-async/.github/workflows/lock.yaml000066400000000000000000000012521507140761400223410ustar00rootroot00000000000000name: 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 discussions: write concurrency: group: lock jobs: lock: runs-on: ubuntu-latest steps: - uses: dessant/lock-threads@1bf7ec25051fe7c00bdd17e6a7cf3d7bfb7dc771 # v5.0.1 with: issue-inactive-days: 14 pr-inactive-days: 14 discussion-inactive-days: 14 asyncclick-8.3.0.5-async/.github/workflows/pre-commit.yaml000066400000000000000000000017271507140761400234740ustar00rootroot00000000000000name: pre-commit on: pull_request: push: branches: [main, stable] jobs: main: runs-on: ubuntu-latest steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - uses: astral-sh/setup-uv@f0ec1fc3b38f5e7cd731bb6ce540c5af426746bb # v6.1.0 with: enable-cache: true prune-cache: false - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 id: setup-python with: python-version-file: pyproject.toml - uses: actions/cache@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3 with: path: ~/.cache/pre-commit key: pre-commit|${{ hashFiles('pyproject.toml', '.pre-commit-config.yaml') }} - run: uv run --locked --group pre-commit pre-commit run --show-diff-on-failure --color=always --all-files - uses: pre-commit-ci/lite-action@5d6cc0eb514c891a40562a58a8e71576c5c7fb43 # v1.1.0 if: ${{ !cancelled() }} asyncclick-8.3.0.5-async/.github/workflows/publish.yaml000066400000000000000000000030031507140761400230530ustar00rootroot00000000000000name: Publish on: push: tags: ['*'] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - uses: astral-sh/setup-uv@f0ec1fc3b38f5e7cd731bb6ce540c5af426746bb # v6.1.0 with: enable-cache: true prune-cache: false - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 with: python-version-file: pyproject.toml - run: echo "SOURCE_DATE_EPOCH=$(git log -1 --pretty=%ct)" >> $GITHUB_ENV - run: uv build - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: path: ./dist create-release: needs: [build] runs-on: ubuntu-latest permissions: contents: write steps: - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 - name: create release run: gh release create --draft --repo ${{ github.repository }} ${{ github.ref_name }} artifact/* env: GH_TOKEN: ${{ github.token }} publish-pypi: needs: [build] 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@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 - uses: pypa/gh-action-pypi-publish@76f52bc884231f62b9a034ebfe128415bbaabdfc # v1.12.4 with: packages-dir: artifact/ asyncclick-8.3.0.5-async/.github/workflows/tests.yaml000066400000000000000000000033461507140761400225610ustar00rootroot00000000000000name: Tests on: pull_request: paths-ignore: ['docs/**', 'README.md'] push: branches: [main, stable] paths-ignore: ['docs/**', 'README.md'] jobs: tests: name: ${{ matrix.name || matrix.python }} runs-on: ${{ matrix.os || 'ubuntu-latest' }} strategy: fail-fast: false matrix: include: - {python: '3.13'} - {name: Windows, python: '3.13', os: windows-latest} - {name: Mac, python: '3.13', os: macos-latest} - {python: '3.12'} - {python: '3.11'} - {name: PyPy, python: 'pypy-3.11', tox: pypy3.11} steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - uses: astral-sh/setup-uv@f0ec1fc3b38f5e7cd731bb6ce540c5af426746bb # v6.1.0 with: enable-cache: true prune-cache: false - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 with: python-version: ${{ matrix.python }} - run: uv run --locked tox run -e ${{ matrix.tox || format('py{0}', matrix.python) }} typing: runs-on: ubuntu-latest steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - uses: astral-sh/setup-uv@f0ec1fc3b38f5e7cd731bb6ce540c5af426746bb # v6.1.0 with: enable-cache: true prune-cache: false - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 with: python-version-file: pyproject.toml - name: cache mypy uses: actions/cache@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3 with: path: ./.mypy_cache key: mypy|${{ hashFiles('pyproject.toml') }} - run: uv run --locked tox run -e typing asyncclick-8.3.0.5-async/.gitignore000066400000000000000000000002431507140761400171170ustar00rootroot00000000000000src/*.egg-info/ /.hypothesis/ /build/ /.pybuild/ .cache/ .idea/ .vscode/ __pycache__/ /dist/ /.pytest_cache/ dist/ .coverage* htmlcov/ .tox/ docs/_build/ /debian/ asyncclick-8.3.0.5-async/.pre-commit-config.yaml000066400000000000000000000011661507140761400214150ustar00rootroot00000000000000repos: - repo: https://github.com/astral-sh/ruff-pre-commit rev: 9aeda5d1f4bbd212c557da1ea78eca9e8c829e19 # frozen: v0.11.13 hooks: - id: ruff - id: ruff-format - repo: https://github.com/astral-sh/uv-pre-commit rev: a621b109bab2e7e832d98c88fd3e83399f4e6657 # frozen: 0.7.12 hooks: - id: uv-lock - repo: https://github.com/pre-commit/pre-commit-hooks rev: cef0300fd0fc4d2a87a85fa2093c6b283ea36f4b # frozen: v5.0.0 hooks: - id: check-merge-conflict - id: debug-statements - id: fix-byte-order-marker - id: trailing-whitespace - id: end-of-file-fixer asyncclick-8.3.0.5-async/.readthedocs.yaml000066400000000000000000000007701507140761400203630ustar00rootroot00000000000000version: 2 # Do not specify sphinx key here to be in full control of build steps. # https://docs.readthedocs.com/platform/stable/build-customization.html#extend-or-override-the-build-process build: os: ubuntu-24.04 tools: python: '3.13' jobs: install: - echo "Installing dependencies" - asdf plugin add uv - asdf install uv latest - asdf global uv latest build: html: - uv run --group docs sphinx-build -W -b dirhtml docs $READTHEDOCS_OUTPUT/html asyncclick-8.3.0.5-async/CHANGES.rst000066400000000000000000001567011507140761400167440ustar00rootroot00000000000000.. currentmodule:: click Version 8.3.0 -------------- Released 2025-09-15 - **Important: Breaking asyncclick change**: :func:`asyncclick.prompt` is now async. It accepts a new `blocking` parameter to switch between keeping the async loop running (`False`) and not going belly-up when the user interrupts it using Control-C (`True`). `True` thus is the default (for now). - **Breaking asyncclick change**: ``Context.exit`` has been renamed to :meth:`Context.aexit` and is now async, due to the fact that async teardown callbacks and context managers needed better support. - **Improved flag option handling**: Reworked the relationship between ``flag_value`` and ``default`` parameters for better consistency: * The ``default`` parameter value is now preserved as-is and passed directly to CLI functions (no more unexpected transformations) * Exception: flag options with ``default=True`` maintain backward compatibility by defaulting to their ``flag_value`` * The ``default`` parameter can now be any type (``bool``, ``None``, etc.) * Fixes inconsistencies reported in: :issue:`1992` :issue:`2514` :issue:`2610` :issue:`3024` :pr:`3030` - Allow ``default`` to be set on ``Argument`` for ``nargs = -1``. :issue:`2164` :pr:`3030` - Show correct auto complete value for ``nargs`` option in combination with flag option :issue:`2813` - Show correct auto complete value for nargs option in combination with flag option :issue:`2813` - Fix handling of quoted and escaped parameters in Fish autocompletion. :issue:`2995` :pr:`3013` - Lazily import ``shutil``. :pr:`3023` - Properly forward exception information to resources registered with ``click.core.Context.with_resource()``. :issue:`2447` :pr:`3058` - Fix regression related to EOF handling in CliRunner. :issue:`2939`:pr:`2940` Version 8.2.2 ------------- Released 2025-07-31 - Fix reconciliation of ``default``, ``flag_value`` and ``type`` parameters for flag options, as well as parsing and normalization of environment variables. :issue:`2952` :pr:`2956` - Fix typing issue in ``BadParameter`` and ``MissingParameter`` exceptions for the parameter ``param_hint`` that did not allow for a sequence of string where the underlying function ``_join_param_hints`` allows for it. :issue:`2777` :pr:`2990` - Use the value of ``Enum`` choices to render their default value in help screen. Refs :issue:`2911` :pr:`3004` - Fix completion for the Z shell (``zsh``) for completion items containing colons. :issue:`2703` :pr:`2846` - Don't include envvar in error hint when not configured. :issue:`2971` :pr:`2972` - Fix a rare race in ``click.testing.StreamMixer``'s finalization that manifested as a ``ValueError`` on close in a multi-threaded test session. :issue:`2993` :pr:`2991` Version 8.2.1 ------------- Released 2025-05-20 - Fix flag value handling for flag options with a provided type. :issue:`2894` :issue:`2897` :pr:`2930` - Fix shell completion for nested groups. :issue:`2906` :pr:`2907` - Flush ``sys.stderr`` at the end of ``CliRunner.invoke``. :issue:`2682` - Fix EOF handling for stdin input in CliRunner. :issue:`2787` Version 8.2.0 ------------- Released 2025-05-10 - Drop support for Python 3.7, 3.8, and 3.9. :pr:`2588` :pr:`2893` - Use modern packaging metadata with ``pyproject.toml`` instead of ``setup.cfg``. :pr:`2438` - Use ``flit_core`` instead of ``setuptools`` as build backend. :pr:`2543` - Deprecate the ``__version__`` attribute. Use feature detection, or ``importlib.metadata.version("click")``, instead. :issue:`2598` - ``BaseCommand`` is deprecated. ``Command`` is the base class for all commands. :issue:`2589` - ``MultiCommand`` is deprecated. ``Group`` is the base class for all group commands. :issue:`2590` - The current parser and related classes and methods, are deprecated. :issue:`2205` - ``OptionParser`` and the ``parser`` module, which is a modified copy of ``optparse`` in the standard library. - ``Context.protected_args`` is unneeded. ``Context.args`` contains any remaining arguments while parsing. - ``Parameter.add_to_parser`` (on both ``Argument`` and ``Option``) is unneeded. Parsing works directly without building a separate parser. - ``split_arg_string`` is moved from ``parser`` to ``shell_completion``. - Enable deferred evaluation of annotations with ``from __future__ import annotations``. :pr:`2270` - When generating a command's name from a decorated function's name, the suffixes ``_command``, ``_cmd``, ``_group``, and ``_grp`` are removed. :issue:`2322` - Show the ``types.ParamType.name`` for ``types.Choice`` options within ``--help`` message if ``show_choices=False`` is specified. :issue:`2356` - Do not display default values in prompts when ``Option.show_default`` is ``False``. :pr:`2509` - Add ``get_help_extra`` method on ``Option`` to fetch the generated extra items used in ``get_help_record`` to render help text. :issue:`2516` :pr:`2517` - Keep stdout and stderr streams independent in ``CliRunner``. Always collect stderr output and never raise an exception. Add a new output stream to simulate what the user sees in its terminal. Removes the ``mix_stderr`` parameter in ``CliRunner``. :issue:`2522` :pr:`2523` - ``Option.show_envvar`` now also shows environment variable in error messages. :issue:`2695` :pr:`2696` - ``Context.close`` will be called on exit. This results in all ``Context.call_on_close`` callbacks and context managers added via ``Context.with_resource`` to be closed on exit as well. :pr:`2680` - Add ``ProgressBar(hidden: bool)`` to allow hiding the progressbar. :issue:`2609` - A ``UserWarning`` will be shown when multiple parameters attempt to use the same name. :issue:`2396` - When using ``Option.envvar`` with ``Option.flag_value``, the ``flag_value`` will always be used instead of the value of the environment variable. :issue:`2746` :pr:`2788` - Add ``Choice.get_invalid_choice_message`` method for customizing the invalid choice message. :issue:`2621` :pr:`2622` - If help is shown because ``no_args_is_help`` is enabled (defaults to ``True`` for groups, ``False`` for commands), the exit code is 2 instead of 0. :issue:`1489` :pr:`1489` - Contexts created during shell completion are closed properly, fixing a ``ResourceWarning`` when using ``click.File``. :issue:`2644` :pr:`2800` :pr:`2767` - ``click.edit(filename)`` now supports passing an iterable of filenames in case the editor supports editing multiple files at once. Its return type is now also typed: ``AnyStr`` if ``text`` is passed, otherwise ``None``. :issue:`2067` :pr:`2068` - Specialized typing of ``progressbar(length=...)`` as ``ProgressBar[int]``. :pr:`2630` - Improve ``echo_via_pager`` behaviour in face of errors. :issue:`2674` - Terminate the pager in case a generator passed to ``echo_via_pager`` raises an exception. - Ensure to always close the pipe to the pager process and wait for it to terminate. - ``echo_via_pager`` will not ignore ``KeyboardInterrupt`` anymore. This allows the user to search for future output of the generator when using less and then aborting the program using ctrl-c. - ``deprecated: bool | str`` can now be used on options and arguments. This previously was only available for ``Command``. The message can now also be customised by using a ``str`` instead of a ``bool``. :issue:`2263` :pr:`2271` - ``Command.deprecated`` formatting in ``--help`` changed from ``(Deprecated) help`` to ``help (DEPRECATED)``. - Parameters cannot be required nor prompted or an error is raised. - A warning will be printed when something deprecated is used. - Add a ``catch_exceptions`` parameter to ``CliRunner``. If ``catch_exceptions`` is not passed to ``CliRunner.invoke``, the value from ``CliRunner`` is used. :issue:`2817` :pr:`2818` - ``Option.flag_value`` will no longer have a default value set based on ``Option.default`` if ``Option.is_flag`` is ``False``. This results in ``Option.default`` not needing to implement `__bool__`. :pr:`2829` - Incorrect ``click.edit`` typing has been corrected. :pr:`2804` - ``Choice`` is now generic and supports any iterable value. This allows you to use enums and other non-``str`` values. :pr:`2796` :issue:`605` - Fix setup of help option's defaults when using a custom class on its decorator. Removes ``HelpOption``. :issue:`2832` :pr:`2840` Version 8.1.8 ------------- Released 2024-12-19 - Fix an issue with type hints for ``click.open_file()``. :issue:`2717` - Fix issue where error message for invalid ``click.Path`` displays on multiple lines. :issue:`2697` - Fixed issue that prevented a default value of ``""`` from being displayed in the help for an option. :issue:`2500` - The test runner handles stripping color consistently on Windows. :issue:`2705` - Show correct value for flag default when using ``default_map``. :issue:`2632` - Fix ``click.echo(color=...)`` passing ``color`` to coloroma so it can be forced on Windows. :issue:`2606`. - More robust bash version check, fixing problem on Windows with git-bash. :issue:`2638` - Cache the help option generated by the ``help_option_names`` setting to respect its eagerness. :pr:`2811` - Replace uses of ``os.system`` with ``subprocess.Popen``. :issue:`1476` - Exceptions generated during a command will use the context's ``color`` setting when being displayed. :issue:`2193` - Error message when defining option with invalid name is more descriptive. :issue:`2452` - Refactor code generating default ``--help`` option to deduplicate code. :pr:`2563` - Test ``CLIRunner`` resets patched ``_compat.should_strip_ansi``. :issue:`2732` Version 8.1.7 ------------- Released 2023-08-17 - Fix issue with regex flags in shell completion. :issue:`2581` - Bash version detection issues a warning instead of an error. :issue:`2574` - Fix issue with completion script for Fish shell. :issue:`2567` Version 8.1.6 ------------- Released 2023-07-18 - Fix an issue with type hints for ``@click.group()``. :issue:`2558` Version 8.1.5 ------------- Released 2023-07-13 - Fix an issue with type hints for ``@click.command()``, ``@click.option()``, and other decorators. Introduce typing tests. :issue:`2558` Version 8.1.4 ------------- Released 2023-07-06 - Replace all ``typing.Dict`` occurrences to ``typing.MutableMapping`` for parameter hints. :issue:`2255` - Improve type hinting for decorators and give all generic types parameters. :issue:`2398` - Fix return value and type signature of `shell_completion.add_completion_class` function. :pr:`2421` - Bash version detection doesn't fail on Windows. :issue:`2461` - Completion works if there is a dot (``.``) in the program name. :issue:`2166` - Improve type annotations for pyright type checker. :issue:`2268` - Improve responsiveness of ``click.clear()``. :issue:`2284` - Improve command name detection when using Shiv or PEX. :issue:`2332` - Avoid showing empty lines if command help text is empty. :issue:`2368` - ZSH completion script works when loaded from ``fpath``. :issue:`2344`. - ``EOFError`` and ``KeyboardInterrupt`` tracebacks are not suppressed when ``standalone_mode`` is disabled. :issue:`2380` - ``@group.command`` does not fail if the group was created with a custom ``command_class``. :issue:`2416` - ``multiple=True`` is allowed for flag options again and does not require setting ``default=()``. :issue:`2246, 2292, 2295` - Make the decorators returned by ``@argument()`` and ``@option()`` reusable when the ``cls`` parameter is used. :issue:`2294` - Don't fail when writing filenames to streams with strict errors. Replace invalid bytes with the replacement character (``�``). :issue:`2395` - Remove unnecessary attempt to detect MSYS2 environment. :issue:`2355` - Remove outdated and unnecessary detection of App Engine environment. :pr:`2554` - ``echo()`` does not fail when no streams are attached, such as with ``pythonw`` on Windows. :issue:`2415` - Argument with ``expose_value=False`` do not cause completion to fail. :issue:`2336` Version 8.1.3 ------------- Released 2022-04-28 - Use verbose form of ``typing.Callable`` for ``@command`` and ``@group``. :issue:`2255` - Show error when attempting to create an option with ``multiple=True, is_flag=True``. Use ``count`` instead. :issue:`2246` Version 8.1.2 ------------- Released 2022-03-31 - Fix error message for readable path check that was mixed up with the executable check. :pr:`2236` - Restore parameter order for ``Path``, placing the ``executable`` parameter at the end. It is recommended to use keyword arguments instead of positional arguments. :issue:`2235` Version 8.1.1 ------------- Released 2022-03-30 - Fix an issue with decorator typing that caused type checking to report that a command was not callable. :issue:`2227` Version 8.1.0 ------------- Released 2022-03-28 - Drop support for Python 3.6. :pr:`2129` - Remove previously deprecated code. :pr:`2130` - ``Group.resultcallback`` is renamed to ``result_callback``. - ``autocompletion`` parameter to ``Command`` is renamed to ``shell_complete``. - ``get_terminal_size`` is removed, use ``shutil.get_terminal_size`` instead. - ``get_os_args`` is removed, use ``sys.argv[1:]`` instead. - Rely on :pep:`538` and :pep:`540` to handle selecting UTF-8 encoding instead of ASCII. Click's locale encoding detection is removed. :issue:`2198` - Single options boolean flags with ``show_default=True`` only show the default if it is ``True``. :issue:`1971` - The ``command`` and ``group`` decorators can be applied with or without parentheses. :issue:`1359` - The ``Path`` type can check whether the target is executable. :issue:`1961` - ``Command.show_default`` overrides ``Context.show_default``, instead of the other way around. :issue:`1963` - Parameter decorators and ``@group`` handles ``cls=None`` the same as not passing ``cls``. ``@option`` handles ``help=None`` the same as not passing ``help``. :issue:`#1959` - A flag option with ``required=True`` requires that the flag is passed instead of choosing the implicit default value. :issue:`1978` - Indentation in help text passed to ``Option`` and ``Command`` is cleaned the same as using the ``@option`` and ``@command`` decorators does. A command's ``epilog`` and ``short_help`` are also processed. :issue:`1985` - Store unprocessed ``Command.help``, ``epilog`` and ``short_help`` strings. Processing is only done when formatting help text for output. :issue:`2149` - Allow empty str input for ``prompt()`` when ``confirmation_prompt=True`` and ``default=""``. :issue:`2157` - Windows glob pattern expansion doesn't fail if a value is an invalid pattern. :issue:`2195` - It's possible to pass a list of ``params`` to ``@command``. Any params defined with decorators are appended to the passed params. :issue:`2131`. - ``@command`` decorator is annotated as returning the correct type if a ``cls`` argument is used. :issue:`2211` - A ``Group`` with ``invoke_without_command=True`` and ``chain=False`` will invoke its result callback with the group function's return value. :issue:`2124` - ``to_info_dict`` will not fail if a ``ParamType`` doesn't define a ``name``. :issue:`2168` - Shell completion prioritizes option values with option prefixes over new options. :issue:`2040` - Options that get an environment variable value using ``autoenvvar_prefix`` treat an empty value as ``None``, consistent with a direct ``envvar``. :issue:`2146` Version 8.0.4 ------------- Released 2022-02-18 - ``open_file`` recognizes ``Path("-")`` as a standard stream, the same as the string ``"-"``. :issue:`2106` - The ``option`` and ``argument`` decorators preserve the type annotation of the decorated function. :pr:`2155` - A callable default value can customize its help text by overriding ``__str__`` instead of always showing ``(dynamic)``. :issue:`2099` - Fix a typo in the Bash completion script that affected file and directory completion. If this script was generated by a previous version, it should be regenerated. :issue:`2163` - Fix typing for ``echo`` and ``secho`` file argument. :issue:`2174, 2185` Version 8.0.3 ------------- Released 2021-10-10 - Fix issue with ``Path(resolve_path=True)`` type creating invalid paths. :issue:`2088` - Importing ``readline`` does not cause the ``confirm()`` prompt to disappear when pressing backspace. :issue:`2092` - Any default values injected by ``invoke()`` are cast to the corresponding parameter's type. :issue:`2089, 2090` Version 8.0.2 ------------- Released 2021-10-08 - ``is_bool_flag`` is not set to ``True`` if ``is_flag`` is ``False``. :issue:`1925` - Bash version detection is locale independent. :issue:`1940` - Empty ``default`` value is not shown for ``multiple=True``. :issue:`1969` - Fix shell completion for arguments that start with a forward slash such as absolute file paths. :issue:`1929` - ``Path`` type with ``resolve_path=True`` resolves relative symlinks to be relative to the containing directory. :issue:`1921` - Completion does not skip Python's resource cleanup when exiting, avoiding some unexpected warning output. :issue:`1738, 2017` - Fix type annotation for ``type`` argument in ``prompt`` function. :issue:`2062` - Fix overline and italic styles, which were incorrectly added when adding underline. :pr:`2058` - An option with ``count=True`` will not show "[x>=0]" in help text. :issue:`2072` - Default values are not cast to the parameter type twice during processing. :issue:`2085` - Options with ``multiple`` and ``flag_value`` use the flag value instead of leaving an internal placeholder. :issue:`2001` Version 8.0.1 ------------- Released 2021-05-19 - Mark top-level names as exported so type checking understand imports in user projects. :issue:`1879` - Annotate ``Context.obj`` as ``Any`` so type checking allows all operations on the arbitrary object. :issue:`1885` - Fix some types that weren't available in Python 3.6.0. :issue:`1882` - Fix type checking for iterating over ``ProgressBar`` object. :issue:`1892` - The ``importlib_metadata`` backport package is installed on Python < 3.8. :issue:`1889` - Arguments with ``nargs=-1`` only use env var value if no command line values are given. :issue:`1903` - Flag options guess their type from ``flag_value`` if given, like regular options do from ``default``. :issue:`1886` - Added documentation that custom parameter types may be passed already valid values in addition to strings. :issue:`1898` - Resolving commands returns the name that was given, not ``command.name``, fixing an unintended change to help text and ``default_map`` lookups. When using patterns like ``AliasedGroup``, override ``resolve_command`` to change the name that is returned if needed. :issue:`1895` - If a default value is invalid, it does not prevent showing help text. :issue:`1889` - Pass ``windows_expand_args=False`` when calling the main command to disable pattern expansion on Windows. There is no way to escape patterns in CMD, so if the program needs to pass them on as-is then expansion must be disabled. :issue:`1901` Version 8.0.0 ------------- Released 2021-05-11 - Drop support for Python 2 and 3.5. - Colorama is always installed on Windows in order to provide style and color support. :pr:`1784` - Adds a repr to Command, showing the command name for friendlier debugging. :issue:`1267`, :pr:`1295` - Add support for distinguishing the source of a command line parameter. :issue:`1264`, :pr:`1329` - Add an optional parameter to ``ProgressBar.update`` to set the ``current_item``. :issue:`1226`, :pr:`1332` - ``version_option`` uses ``importlib.metadata`` (or the ``importlib_metadata`` backport) instead of ``pkg_resources``. The version is detected based on the package name, not the entry point name. The Python package name must match the installed package name, or be passed with ``package_name=``. :issue:`1582` - If validation fails for a prompt with ``hide_input=True``, the value is not shown in the error message. :issue:`1460` - An ``IntRange`` or ``FloatRange`` option shows the accepted range in its help text. :issue:`1525`, :pr:`1303` - ``IntRange`` and ``FloatRange`` bounds can be open (``<``) instead of closed (``<=``) by setting ``min_open`` and ``max_open``. Error messages have changed to reflect this. :issue:`1100` - An option defined with duplicate flag names (``"--foo/--foo"``) raises a ``ValueError``. :issue:`1465` - ``echo()`` will not fail when using pytest's ``capsys`` fixture on Windows. :issue:`1590` - Resolving commands returns the canonical command name instead of the matched name. This makes behavior such as help text and ``Context.invoked_subcommand`` consistent when using patterns like ``AliasedGroup``. :issue:`1422` - The ``BOOL`` type accepts the values "on" and "off". :issue:`1629` - A ``Group`` with ``invoke_without_command=True`` will always invoke its result callback. :issue:`1178` - ``nargs == -1`` and ``nargs > 1`` is parsed and validated for values from environment variables and defaults. :issue:`729` - Detect the program name when executing a module or package with ``python -m name``. :issue:`1603` - Include required parent arguments in help synopsis of subcommands. :issue:`1475` - Help for boolean flags with ``show_default=True`` shows the flag name instead of ``True`` or ``False``. :issue:`1538` - Non-string objects passed to ``style()`` and ``secho()`` will be converted to string. :pr:`1146` - ``edit(require_save=True)`` will detect saves for editors that exit very fast on filesystems with 1 second resolution. :pr:`1050` - New class attributes make it easier to use custom core objects throughout an entire application. :pr:`938` - ``Command.context_class`` controls the context created when running the command. - ``Context.invoke`` creates new contexts of the same type, so a custom type will persist to invoked subcommands. - ``Context.formatter_class`` controls the formatter used to generate help and usage. - ``Group.command_class`` changes the default type for subcommands with ``@group.command()``. - ``Group.group_class`` changes the default type for subgroups with ``@group.group()``. Setting it to ``type`` will create subgroups of the same type as the group itself. - Core objects use ``super()`` consistently for better support of subclassing. - Use ``Context.with_resource()`` to manage resources that would normally be used in a ``with`` statement, allowing them to be used across subcommands and callbacks, then cleaned up when the context ends. :pr:`1191` - The result object returned by the test runner's ``invoke()`` method has a ``return_value`` attribute with the value returned by the invoked command. :pr:`1312` - Required arguments with the ``Choice`` type show the choices in curly braces to indicate that one is required (``{a|b|c}``). :issue:`1272` - If only a name is passed to ``option()``, Click suggests renaming it to ``--name``. :pr:`1355` - A context's ``show_default`` parameter defaults to the value from the parent context. :issue:`1565` - ``click.style()`` can output 256 and RGB color codes. Most modern terminals support these codes. :pr:`1429` - When using ``CliRunner.invoke()``, the replaced ``stdin`` file has ``name`` and ``mode`` attributes. This lets ``File`` options with the ``-`` value match non-testing behavior. :issue:`1064` - When creating a ``Group``, allow passing a list of commands instead of a dict. :issue:`1339` - When a long option name isn't valid, use ``difflib`` to make better suggestions for possible corrections. :issue:`1446` - Core objects have a ``to_info_dict()`` method. This gathers information about the object's structure that could be useful for a tool generating user-facing documentation. To get the structure of an entire CLI, use ``Context(cli).to_info_dict()``. :issue:`461` - Redesign the shell completion system. :issue:`1484`, :pr:`1622` - Support Bash >= 4.4, Zsh, and Fish, with the ability for extensions to add support for other shells. - Allow commands, groups, parameters, and types to override their completions suggestions. - Groups complete the names commands were registered with, which can differ from the name they were created with. - The ``autocompletion`` parameter for options and arguments is renamed to ``shell_complete``. The function must take ``ctx, param, incomplete``, must do matching rather than return all values, and must return a list of strings or a list of ``CompletionItem``. The old name and behavior is deprecated and will be removed in 8.1. - The env var values used to start completion have changed order. The shell now comes first, such as ``{shell}_source`` rather than ``source_{shell}``, and is always required. - Completion correctly parses command line strings with incomplete quoting or escape sequences. :issue:`1708` - Extra context settings (``obj=...``, etc.) are passed on to the completion system. :issue:`942` - Include ``--help`` option in completion. :pr:`1504` - ``ParameterSource`` is an ``enum.Enum`` subclass. :issue:`1530` - Boolean and UUID types strip surrounding space before converting. :issue:`1605` - Adjusted error message from parameter type validation to be more consistent. Quotes are used to distinguish the invalid value. :issue:`1605` - The default value for a parameter with ``nargs`` > 1 and ``multiple=True`` must be a list of tuples. :issue:`1649` - When getting the value for a parameter, the default is tried in the same section as other sources to ensure consistent processing. :issue:`1649` - All parameter types accept a value that is already the correct type. :issue:`1649` - For shell completion, an argument is considered incomplete if its value did not come from the command line args. :issue:`1649` - Added ``ParameterSource.PROMPT`` to track parameter values that were prompted for. :issue:`1649` - Options with ``nargs`` > 1 no longer raise an error if a default is not given. Parameters with ``nargs`` > 1 default to ``None``, and parameters with ``multiple=True`` or ``nargs=-1`` default to an empty tuple. :issue:`472` - Handle empty env vars as though the option were not passed. This extends the change introduced in 7.1 to be consistent in more cases. :issue:`1285` - ``Parameter.get_default()`` checks ``Context.default_map`` to handle overrides consistently in help text, ``invoke()``, and prompts. :issue:`1548` - Add ``prompt_required`` param to ``Option``. When set to ``False``, the user will only be prompted for an input if no value was passed. :issue:`736` - Providing the value to an option can be made optional through ``is_flag=False``, and the value can instead be prompted for or passed in as a default value. :issue:`549, 736, 764, 921, 1015, 1618` - Fix formatting when ``Command.options_metavar`` is empty. :pr:`1551` - Revert adding space between option help text that wraps. :issue:`1831` - The default value passed to ``prompt`` will be cast to the correct type like an input value would be. :pr:`1517` - Automatically generated short help messages will stop at the first ending of a phrase or double linebreak. :issue:`1082` - Skip progress bar render steps for efficiency with very fast iterators by setting ``update_min_steps``. :issue:`676` - Respect ``case_sensitive=False`` when doing shell completion for ``Choice`` :issue:`1692` - Use ``mkstemp()`` instead of ``mktemp()`` in pager implementation. :issue:`1752` - If ``Option.show_default`` is a string, it is displayed even if ``default`` is ``None``. :issue:`1732` - ``click.get_terminal_size()`` is deprecated and will be removed in 8.1. Use :func:`shutil.get_terminal_size` instead. :issue:`1736` - Control the location of the temporary directory created by ``CLIRunner.isolated_filesystem`` by passing ``temp_dir``. A custom directory will not be removed automatically. :issue:`395` - ``click.confirm()`` will prompt until input is given if called with ``default=None``. :issue:`1381` - Option prompts validate the value with the option's callback in addition to its type. :issue:`457` - ``confirmation_prompt`` can be set to a custom string. :issue:`723` - Allow styled output in Jupyter on Windows. :issue:`1271` - ``style()`` supports the ``strikethrough``, ``italic``, and ``overline`` styles. :issue:`805, 1821` - Multiline marker is removed from short help text. :issue:`1597` - Restore progress bar behavior of echoing only the label if the file is not a TTY. :issue:`1138` - Progress bar output is shown even if execution time is less than 0.5 seconds. :issue:`1648` - Progress bar ``item_show_func`` shows the current item, not the previous item. :issue:`1353` - The ``Path`` param type can be passed ``path_type=pathlib.Path`` to return a path object instead of a string. :issue:`405` - ``TypeError`` is raised when parameter with ``multiple=True`` or ``nargs > 1`` has non-iterable default. :issue:`1749` - Add a ``pass_meta_key`` decorator for passing a key from ``Context.meta``. This is useful for extensions using ``meta`` to store information. :issue:`1739` - ``Path`` ``resolve_path`` resolves symlinks on Windows Python < 3.8. :issue:`1813` - Command deprecation notice appears at the start of the help text, as well as in the short help. The notice is not in all caps. :issue:`1791` - When taking arguments from ``sys.argv`` on Windows, glob patterns, user dir, and env vars are expanded. :issue:`1096` - Marked messages shown by the CLI with ``gettext()`` to allow applications to translate Click's built-in strings. :issue:`303` - Writing invalid characters to ``stderr`` when using the test runner does not raise a ``UnicodeEncodeError``. :issue:`848` - Fix an issue where ``readline`` would clear the entire ``prompt()`` line instead of only the input when pressing backspace. :issue:`665` - Add all kwargs passed to ``Context.invoke()`` to ``ctx.params``. Fixes an inconsistency when nesting ``Context.forward()`` calls. :issue:`1568` - The ``MultiCommand.resultcallback`` decorator is renamed to ``result_callback``. The old name is deprecated. :issue:`1160` - Fix issues with ``CliRunner`` output when using ``echo_stdin=True``. :issue:`1101` - Fix a bug of ``click.utils.make_default_short_help`` for which the returned string could be as long as ``max_width + 3``. :issue:`1849` - When defining a parameter, ``default`` is validated with ``multiple`` and ``nargs``. More validation is done for values being processed as well. :issue:`1806` - ``HelpFormatter.write_text`` uses the full line width when wrapping text. :issue:`1871` Version 7.1.2 ------------- Released 2020-04-27 - Revert applying shell quoting to commands for ``echo_with_pager`` and ``edit``. This was intended to allows spaces in commands, but caused issues if the string was actually a command and arguments, or on Windows. Instead, the string must be quoted manually as it should appear on the command line. :issue:`1514` Version 7.1.1 ------------- Released 2020-03-09 - Fix ``ClickException`` output going to stdout instead of stderr. :issue:`1495` Version 7.1 ----------- Released 2020-03-09 - Fix PyPI package name, "click" is lowercase again. - Fix link in ``unicode_literals`` error message. :pr:`1151` - Add support for colored output on UNIX Jupyter notebooks. :issue:`1185` - Operations that strip ANSI controls will strip the cursor hide/show sequences. :issue:`1216` - Remove unused compat shim for ``bytes``. :pr:`1195` - Expand testing around termui, especially getchar on Windows. :issue:`1116` - Fix output on Windows Python 2.7 built with MSVC 14. :pr:`1342` - Fix ``OSError`` when running in MSYS2. :issue:`1338` - Fix ``OSError`` when redirecting to ``NUL`` stream on Windows. :issue:`1065` - Fix memory leak when parsing Unicode arguments on Windows. :issue:`1136` - Fix error in new AppEngine environments. :issue:`1462` - Always return one of the passed choices for ``click.Choice`` :issue:`1277`, :pr:`1318` - Add ``no_args_is_help`` option to ``click.Command``, defaults to False :pr:`1167` - Add ``show_default`` parameter to ``Context`` to enable showing defaults globally. :issue:`1018` - Handle ``env MYPATH=''`` as though the option were not passed. :issue:`1196` - It is once again possible to call ``next(bar)`` on an active progress bar instance. :issue:`1125` - ``open_file`` with ``atomic=True`` retains permissions of existing files and respects the current umask for new files. :issue:`1376` - When using the test ``CliRunner`` with ``mix_stderr=False``, if ``result.stderr`` is empty it will not raise a ``ValueError``. :issue:`1193` - Remove the unused ``mix_stderr`` parameter from ``CliRunner.invoke``. :issue:`1435` - Fix ``TypeError`` raised when using bool flags and specifying ``type=bool``. :issue:`1287` - Newlines in option help text are replaced with spaces before re-wrapping to avoid uneven line breaks. :issue:`834` - ``MissingParameter`` exceptions are printable in the Python interpreter. :issue:`1139` - Fix how default values for file-type options are shown during prompts. :issue:`914` - Fix environment variable automatic generation for commands containing ``-``. :issue:`1253` - Option help text replaces newlines with spaces when rewrapping, but preserves paragraph breaks, fixing multiline formatting. :issue:`834, 1066, 1397` - Option help text that is wrapped adds an extra newline at the end to distinguish it from the next option. :issue:`1075` - Consider ``sensible-editor`` when determining the editor to use for ``click.edit()``. :pr:`1469` - Arguments to system calls such as the executable path passed to ``click.edit`` can contains spaces. :pr:`1470` - Add ZSH completion autoloading and error handling. :issue:`1348` - Add a repr to ``Command``, ``Group``, ``Option``, and ``Argument``, showing the name for friendlier debugging. :issue:`1267` - Completion doesn't consider option names if a value starts with ``-`` after the ``--`` separator. :issue:`1247` - ZSH completion escapes special characters in values. :pr:`1418` - Add completion support for Fish shell. :pr:`1423` - Decoding bytes option values falls back to UTF-8 in more cases. :pr:`1468` - Make the warning about old 2-arg parameter callbacks a deprecation warning, to be removed in 8.0. This has been a warning since Click 2.0. :pr:`1492` - Adjust error messages to standardize the types of quotes used so they match error messages from Python. Version 7.0 ----------- Released 2018-09-25 - Drop support for Python 2.6 and 3.3. :pr:`967, 976` - Wrap ``click.Choice``'s missing message. :issue:`202`, :pr:`1000` - Add native ZSH autocompletion support. :issue:`323`, :pr:`865` - Document that ANSI color info isn't parsed from bytearrays in Python 2. :issue:`334` - Document byte-stripping behavior of ``CliRunner``. :issue:`334`, :pr:`1010` - Usage errors now hint at the ``--help`` option. :issue:`393`, :pr:`557` - Implement streaming pager. :issue:`409`, :pr:`889` - Extract bar formatting to its own method. :pr:`414` - Add ``DateTime`` type for converting input in given date time formats. :pr:`423` - ``secho``'s first argument can now be ``None``, like in ``echo``. :pr:`424` - Fixes a ``ZeroDivisionError`` in ``ProgressBar.make_step``, when the arg passed to the first call of ``ProgressBar.update`` is 0. :issue:`447`, :pr:`1012` - Show progressbar only if total execution time is visible. :pr:`487` - Added the ability to hide commands and options from help. :pr:`500` - Document that options can be ``required=True``. :issue:`514`, :pr:`1022` - Non-standalone calls to ``Context.exit`` return the exit code, rather than calling ``sys.exit``. :issue:`667`, :pr:`533, 1098` - ``click.getchar()`` returns Unicode in Python 3 on Windows, consistent with other platforms. :issue:`537, 821, 822, 1088`, :pr:`1108` - Added ``FloatRange`` type. :pr:`538, 553` - Added support for bash completion of ``type=click.Choice`` for ``Options`` and ``Arguments``. :issue:`535`, :pr:`681` - Only allow one positional arg for ``Argument`` parameter declaration. :issue:`568, 574`, :pr:`1014` - Add ``case_sensitive=False`` as an option to Choice. :issue:`569` - ``click.getchar()`` correctly raises ``KeyboardInterrupt`` on "^C" and ``EOFError`` on "^D" on Linux. :issue:`583`, :pr:`1115` - Fix encoding issue with ``click.getchar(echo=True)`` on Linux. :pr:`1115` - ``param_hint`` in errors now derived from param itself. :issue:`598, 704`, :pr:`709` - Add a test that ensures that when an argument is formatted into a usage error, its metavar is used, not its name. :pr:`612` - Allow setting ``prog_name`` as extra in ``CliRunner.invoke``. :issue:`616`, :pr:`999` - Help text taken from docstrings truncates at the ``\f`` form feed character, useful for hiding Sphinx-style parameter documentation. :pr:`629, 1091` - ``launch`` now works properly under Cygwin. :pr:`650` - Update progress after iteration. :issue:`651`, :pr:`706` - ``CliRunner.invoke`` now may receive ``args`` as a string representing a Unix shell command. :pr:`664` - Make ``Argument.make_metavar()`` default to type metavar. :pr:`675` - Add documentation for ``ignore_unknown_options``. :pr:`684` - Add bright colors support for ``click.style`` and fix the reset option for parameters ``fg`` and ``bg``. :issue:`703`, :pr:`809` - Add ``show_envvar`` for showing environment variables in help. :pr:`710` - Avoid ``BrokenPipeError`` during interpreter shutdown when stdout or stderr is a closed pipe. :issue:`712`, :pr:`1106` - Document customizing option names. :issue:`725`, :pr:`1016` - Disable ``sys._getframes()`` on Python interpreters that don't support it. :pr:`728` - Fix bug in test runner when calling ``sys.exit`` with ``None``. :pr:`739` - Clarify documentation on command line options. :issue:`741`, :pr:`1003` - Fix crash on Windows console. :issue:`744` - Fix bug that caused bash completion to give improper completions on chained commands. :issue:`754`, :pr:`774` - Added support for dynamic bash completion from a user-supplied callback. :pr:`755` - Added support for bash completions containing spaces. :pr:`773` - Allow autocompletion function to determine whether or not to return completions that start with the incomplete argument. :issue:`790`, :pr:`806` - Fix option naming routine to match documentation and be deterministic. :issue:`793`, :pr:`794` - Fix path validation bug. :issue:`795`, :pr:`1020` - Add test and documentation for ``Option`` naming: functionality. :pr:`799` - Update doc to match arg name for ``path_type``. :pr:`801` - Raw strings added so correct escaping occurs. :pr:`807` - Fix 16k character limit of ``click.echo`` on Windows. :issue:`816`, :pr:`819` - Overcome 64k character limit when writing to binary stream on Windows 7. :issue:`825`, :pr:`830` - Add bool conversion for "t" and "f". :pr:`842` - ``NoSuchOption`` errors take ``ctx`` so that ``--help`` hint gets printed in error output. :pr:`860` - Fixed the behavior of Click error messages with regards to Unicode on 2.x and 3.x. Message is now always Unicode and the str and Unicode special methods work as you expect on that platform. :issue:`862` - Progress bar now uses stderr by default. :pr:`863` - Add support for auto-completion documentation. :issue:`866`, :pr:`869` - Allow ``CliRunner`` to separate stdout and stderr. :pr:`868` - Fix variable precedence. :issue:`873`, :pr:`874` - Fix invalid escape sequences. :pr:`877` - Fix ``ResourceWarning`` that occurs during some tests. :pr:`878` - When detecting a misconfigured locale, don't fail if the ``locale`` command fails. :pr:`880` - Add ``case_sensitive=False`` as an option to ``Choice`` types. :pr:`887` - Force stdout/stderr writable. This works around issues with badly patched standard streams like those from Jupyter. :pr:`918` - Fix completion of subcommand options after last argument :issue:`919`, :pr:`930` - ``_AtomicFile`` now uses the ``realpath`` of the original filename so that changing the working directory does not affect it. :pr:`920` - Fix incorrect completions when defaults are present :issue:`925`, :pr:`930` - Add copy option attrs so that custom classes can be re-used. :issue:`926`, :pr:`994` - "x" and "a" file modes now use stdout when file is ``"-"``. :pr:`929` - Fix missing comma in ``__all__`` list. :pr:`935` - Clarify how parameters are named. :issue:`949`, :pr:`1009` - Stdout is now automatically set to non blocking. :pr:`954` - Do not set options twice. :pr:`962` - Move ``fcntl`` import. :pr:`965` - Fix Google App Engine ``ImportError``. :pr:`995` - Better handling of help text for dynamic default option values. :pr:`996` - Fix ``get_winter_size()`` so it correctly returns ``(0,0)``. :pr:`997` - Add test case checking for custom param type. :pr:`1001` - Allow short width to address cmd formatting. :pr:`1002` - Add details about Python version support. :pr:`1004` - Added deprecation flag to commands. :pr:`1005` - Fixed issues where ``fd`` was undefined. :pr:`1007` - Fix formatting for short help. :pr:`1008` - Document how ``auto_envvar_prefix`` works with command groups. :pr:`1011` - Don't add newlines by default for progress bars. :pr:`1013` - Use Python sorting order for ZSH completions. :issue:`1047`, :pr:`1059` - Document that parameter names are converted to lowercase by default. :pr:`1055` - Subcommands that are named by the function now automatically have the underscore replaced with a dash. If you register a function named ``my_command`` it becomes ``my-command`` in the command line interface. - Hide hidden commands and options from completion. :issue:`1058`, :pr:`1061` - Fix absolute import blocking Click from being vendored into a project on Windows. :issue:`1068`, :pr:`1069` - Fix issue where a lowercase ``auto_envvar_prefix`` would not be converted to uppercase. :pr:`1105` Version 6.7 ----------- Released 2017-01-06 - Make ``click.progressbar`` work with ``codecs.open`` files. :pr:`637` - Fix bug in bash completion with nested subcommands. :pr:`639` - Fix test runner not saving caller env correctly. :pr:`644` - Fix handling of SIGPIPE. :pr:`62` - Deal with broken Windows environments such as Google App Engine's. :issue:`711` Version 6.6 ----------- Released 2016-04-04 - Fix bug in ``click.Path`` where it would crash when passed a ``-``. :issue:`551` Version 6.4 ----------- Released 2016-03-24 - Fix bug in bash completion where click would discard one or more trailing arguments. :issue:`471` Version 6.3 ----------- Released 2016-02-22 - Fix argument checks for interpreter invoke with ``-m`` and ``-c`` on Windows. - Fixed a bug that cased locale detection to error out on Python 3. Version 6.2 ----------- Released 2015-11-27 - Correct fix for hidden progress bars. Version 6.1 ----------- Released 2015-11-27 - Resolved an issue with invisible progress bars no longer rendering. - Disable chain commands with subcommands as they were inherently broken. - Fix ``MissingParameter`` not working without parameters passed. Version 6.0 ----------- Released 2015-11-24, codename "pow pow" - Optimized the progressbar rendering to not render when it did not actually change. - Explicitly disallow ``nargs=-1`` with a set default. - The context is now closed before it's popped from the stack. - Added support for short aliases for the false flag on toggles. - Click will now attempt to aid you with debugging locale errors better by listing with the help of the OS what locales are available. - Click used to return byte strings on Python 2 in some unit-testing situations. This has been fixed to correctly return unicode strings now. - For Windows users on Python 2, Click will now handle Unicode more correctly handle Unicode coming in from the system. This also has the disappointing side effect that filenames will now be always unicode by default in the ``Path`` type which means that this can introduce small bugs for code not aware of this. - Added a ``type`` parameter to ``Path`` to force a specific string type on the value. - For users running Python on Windows the ``echo`` and ``prompt`` functions now work with full unicode functionality in the Python windows console by emulating an output stream. This also applies to getting the virtual output and input streams via ``click.get_text_stream(...)``. - Unittests now always force a certain virtual terminal width. - Added support for allowing dashes to indicate standard streams to the ``Path`` type. - Multi commands in chain mode no longer propagate arguments left over from parsing to the callbacks. It's also now disallowed through an exception when optional arguments are attached to multi commands if chain mode is enabled. - Relaxed restriction that disallowed chained commands to have other chained commands as child commands. - Arguments with positive nargs can now have defaults implemented. Previously this configuration would often result in slightly unexpected values be returned. Version 5.1 ----------- Released 2015-08-17 - Fix a bug in ``pass_obj`` that would accidentally pass the context too. Version 5.0 ----------- Released 2015-08-16, codename "tok tok" - Removed various deprecated functionality. - Atomic files now only accept the ``w`` mode. - Change the usage part of help output for very long commands to wrap their arguments onto the next line, indented by 4 spaces. - Fix a bug where return code and error messages were incorrect when using ``CliRunner``. - Added ``get_current_context``. - Added a ``meta`` dictionary to the context which is shared across the linked list of contexts to allow click utilities to place state there. - Introduced ``Context.scope``. - The ``echo`` function is now threadsafe: It calls the ``write`` method of the underlying object only once. - ``prompt(hide_input=True)`` now prints a newline on ``^C``. - Click will now warn if users are using ``unicode_literals``. - Click will now ignore the ``PAGER`` environment variable if it is empty or contains only whitespace. - The ``click-contrib`` GitHub organization was created. Version 4.1 ----------- Released 2015-07-14 - Fix a bug where error messages would include a trailing ``None`` string. - Fix a bug where Click would crash on docstrings with trailing newlines. - Support streams with encoding set to ``None`` on Python 3 by barfing with a better error. - Handle ^C in less-pager properly. - Handle return value of ``None`` from ``sys.getfilesystemencoding`` - Fix crash when writing to unicode files with ``click.echo``. - Fix type inference with multiple options. Version 4.0 ----------- Released 2015-03-31, codename "zoom zoom" - Added ``color`` parameters to lots of interfaces that directly or indirectly call into echoing. This previously was always autodetection (with the exception of the ``echo_via_pager`` function). Now you can forcefully enable or disable it, overriding the auto detection of Click. - Added an ``UNPROCESSED`` type which does not perform any type changes which simplifies text handling on 2.x / 3.x in some special advanced usecases. - Added ``NoSuchOption`` and ``BadOptionUsage`` exceptions for more generic handling of errors. - Added support for handling of unprocessed options which can be useful in situations where arguments are forwarded to underlying tools. - Added ``max_content_width`` parameter to the context which can be used to change the maximum width of help output. By default Click will not format content for more than 80 characters width. - Added support for writing prompts to stderr. - Fix a bug when showing the default for multiple arguments. - Added support for custom subclasses to ``option`` and ``argument``. - Fix bug in ``clear()`` on Windows when colorama is installed. - Reject ``nargs=-1`` for options properly. Options cannot be variadic. - Fixed an issue with bash completion not working properly for commands with non ASCII characters or dashes. - Added a way to manually update the progressbar. - Changed the formatting of missing arguments. Previously the internal argument name was shown in error messages, now the metavar is shown if passed. In case an automated metavar is selected, it's stripped of extra formatting first. Version 3.3 ----------- Released 2014-09-08 - Fixed an issue with error reporting on Python 3 for invalid forwarding of commands. Version 3.2 ----------- Released 2014-08-22 - Added missing ``err`` parameter forwarding to the ``secho`` function. - Fixed default parameters not being handled properly by the context invoke method. This is a backwards incompatible change if the function was used improperly. - Removed the ``invoked_subcommands`` attribute largely. It is not possible to provide it to work error free due to how the parsing works so this API has been deprecated. - Restored the functionality of ``invoked_subcommand`` which was broken as a regression in 3.1. Version 3.1 ----------- Released 2014-08-13 - Fixed a regression that caused contexts of subcommands to be created before the parent command was invoked which was a regression from earlier Click versions. Version 3.0 ----------- Released 2014-08-12, codename "clonk clonk" - Formatter now no longer attempts to accommodate for terminals smaller than 50 characters. If that happens it just assumes a minimal width. - Added a way to not swallow exceptions in the test system. - Added better support for colors with pagers and ways to override the autodetection. - The CLI runner's result object now has a traceback attached. - Improved automatic short help detection to work better with dots that do not terminate sentences. - When defining options without actual valid option strings now, Click will give an error message instead of silently passing. This should catch situations where users wanted to created arguments instead of options. - Restructured Click internally to support vendoring. - Added support for multi command chaining. - Added support for defaults on options with ``multiple`` and options and arguments with ``nargs != 1``. - Label passed to ``progressbar`` is no longer rendered with whitespace stripped. - Added a way to disable the standalone mode of the ``main`` method on a Click command to be able to handle errors better. - Added support for returning values from command callbacks. - Added simplifications for printing to stderr from ``echo``. - Added result callbacks for groups. - Entering a context multiple times defers the cleanup until the last exit occurs. - Added ``open_file``. Version 2.6 ----------- Released 2014-08-11 - Fixed an issue where the wrapped streams on Python 3 would be reporting incorrect values for seekable. Version 2.5 ----------- Released 2014-07-28 - Fixed a bug with text wrapping on Python 3. Version 2.4 ----------- Released 2014-07-04 - Corrected a bug in the change of the help option in 2.3. Version 2.3 ----------- Released 2014-07-03 - Fixed an incorrectly formatted help record for count options. - Add support for ansi code stripping on Windows if colorama is not available. - Restored the Click 1.0 handling of the help parameter for certain edge cases. Version 2.2 ----------- Released 2014-06-26 - Fixed tty detection on PyPy. - Fixed an issue that progress bars were not rendered when the context manager was entered. Version 2.1 ----------- Released 2014-06-14 - Fixed the :func:`launch` function on windows. - Improved the colorama support on windows to try hard to not screw up the console if the application is interrupted. - Fixed windows terminals incorrectly being reported to be 80 characters wide instead of 79 - Use colorama win32 bindings if available to get the correct dimensions of a windows terminal. - Fixed an issue with custom function types on Python 3. - Fixed an issue with unknown options being incorrectly reported in error messages. Version 2.0 ----------- Released 2014-06-06, codename "tap tap tap" - Added support for opening stdin/stdout on Windows in binary mode correctly. - Added support for atomic writes to files by going through a temporary file. - Introduced :exc:`BadParameter` which can be used to easily perform custom validation with the same error messages as in the type system. - Added :func:`progressbar`; a function to show progress bars. - Added :func:`get_app_dir`; a function to calculate the home folder for configs. - Added transparent handling for ANSI codes into the :func:`echo` function through ``colorama``. - Added :func:`clear` function. - Breaking change: parameter callbacks now get the parameter object passed as second argument. There is legacy support for old callbacks which will warn but still execute the script. - Added :func:`style`, :func:`unstyle` and :func:`secho` for ANSI styles. - Added an :func:`edit` function that invokes the default editor. - Added an :func:`launch` function that launches browsers and applications. - Nargs of -1 for arguments can now be forced to be a single item through the required flag. It defaults to not required. - Setting a default for arguments now implicitly makes it non required. - Changed "yN" / "Yn" to "y/N" and "Y/n" in confirmation prompts. - Added basic support for bash completion. - Added :func:`getchar` to fetch a single character from the terminal. - Errors now go to stderr as intended. - Fixed various issues with more exotic parameter formats like DOS/Windows style arguments. - Added :func:`pause` which works similar to the Windows ``pause`` cmd built-in but becomes an automatic noop if the application is not run through a terminal. - Added a bit of extra information about missing choice parameters. - Changed how the help function is implemented to allow global overriding of the help option. - Added support for token normalization to implement case insensitive handling. - Added support for providing defaults for context settings. Version 1.1 ----------- Released 2014-05-23 - Fixed a bug that caused text files in Python 2 to not accept native strings. Version 1.0 ----------- Released 2014-05-21 - Initial release. asyncclick-8.3.0.5-async/LICENSE.txt000066400000000000000000000027031507140761400167550ustar00rootroot00000000000000Copyright 2014 Pallets Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. asyncclick-8.3.0.5-async/Makefile000066400000000000000000000003611507140761400165700ustar00rootroot00000000000000#!/usr/bin/make -f PACKAGE=asyncclick ifneq ($(wildcard /usr/share/sourcemgr/make/py),) include /usr/share/sourcemgr/make/py # available via http://github.com/smurfix/sourcemgr else %: @echo "Please use 'python setup.py'." @exit 1 endif asyncclick-8.3.0.5-async/README.md000066400000000000000000000076051507140761400164170ustar00rootroot00000000000000# $ asyncclick_ Asyncclick is a fork of Click (described below) that works with trio or asyncio. AsyncClick allows you to seamlessly use async command and subcommand handlers.
# Click Click is a Python package for creating beautiful command line interfaces in a composable way with as little code as necessary. It's the "Command Line Interface Creation Kit". It's highly configurable but comes with sensible defaults out of the box. It aims to make the process of writing command line tools quick and fun while also preventing any frustration caused by the inability to implement an intended CLI API. Click in three points: - Arbitrary nesting of commands - Automatic help page generation - Supports lazy loading of subcommands at runtime ## A Simple Example ```python import asyncclick as click import anyio @click.command() @click.option("--count", default=1, help="Number of greetings.") @click.option("--name", prompt="Your name", help="The person to greet.") async def hello(count, name): """Simple program that greets NAME for a total of COUNT times.""" for _ in range(count): click.echo(f"Hello, {name}!") await anyio.sleep(0.2) if __name__ == '__main__': hello() # alternately: anyio.run(hello.main) ``` ``` $ python hello.py --count=3 Your name: Click Hello, Click! Hello, Click! Hello, Click! ``` ## Differences to Click This async-ized version of Click is mostly backwards compatible for "normal" use: you can freely mix sync and async versions of your command handlers and callbacks. Several advanced methods, most notably :meth:`BaseCommand.main`, and :meth:`Context.invoke`, are now asynchronous. The :meth:`BaseCommand.__call__` alias now invokes the main entry point via `anyio.run`. If you already have an async main program, simply use ``await cmd.main()`` instead of ``cmd()``. :func:`asyncclick.prompt` is asyncronous and accepts a ``blocking`` parameter that switches between "doesn't affect your event loop but has unwanted effects when interrupted" (bugfix pending) and "pauses your event loop but is safe to interrupt" with Control-C". The latter is the default until we fix that bug. You cannot use Click and AsyncClick in the same program. This is not a problem in practice, as replacing ``import click`` with ``import asyncclick as click``, and ``from click import ...`` with ``from asyncclick import ...``, should be all that's required. ### Notable packages supporting asyncclick * [OpenTelemetry][opentelemetry] supports instrumenting asyncclick. [opentelemetry]: https://pypi.org/project/opentelemetry-instrumentation-asyncclick/ ## Donate The Pallets organization develops and supports Click and other popular packages. In order to grow the community of contributors and users, and allow the maintainers to devote more time to the projects, [please donate today][]. [please donate today]: https://palletsprojects.com/donate The AsyncClick fork is maintained by Matthias Urlichs . ## Contributing ### Click See our [detailed contributing documentation][contrib] for many ways to contribute, including reporting issues, requesting features, asking or answering questions, and making PRs. [contrib]: https://palletsprojects.com/contributing/ ### AsyncClick You can file async-specific issues, ideally including a corresponding fix, to the [MoaT/asyncclick][moat] repository on github. [moat]: https://github.com/M-o-a-T/asyncclick #### Testing If you find a bug, please add a testcase to prevent it from recurring. In tests, you might wonder why `runner.invoke` is not called asynchronously. The reason is that there are far too many of these calls to modify them all. Thus ``tests/conftest.py`` contains a monkeypatch that turns this call into a thread that runs this call using `anyio.run`. asyncclick-8.3.0.5-async/docs/000077500000000000000000000000001507140761400160605ustar00rootroot00000000000000asyncclick-8.3.0.5-async/docs/_static/000077500000000000000000000000001507140761400175065ustar00rootroot00000000000000asyncclick-8.3.0.5-async/docs/_static/click-icon.svg000066400000000000000000000030361507140761400222440ustar00rootroot00000000000000 asyncclick-8.3.0.5-async/docs/_static/click-logo.svg000066400000000000000000000053151507140761400222560ustar00rootroot00000000000000 asyncclick-8.3.0.5-async/docs/_static/click-name.svg000066400000000000000000000113731507140761400222370ustar00rootroot00000000000000 asyncclick-8.3.0.5-async/docs/advanced.rst000066400000000000000000000337171507140761400203720ustar00rootroot00000000000000Advanced Patterns ================= .. currentmodule:: click In addition to common functionality, Click offers some advanced features. .. contents:: :depth: 1 :local: Callbacks and Eager Options --------------------------- Sometimes, you want a parameter to completely change the execution flow. For instance, this is the case when you want to have a ``--version`` parameter that prints out the version and then exits the application. Note: an actual implementation of a ``--version`` parameter that is reusable is available in Click as :func:`click.version_option`. The code here is merely an example of how to implement such a flag. In such cases, you need two concepts: eager parameters and a callback. An eager parameter is a parameter that is handled before others, and a callback is what executes after the parameter is handled. The eagerness is necessary so that an earlier required parameter does not produce an error message. For instance, if ``--version`` was not eager and a parameter ``--foo`` was required and defined before, you would need to specify it for ``--version`` to work. For more information, see :ref:`callback-evaluation-order`. A callback is a function that is invoked with three parameters: the current :class:`Context`, the current :class:`Parameter`, and the value. The context provides some useful features such as quitting the application and gives access to other already processed parameters. Here's an example for a ``--version`` flag: .. click:example:: async def print_version(ctx, param, value): if not value or ctx.resilient_parsing: return click.echo('Version 1.0') ctx.aexit() @click.command() @click.option('--version', is_flag=True, callback=print_version, expose_value=False, is_eager=True) def hello(): click.echo('Hello World!') (Note that ``ctx.exit`` is asynchronous in asyncclick, and has thus been renamed. Alternately you can use ``sys.exit``.) The `expose_value` parameter prevents the pretty pointless ``version`` parameter from being passed to the callback. If that was not specified, a boolean would be passed to the `hello` script. The `resilient_parsing` flag is applied to the context if Click wants to parse the command line without any destructive behavior that would change the execution flow. In this case, because we would exit the program, we instead do nothing. What it looks like: .. click:run:: invoke(hello) invoke(hello, args=['--version']) Callbacks for Validation ------------------------ .. versionchanged:: 2.0 If you want to apply custom validation logic, you can do this in the parameter callbacks. These callbacks can both modify values as well as raise errors if the validation does not work. The callback runs after type conversion. It is called for all sources, including prompts. In Click 1.0, you can only raise the :exc:`UsageError` but starting with Click 2.0, you can also raise the :exc:`BadParameter` error, which has the added advantage that it will automatically format the error message to also contain the parameter name. .. click:example:: def validate_rolls(ctx, param, value): if isinstance(value, tuple): return value try: rolls, _, dice = value.partition("d") return int(dice), int(rolls) except ValueError: raise click.BadParameter("format must be 'NdM'") @click.command() @click.option( "--rolls", type=click.UNPROCESSED, callback=validate_rolls, default="1d6", prompt=True, ) def roll(rolls): sides, times = rolls click.echo(f"Rolling a {sides}-sided dice {times} time(s)") .. click:run:: invoke(roll, args=["--rolls=42"]) println() invoke(roll, args=["--rolls=2d12"]) println() invoke(roll, input=["42", "2d12"]) Parameter Modifications ----------------------- Parameters (options and arguments) are forwarded to the command callbacks as you have seen. One common way to prevent a parameter from being passed to the callback is the `expose_value` argument to a parameter which hides the parameter entirely. The way this works is that the :class:`Context` object has a :attr:`~Context.params` attribute which is a dictionary of all parameters. Whatever is in that dictionary is being passed to the callbacks. This can be used to make up additional parameters. Generally this pattern is not recommended but in some cases it can be useful. At the very least it's good to know that the system works this way. .. click:example:: import urllib def open_url(ctx, param, value): if value is not None: ctx.params['fp'] = urllib.urlopen(value) return value @click.command() @click.option('--url', callback=open_url) def cli(url, fp=None): if fp is not None: click.echo(f"{url}: {fp.code}") In this case the callback returns the URL unchanged but also passes a second ``fp`` value to the callback. What's more recommended is to pass the information in a wrapper however: .. click:example:: import urllib class URL(object): def __init__(self, url, fp): self.url = url self.fp = fp def open_url(ctx, param, value): if value is not None: return URL(value, urllib.urlopen(value)) @click.command() @click.option('--url', callback=open_url) def cli(url): if url is not None: click.echo(f"{url.url}: {url.fp.code}") Token Normalization ------------------- .. versionadded:: 2.0 Starting with Click 2.0, it's possible to provide a function that is used for normalizing tokens. Tokens are option names, choice values, or command values. This can be used to implement case insensitive options, for instance. In order to use this feature, the context needs to be passed a function that performs the normalization of the token. For instance, you could have a function that converts the token to lowercase: .. click:example:: CONTEXT_SETTINGS = dict(token_normalize_func=lambda x: x.lower()) @click.command(context_settings=CONTEXT_SETTINGS) @click.option('--name', default='Pete') def cli(name): click.echo(f"Name: {name}") And how it works on the command line: .. click:run:: invoke(cli, prog_name='cli', args=['--NAME=Pete']) Invoking Other Commands ----------------------- Sometimes, it might be interesting to invoke one command from another command. This is a pattern that is generally discouraged with Click, but possible nonetheless. For this, you can use the :func:`Context.invoke` or :func:`Context.forward` methods. They work similarly, but the difference is that :func:`Context.invoke` merely invokes another command with the arguments you provide as a caller, whereas :func:`Context.forward` fills in the arguments from the current command. Both accept the command as the first argument and everything else is passed onwards as you would expect. These methods are asynchrous. Example: .. click:example:: cli = click.Group() @cli.command() @click.option('--count', default=1) def test(count): click.echo(f'Count: {count}') @cli.command() @click.option('--count', default=1) @click.pass_context def dist(ctx, count): await ctx.forward(test) await ctx.invoke(test, count=42) And what it looks like: .. click:run:: invoke(cli, prog_name='cli', args=['dist']) .. _forwarding-unknown-options: Forwarding Unknown Options -------------------------- In some situations it is interesting to be able to accept all unknown options for further manual processing. Click can generally do that as of Click 4.0, but it has some limitations that lie in the nature of the problem. The support for this is provided through a parser flag called ``ignore_unknown_options`` which will instruct the parser to collect all unknown options and to put them to the leftover argument instead of triggering a parsing error. This can generally be activated in two different ways: 1. It can be enabled on custom :class:`Command` subclasses by changing the :attr:`~Command.ignore_unknown_options` attribute. 2. It can be enabled by changing the attribute of the same name on the context class (:attr:`Context.ignore_unknown_options`). This is best changed through the ``context_settings`` dictionary on the command. For most situations the easiest solution is the second. Once the behavior is changed something needs to pick up those leftover options (which at this point are considered arguments). For this again you have two options: 1. You can use :func:`pass_context` to get the context passed. This will only work if in addition to :attr:`~Context.ignore_unknown_options` you also set :attr:`~Context.allow_extra_args` as otherwise the command will abort with an error that there are leftover arguments. If you go with this solution, the extra arguments will be collected in :attr:`Context.args`. 2. You can attach an :func:`argument` with ``nargs`` set to `-1` which will eat up all leftover arguments. In this case it's recommended to set the `type` to :data:`UNPROCESSED` to avoid any string processing on those arguments as otherwise they are forced into unicode strings automatically which is often not what you want. In the end you end up with something like this: .. click:example:: import sys from subprocess import call @click.command(context_settings=dict( ignore_unknown_options=True, )) @click.option('-v', '--verbose', is_flag=True, help='Enables verbose mode') @click.argument('timeit_args', nargs=-1, type=click.UNPROCESSED) def cli(verbose, timeit_args): """A fake wrapper around Python's timeit.""" cmdline = ['echo', 'python', '-mtimeit'] + list(timeit_args) if verbose: click.echo(f"Invoking: {' '.join(cmdline)}") call(cmdline) And what it looks like: .. click:run:: invoke(cli, prog_name='cli', args=['--help']) println() invoke(cli, prog_name='cli', args=['-n', '100', 'a = 1; b = 2; a * b']) println() invoke(cli, prog_name='cli', args=['-v', 'a = 1; b = 2; a * b']) As you can see the verbosity flag is handled by Click, everything else ends up in the `timeit_args` variable for further processing which then for instance, allows invoking a subprocess. There are a few things that are important to know about how this ignoring of unhandled flag happens: * Unknown long options are generally ignored and not processed at all. So for instance if ``--foo=bar`` or ``--foo bar`` are passed they generally end up like that. Note that because the parser cannot know if an option will accept an argument or not, the ``bar`` part might be handled as an argument. * Unknown short options might be partially handled and reassembled if necessary. For instance in the above example there is an option called ``-v`` which enables verbose mode. If the command would be ignored with ``-va`` then the ``-v`` part would be handled by Click (as it is known) and ``-a`` would end up in the leftover parameters for further processing. * Depending on what you plan on doing you might have some success by disabling interspersed arguments (:attr:`~Context.allow_interspersed_args`) which instructs the parser to not allow arguments and options to be mixed. Depending on your situation this might improve your results. Generally though the combined handling of options and arguments from your own commands and commands from another application are discouraged and if you can avoid it, you should. It's a much better idea to have everything below a subcommand be forwarded to another application than to handle some arguments yourself. Managing Resources ------------------ It can be useful to open a resource in a group, to be made available to subcommands. Many types of resources need to be closed or otherwise cleaned up after use. The standard way to do this in Python is by using a context manager with the ``with`` statement. For example, the ``Repo`` class from :doc:`complex` might actually be defined as a context manager: .. code-block:: python class Repo: def __init__(self, home=None): self.home = os.path.abspath(home or ".") self.db = None def __enter__(self): path = os.path.join(self.home, "repo.db") self.db = open_database(path) return self def __exit__(self, exc_type, exc_value, tb): self.db.close() Ordinarily, it would be used with the ``with`` statement: .. code-block:: python with Repo() as repo: repo.db.query(...) However, a ``with`` block in a group would exit and close the database before it could be used by a subcommand. Instead, use the context's :meth:`~click.Context.with_resource` method to enter the context manager and return the resource. When the group and any subcommands finish, the context's resources are cleaned up. .. code-block:: python @click.group() @click.option("--repo-home", default=".repo") @click.pass_context def cli(ctx, repo_home): ctx.obj = ctx.with_resource(Repo(repo_home)) @cli.command() @click.pass_obj def log(obj): # obj is the repo opened in the cli group for entry in obj.db.query(...): click.echo(entry) If the resource isn't a context manager, usually it can be wrapped in one using something from :mod:`contextlib`. If that's not possible, use the context's :meth:`~click.Context.call_on_close` method to register a cleanup function. .. code-block:: python @click.group() @click.option("--name", default="repo.db") @click.pass_context def cli(ctx, repo_home): ctx.obj = db = open_db(repo_home) @ctx.call_on_close def close_db(): db.record_use() db.save() db.close() .. versionchanged:: 8.2 ``Context.call_on_close`` and context managers registered via ``Context.with_resource`` will be closed when the CLI exits. These were previously not called on exit. asyncclick-8.3.0.5-async/docs/api.rst000066400000000000000000000055741507140761400173760ustar00rootroot00000000000000API === .. module:: asyncclick This part of the documentation lists the full API reference of all public classes and functions. .. contents:: :depth: 1 :local: Decorators ---------- .. autofunction:: command .. autofunction:: group .. autofunction:: argument .. autofunction:: option .. autofunction:: password_option .. autofunction:: confirmation_option .. autofunction:: version_option .. autofunction:: help_option .. autofunction:: pass_context .. autofunction:: pass_obj .. autofunction:: make_pass_decorator .. autofunction:: asyncclick.decorators.pass_meta_key Utilities --------- .. autofunction:: echo .. autofunction:: echo_via_pager .. autofunction:: prompt .. autofunction:: confirm .. autofunction:: progressbar .. autofunction:: clear .. autofunction:: style .. autofunction:: unstyle .. autofunction:: secho .. autofunction:: edit .. autofunction:: launch .. autofunction:: getchar .. autofunction:: pause .. autofunction:: get_binary_stream .. autofunction:: get_text_stream .. autofunction:: open_file .. autofunction:: get_app_dir .. autofunction:: format_filename Commands -------- .. autoclass:: BaseCommand :members: .. autoclass:: Command :members: .. autoclass:: MultiCommand :members: .. autoclass:: Group :members: .. autoclass:: CommandCollection :members: Parameters ---------- .. autoclass:: Parameter :members: .. autoclass:: Option .. autoclass:: Argument Context ------- .. autoclass:: Context :members: .. autofunction:: get_current_context .. autoclass:: asyncclick.core.ParameterSource :members: :member-order: bysource .. _click-api-types: Types ----- .. autodata:: STRING .. autodata:: INT .. autodata:: FLOAT .. autodata:: BOOL .. autodata:: UUID .. autodata:: UNPROCESSED .. autoclass:: File .. autoclass:: Path .. autoclass:: Choice :members: .. autoclass:: IntRange .. autoclass:: FloatRange .. autoclass:: DateTime .. autoclass:: Tuple .. autoclass:: ParamType :members: Exceptions ---------- .. autoexception:: ClickException .. autoexception:: Abort .. autoexception:: UsageError .. autoexception:: BadParameter .. autoexception:: FileError .. autoexception:: NoSuchOption .. autoexception:: BadOptionUsage .. autoexception:: BadArgumentUsage Formatting ---------- .. autoclass:: HelpFormatter :members: .. autofunction:: wrap_text Parsing ------- .. autoclass:: OptionParser :members: Shell Completion ---------------- See :doc:`/shell-completion` for information about enabling and customizing Click's shell completion system. .. currentmodule:: asyncclick.shell_completion .. autoclass:: CompletionItem .. autoclass:: ShellComplete :members: :member-order: bysource .. autofunction:: add_completion_class .. _testing: Testing ------- .. currentmodule:: asyncclick.testing .. autoclass:: CliRunner :members: .. autoclass:: Result :members: asyncclick-8.3.0.5-async/docs/arguments.rst000066400000000000000000000113251507140761400206210ustar00rootroot00000000000000.. _arguments: Arguments ========= .. currentmodule:: click Arguments are: * Are positional in nature. * Similar to a limited version of :ref:`options ` that can take an arbitrary number of inputs * :ref:`Documented manually `. Useful and often used kwargs are: * ``default``: Passes a default. * ``nargs``: Sets the number of arguments. Set to -1 to take an arbitrary number. Basic Arguments --------------- A minimal :class:`click.Argument` solely takes one string argument: the name of the argument. This will assume the argument is required, has no default, and is of the type ``str``. Example: .. click:example:: @click.command() @click.argument('filename') def touch(filename: str): """Print FILENAME.""" click.echo(filename) And from the command line: .. click:run:: invoke(touch, args=['foo.txt']) An argument may be assigned a :ref:`parameter type `. If no type is provided, the type of the default value is used. If no default value is provided, the type is assumed to be :data:`STRING`. .. admonition:: Note on Required Arguments It is possible to make an argument required by setting ``required=True``. It is not recommended since we think command line tools should gracefully degrade into becoming no ops. We think this because command line tools are often invoked with wildcard inputs and they should not error out if the wildcard is empty. Multiple Arguments ----------------------------------- To set the number of argument use the ``nargs`` kwarg. It can be set to any positive integer and -1. Setting it to -1, makes the number of arguments arbitrary (which is called variadic) and can only be used once. The arguments are then packed as a tuple and passed to the function. .. click:example:: @click.command() @click.argument('src', nargs=1) @click.argument('dsts', nargs=-1) def copy(src: str, dsts: tuple[str, ...]): """Move file SRC to DST.""" for destination in dsts: click.echo(f"Copy {src} to folder {destination}") And from the command line: .. click:run:: invoke(copy, args=['foo.txt', 'usr/david/foo.txt', 'usr/mitsuko/foo.txt']) .. admonition:: Note on Handling Files This is not how you should handle files and files paths. This merely used as a simple example. See :ref:`handling-files` to learn more about how to handle files in parameters. Argument Escape Sequences --------------------------- If you want to process arguments that look like options, like a file named ``-foo.txt`` or ``--foo.txt`` , you must pass the ``--`` separator first. After you pass the ``--``, you may only pass arguments. This is a common feature for POSIX command line tools. Example usage: .. click:example:: @click.command() @click.argument('files', nargs=-1, type=click.Path()) def touch(files): """Print all FILES file names.""" for filename in files: click.echo(filename) And from the command line: .. click:run:: invoke(touch, ['--', '-foo.txt', 'bar.txt']) If you don't like the ``--`` marker, you can set ignore_unknown_options to True to avoid checking unknown options: .. click:example:: @click.command(context_settings={"ignore_unknown_options": True}) @click.argument('files', nargs=-1, type=click.Path()) def touch(files): """Print all FILES file names.""" for filename in files: click.echo(filename) And from the command line: .. click:run:: invoke(touch, ['-foo.txt', 'bar.txt']) .. _environment-variables: Environment Variables --------------------- Arguments can use environment variables. To do so, pass the name(s) of the environment variable(s) via `envvar` in ``click.argument``. Checking one environment variable: .. click:example:: @click.command() @click.argument('src', envvar='SRC', type=click.File('r')) def echo(src): """Print value of SRC environment variable.""" click.echo(src.read()) And from the command line: .. click:run:: with isolated_filesystem(): # Writing the file in the filesystem. with open('hello.txt', 'w') as f: f.write('Hello World!') invoke(echo, env={'SRC': 'hello.txt'}) Checking multiple environment variables: .. click:example:: @click.command() @click.argument('src', envvar=['SRC', 'SRC_2'], type=click.File('r')) def echo(src): """Print value of SRC environment variable.""" click.echo(src.read()) And from the command line: .. click:run:: with isolated_filesystem(): # Writing the file in the filesystem. with open('hello.txt', 'w') as f: f.write('Hello World from second variable!') invoke(echo, env={'SRC_2': 'hello.txt'}) asyncclick-8.3.0.5-async/docs/changes.rst000066400000000000000000000000551507140761400202220ustar00rootroot00000000000000Changes ======= .. include:: ../CHANGES.rst asyncclick-8.3.0.5-async/docs/click-concepts.rst000066400000000000000000000055271507140761400215240ustar00rootroot00000000000000Click Concepts ================ This section covers concepts about Click's design. .. contents:: :depth: 1 :local: .. _callback-evaluation-order: Callback Evaluation Order ------------------------- Click works a bit differently than some other command line parsers in that it attempts to reconcile the order of arguments as defined by the programmer with the order of arguments as defined by the user before invoking any callbacks. This is an important concept to understand when porting complex patterns to Click from optparse or other systems. A parameter callback invocation in optparse happens as part of the parsing step, whereas a callback invocation in Click happens after the parsing. The main difference is that in optparse, callbacks are invoked with the raw value as it happens, whereas a callback in Click is invoked after the value has been fully converted. Generally, the order of invocation is driven by the order in which the user provides the arguments to the script; if there is an option called ``--foo`` and an option called ``--bar`` and the user calls it as ``--bar --foo``, then the callback for ``bar`` will fire before the one for ``foo``. There are three exceptions to this rule which are important to know: Eagerness: An option can be set to be "eager". All eager parameters are evaluated before all non-eager parameters, but again in the order as they were provided on the command line by the user. This is important for parameters that execute and exit like ``--help`` and ``--version``. Both are eager parameters, but whatever parameter comes first on the command line will win and exit the program. Repeated parameters: If an option or argument is split up on the command line into multiple places because it is repeated -- for instance, ``--exclude foo --include baz --exclude bar`` -- the callback will fire based on the position of the first option. In this case, the callback will fire for ``exclude`` and it will be passed both options (``foo`` and ``bar``), then the callback for ``include`` will fire with ``baz`` only. Note that even if a parameter does not allow multiple versions, Click will still accept the position of the first, but it will ignore every value except the last. The reason for this is to allow composability through shell aliases that set defaults. Missing parameters: If a parameter is not defined on the command line, the callback will still fire. This is different from how it works in optparse where undefined values do not fire the callback. Missing parameters fire their callbacks at the very end which makes it possible for them to default to values from a parameter that came before. Most of the time you do not need to be concerned about any of this, but it is important to know how it works for some advanced cases. asyncclick-8.3.0.5-async/docs/commands-and-groups.rst000066400000000000000000000247001507140761400224730ustar00rootroot00000000000000Basic Commands, Groups, Context ================================ .. currentmodule:: click Commands and Groups are the building blocks for Click applications. :class:`Command` wraps a function to make it into a cli command. :class:`Group` wraps Commands and Groups to make them into applications. :class:`Context` is how groups and commands communicate. .. contents:: :depth: 2 :local: Commands -------------------- Basic Command Example ^^^^^^^^^^^^^^^^^^^^^^^ A simple command decorator takes no arguments. .. click:example:: @click.command() @click.option('--count', default=1) def hello(count): for x in range(count): click.echo("Hello!") .. click:run:: invoke(hello, args=['--count', '2',]) Renaming Commands ^^^^^^^^^^^^^^^^^^^ By default the command is the function name with underscores replaced by dashes. To change this pass the desired name into the first positional argument. .. click:example:: @click.command('say-hello') @click.option('--count', default=1) def hello(count): for x in range(count): click.echo("Hello!") .. click:run:: invoke(hello, args=['--count', '2',]) Deprecating Commands ^^^^^^^^^^^^^^^^^^^^^^ To mark a command as deprecated pass in ``deprecated=True`` .. click:example:: @click.command('say-hello', deprecated=True) @click.option('--count', default=1) def hello(count): for x in range(count): click.echo("Hello!") .. click:run:: invoke(hello, args=['--count', '2',]) Groups ------------ Basic Group Example ^^^^^^^^^^^^^^^^^^^^^ A group wraps one or more commands. After being wrapped, the commands are nested under that group. You can see that on the help pages and in the execution. By default, invoking the group with no command shows the help page. .. click:example:: @click.group() def greeting(): click.echo('Starting greeting ...') @greeting.command('say-hello') @click.option('--count', default=1) def hello(count): for x in range(count): click.echo("Hello!") At the top level: .. click:run:: invoke(greeting) At the command level: .. click:run:: invoke(greeting, args=['say-hello']) invoke(greeting, args=['say-hello', '--help']) As you can see from the above example, the function wrapped by the group decorator executes unless it is interrupted (for example by calling the help). Renaming Groups ^^^^^^^^^^^^^^^^^ To have a name other than the decorated function name as the group name, pass it in as the first positional argument. .. click:example:: @click.group('greet-someone') def greeting(): click.echo('Starting greeting ...') @greeting.command('say-hello') @click.option('--count', default=1) def hello(count): for x in range(count): click.echo("Hello!") .. click:run:: invoke(greeting, args=['say-hello']) Group Invocation Without Command ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ By default, if a group is passed without a command, the group is not invoked and a command automatically passes ``--help``. To change this, pass ``invoke_without_command=True`` to the group. The context object also includes information about whether or not the group invocation would go to a command nested under it. .. click:example:: @click.group(invoke_without_command=True) @click.pass_context def cli(ctx): if ctx.invoked_subcommand is None: click.echo('I was invoked without subcommand') else: click.echo(f"I am about to invoke {ctx.invoked_subcommand}") @cli.command() def sync(): click.echo('The subcommand') .. click:run:: invoke(cli, prog_name='tool', args=[]) invoke(cli, prog_name='tool', args=['sync']) Group Separation ^^^^^^^^^^^^^^^^^^^ Command :ref:`parameters` attached to a command belong only to that command. .. click:example:: @click.group() def greeting(): pass @greeting.command() @click.option('--count', default=1) def hello(count): for x in range(count): click.echo("Hello!") @greeting.command() @click.option('--count', default=1) def goodbye(count): for x in range(count): click.echo("Goodbye!") .. click:run:: invoke(greeting, args=['hello', '--count', '2']) invoke(greeting, args=['goodbye', '--count', '2']) invoke(greeting) Additionally parameters for a given group belong only to that group and not to the commands under it. What this means is that options and arguments for a specific command have to be specified *after* the command name itself, but *before* any other command names. This behavior is observable with the ``--help`` option. Suppose we have a group called ``tool`` containing a command called ``sub``. - ``tool --help`` returns the help for the whole program (listing subcommands). - ``tool sub --help`` returns the help for the ``sub`` subcommand. - But ``tool --help sub`` treats ``--help`` as an argument for the main program. Click then invokes the callback for ``--help``, which prints the help and aborts the program before click can process the subcommand. Arbitrary Nesting ^^^^^^^^^^^^^^^^^^^ :class:`Commands ` are attached to a :class:`Group`. Multiple groups can be attached to another group. Groups containing multiple groups can be attached to a group, and so on. To invoke a command nested under multiple groups, all the groups under which it is nested must be invoked. .. click:example:: @click.group() def cli(): pass # Not @click so that the group is registered now. @cli.group() def session(): click.echo('Starting session') @session.command() def initdb(): click.echo('Initialized the database') @session.command() def dropdb(): click.echo('Dropped the database') .. click:run:: invoke(cli, args=['session', 'initdb']) Lazily Attaching Commands ^^^^^^^^^^^^^^^^^^^^^^^^^^^ Most examples so far have attached the commands to a group immediately, but commands may be registered later. This could be used to split commands into multiple Python modules. Regardless of how they are attached, the commands are invoked identically. .. click:example:: @click.group() def cli(): pass @cli.command() def initdb(): click.echo('Initialized the database') @click.command() def dropdb(): click.echo('Dropped the database') cli.add_command(dropdb) .. click:run:: invoke(cli, args=['initdb']) invoke(cli, args=['dropdb']) Context Object ------------------- The :class:`Context` object is how commands and groups communicate. Auto Envvar Prefix ^^^^^^^^^^^^^^^^^^^^ Automatically built environment variables are supported for options only. To enable this feature, the ``auto_envvar_prefix`` parameter needs to be passed to the script that is invoked. Each command and parameter is then added as an uppercase underscore-separated variable. If you have a subcommand called ``run`` taking an option called ``reload`` and the prefix is ``WEB``, then the variable is ``WEB_RUN_RELOAD``. Example usage: .. click:example:: @click.command() @click.option('--username') def greet(username): click.echo(f'Hello {username}!') if __name__ == '__main__': greet(auto_envvar_prefix='GREETER') And from the command line: .. click:run:: invoke(greet, env={'GREETER_USERNAME': 'john'}, auto_envvar_prefix='GREETER') When using ``auto_envvar_prefix`` with command groups, the command name needs to be included in the environment variable, between the prefix and the parameter name, *i.e.* ``PREFIX_COMMAND_VARIABLE``. If you have a subcommand called ``run-server`` taking an option called ``host`` and the prefix is ``WEB``, then the variable is ``WEB_RUN_SERVER_HOST``. .. click:example:: @click.group() @click.option('--debug/--no-debug') def cli(debug): click.echo(f"Debug mode is {'on' if debug else 'off'}") @cli.command() @click.option('--username') def greet(username): click.echo(f"Hello {username}!") if __name__ == '__main__': cli(auto_envvar_prefix='GREETER') .. click:run:: invoke(cli, args=['greet',], env={'GREETER_GREET_USERNAME': 'John', 'GREETER_DEBUG': 'false'}, auto_envvar_prefix='GREETER') Global Context Access ^^^^^^^^^^^^^^^^^^^^^^ .. versionadded:: 5.0 Starting with Click 5.0 it is possible to access the current context from anywhere within the same thread through the use of the :func:`get_current_context` function which returns it. This is primarily useful for accessing the context bound object as well as some flags that are stored on it to customize the runtime behavior. For instance the :func:`echo` function does this to infer the default value of the `color` flag. Example usage:: def get_current_command_name(): return click.get_current_context().info_name It should be noted that this only works within the current thread. If you spawn additional threads then those threads will not have the ability to refer to the current context. If you want to give another thread the ability to refer to this context you need to use the context within the thread as a context manager:: def spawn_thread(ctx, func): def wrapper(): with ctx: func() t = threading.Thread(target=wrapper) t.start() return t Now the thread function can access the context like the main thread would do. However if you do use this for threading you need to be very careful as the vast majority of the context is not thread safe! You are only allowed to read from the context, but not to perform any modifications on it. Detecting the Source of a Parameter ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ In some situations it's helpful to understand whether or not an option or parameter came from the command line, the environment, the default value, or :attr:`Context.default_map`. The :meth:`Context.get_parameter_source` method can be used to find this out. It will return a member of the :class:`~click.core.ParameterSource` enum. .. click:example:: @click.command() @click.argument('port', nargs=1, default=8080, envvar="PORT") @click.pass_context def cli(ctx, port): source = ctx.get_parameter_source("port") click.echo(f"Port came from {source.name}") .. click:run:: invoke(cli, prog_name='cli', args=['8080']) println() invoke(cli, prog_name='cli', args=[], env={"PORT": "8080"}) println() invoke(cli, prog_name='cli', args=[]) println() asyncclick-8.3.0.5-async/docs/commands.rst000066400000000000000000000337161507140761400204250ustar00rootroot00000000000000Advanced Groups and Context ============================= .. currentmodule:: click In addition to the capabilities covered in the previous section, Groups have more advanced capabilities that leverage the Context. .. contents:: :depth: 1 :local: Callback Invocation ------------------- For a regular command, the callback is executed whenever the command runs. If the script is the only command, it will always fire (unless a parameter callback prevents it. This for instance happens if someone passes ``--help`` to the script). For groups, the situation looks different. In this case, the callback fires whenever a subcommand fires. What this means in practice is that an outer command runs when an inner command runs: .. click:example:: @click.group() @click.option('--debug/--no-debug', default=False) def cli(debug): click.echo(f"Debug mode is {'on' if debug else 'off'}") @cli.command() # @cli, not @click! def sync(): click.echo('Syncing') Here is what this looks like: .. click:run:: invoke(cli, prog_name='tool.py') println() invoke(cli, prog_name='tool.py', args=['--debug', 'sync']) Nested Handling and Contexts ---------------------------- As you can see from the earlier example, the basic command group accepts a debug argument which is passed to its callback, but not to the sync command itself. The sync command only accepts its own arguments. This allows tools to act completely independent of each other, but how does one command talk to a nested one? The answer to this is the :class:`Context`. Each time a command is invoked, a new context is created and linked with the parent context. Normally, you can't see these contexts, but they are there. Contexts are passed to parameter callbacks together with the value automatically. Commands can also ask for the context to be passed by marking themselves with the :func:`pass_context` decorator. In that case, the context is passed as first argument. The context can also carry a program specified object that can be used for the program's purposes. What this means is that you can build a script like this: .. click:example:: @click.group() @click.option('--debug/--no-debug', default=False) @click.pass_context def cli(ctx, debug): # ensure that ctx.obj exists and is a dict (in case `cli()` is called # by means other than the `if` block below) ctx.ensure_object(dict) ctx.obj['DEBUG'] = debug @cli.command() @click.pass_context def sync(ctx): click.echo(f"Debug is {'on' if ctx.obj['DEBUG'] else 'off'}") if __name__ == '__main__': cli(obj={}) If the object is provided, each context will pass the object onwards to its children, but at any level a context's object can be overridden. To reach to a parent, ``context.parent`` can be used. In addition to that, instead of passing an object down, nothing stops the application from modifying global state. For instance, you could just flip a global ``DEBUG`` variable and be done with it. Decorating Commands ------------------- As you have seen in the earlier example, a decorator can change how a command is invoked. What actually happens behind the scenes is that callbacks are always invoked through the :meth:`Context.invoke` method which automatically invokes a command correctly (by either passing the context or not). This is very useful when you want to write custom decorators. For instance, a common pattern would be to configure an object representing state and then storing it on the context and then to use a custom decorator to find the most recent object of this sort and pass it as first argument. For instance, the :func:`pass_obj` decorator can be implemented like this: .. click:example:: from functools import update_wrapper def pass_obj(f): @click.pass_context def new_func(ctx, *args, **kwargs): return ctx.invoke(f, ctx.obj, *args, **kwargs) return update_wrapper(new_func, f) The :meth:`Context.invoke` command will automatically invoke the function in the correct way, so the function will either be called with ``f(ctx, obj)`` or ``f(obj)`` depending on whether or not it itself is decorated with :func:`pass_context`. This is a very powerful concept that can be used to build very complex nested applications; see :ref:`complex-guide` for more information. .. _command-chaining: Command Chaining ---------------- It is useful to invoke more than one subcommand in one call. For example, ``my-app validate build upload`` would invoke ``validate``, then ``build``, then ``upload``. To implement this, pass ``chain=True`` when creating a group. .. click:example:: @click.group(chain=True) def cli(): pass @cli.command('validate') def validate(): click.echo('validate') @cli.command('build') def build(): click.echo('build') You can invoke it like this: .. click:run:: invoke(cli, prog_name='my-app', args=['validate', 'build']) When using chaining, there are a few restrictions: - Only the last command may use ``nargs=-1`` on an argument, otherwise the parser will not be able to find further commands. - It is not possible to nest groups below a chain group. - On the command line, options must be specified before arguments for each command in the chain. - The :attr:`Context.invoked_subcommand` attribute will be ``'*'`` because the parser doesn't know the full list of commands that will run yet. .. _command-pipelines: Command Pipelines ------------------ When using chaining, a common pattern is to have each command process the result of the previous command. A straightforward way to do this is to use :func:`make_pass_decorator` to pass a context object to each command, and store and read the data on that object. .. click:example:: pass_ns = click.make_pass_decorator(dict, ensure=True) @click.group(chain=True) @click.argument("name") @pass_ns def cli(ns, name): ns["name"] = name @cli.command @pass_ns def lower(ns): ns["name"] = ns["name"].lower() @cli.command @pass_ns def show(ns): click.echo(ns["name"]) .. click:run:: invoke(cli, prog_name="process", args=["Click", "show", "lower", "show"]) Another way to do this is to collect data returned by each command, then process it at the end of the chain. Use the group's :meth:`~Group.result_callback` decorator to register a function that is called after the chain is finished. It is passed the list of return values as well as any parameters registered on the group. A command can return anything, including a function. Here's an example of that, where each subcommand creates a function that processes the input, then the result callback calls each function. The command takes a file, processes each line, then outputs it. If no subcommands are given, it outputs the contents of the file unchanged. .. code-block:: python @click.group(chain=True, invoke_without_command=True) @click.argument("fin", type=click.File("r")) def cli(fin): pass @cli.result_callback() def process_pipeline(processors, fin): iterator = (x.rstrip("\r\n") for x in input) for processor in processors: iterator = processor(iterator) for item in iterator: click.echo(item) @cli.command("upper") def make_uppercase(): def processor(iterator): for line in iterator: yield line.upper() return processor @cli.command("lower") def make_lowercase(): def processor(iterator): for line in iterator: yield line.lower() return processor @cli.command("strip") def make_strip(): def processor(iterator): for line in iterator: yield line.strip() return processor That's a lot in one go, so let's go through it step by step. 1. The first thing is to make a :func:`group` that is chainable. In addition to that we also instruct Click to invoke even if no subcommand is defined. If this would not be done, then invoking an empty pipeline would produce the help page instead of running the result callbacks. 2. The next thing we do is to register a result callback on our group. This callback will be invoked with an argument which is the list of all return values of all subcommands and then the same keyword parameters as our group itself. This means we can access the input file easily there without having to use the context object. 3. In this result callback we create an iterator of all the lines in the input file and then pass this iterator through all the returned callbacks from all subcommands and finally we print all lines to stdout. After that point we can register as many subcommands as we want and each subcommand can return a processor function to modify the stream of lines. One important thing of note is that Click shuts down the context after each callback has been run. This means that for instance file types cannot be accessed in the `processor` functions as the files will already be closed there. This limitation is unlikely to change because it would make resource handling much more complicated. For such it's recommended to not use the file type and manually open the file through :func:`open_file`. For a more complex example that also improves upon handling of the pipelines, see the `imagepipe example`_ in the Click repository. It implements a pipeline based image editing tool that has a nice internal structure. .. _imagepipe example: https://github.com/pallets/click/tree/main/examples/imagepipe Overriding Defaults ------------------- By default, the default value for a parameter is pulled from the ``default`` flag that is provided when it's defined, but that's not the only place defaults can be loaded from. The other place is the :attr:`Context.default_map` (a dictionary) on the context. This allows defaults to be loaded from a configuration file to override the regular defaults. This is useful if you plug in some commands from another package but you're not satisfied with the defaults. The default map can be nested arbitrarily for each subcommand: .. code-block:: python default_map = { "debug": True, # default for a top level option "runserver": {"port": 5000} # default for a subcommand } The default map can be provided when the script is invoked, or overridden at any point by commands. For instance, a top-level command could load the defaults from a configuration file. Example usage: .. click:example:: import asyncclick as click @click.group() def cli(): pass @cli.command() @click.option('--port', default=8000) def runserver(port): click.echo(f"Serving on http://127.0.0.1:{port}/") if __name__ == '__main__': cli(default_map={ 'runserver': { 'port': 5000 } }) And in action: .. click:run:: invoke(cli, prog_name='cli', args=['runserver'], default_map={ 'runserver': { 'port': 5000 } }) Context Defaults ---------------- .. versionadded:: 2.0 Starting with Click 2.0 you can override defaults for contexts not just when calling your script, but also in the decorator that declares a command. For instance given the previous example which defines a custom ``default_map`` this can also be accomplished in the decorator now. This example does the same as the previous example: .. click:example:: import asyncclick as click CONTEXT_SETTINGS = dict( default_map={'runserver': {'port': 5000}} ) @click.group(context_settings=CONTEXT_SETTINGS) def cli(): pass @cli.command() @click.option('--port', default=8000) def runserver(port): click.echo(f"Serving on http://127.0.0.1:{port}/") if __name__ == '__main__': cli() And again the example in action: .. click:run:: invoke(cli, prog_name='cli', args=['runserver']) Command Return Values --------------------- .. versionadded:: 3.0 One of the new introductions in Click 3.0 is the full support for return values from command callbacks. This enables a whole range of features that were previously hard to implement. In essence any command callback can now return a value. This return value is bubbled to certain receivers. One usecase for this has already been show in the example of :ref:`command-chaining` where it has been demonstrated that chained groups can have callbacks that process all return values. When working with command return values in Click, this is what you need to know: - The return value of a command callback is generally returned from the :meth:`Command.invoke` method. The exception to this rule has to do with :class:`Group`\s: * In a group the return value is generally the return value of the subcommand invoked. The only exception to this rule is that the return value is the return value of the group callback if it's invoked without arguments and `invoke_without_command` is enabled. * If a group is set up for chaining then the return value is a list of all subcommands' results. * Return values of groups can be processed through a :attr:`Group.result_callback`. This is invoked with the list of all return values in chain mode, or the single return value in case of non chained commands. - The return value is bubbled through from the :meth:`Context.invoke` and :meth:`Context.forward` methods. This is useful in situations where you internally want to call into another command. - Click does not have any hard requirements for the return values and does not use them itself. This allows return values to be used for custom decorators or workflows (like in the command chaining example). - When a Click script is invoked as command line application (through :meth:`Command.main`) the return value is ignored unless the `standalone_mode` is disabled in which case it's bubbled through. asyncclick-8.3.0.5-async/docs/complex.rst000066400000000000000000000325461507140761400202730ustar00rootroot00000000000000.. _complex-guide: Complex Applications ==================== .. currentmodule:: click Click is designed to assist with the creation of complex and simple CLI tools alike. However, the power of its design is the ability to arbitrarily nest systems together. For instance, if you have ever used Django, you will have realized that it provides a command line utility, but so does Celery. When using Celery with Django, there are two tools that need to interact with each other and be cross-configured. In a theoretical world of two separate Click command line utilities, they could solve this problem by nesting one inside the other. For instance, the web framework could also load the commands for the message queue framework. .. contents:: :depth: 1 :local: Basic Concepts -------------- To understand how this works, you need to understand two concepts: contexts and the calling convention. Contexts ```````` Whenever a Click command is executed, a :class:`Context` object is created which holds state for this particular invocation. It remembers parsed parameters, what command created it, which resources need to be cleaned up at the end of the function, and so forth. It can also optionally hold an application-defined object. Context objects build a linked list until they hit the top one. Each context is linked to a parent context. This allows a command to work below another command and store its own information there without having to be afraid of altering up the state of the parent command. Because the parent data is available, however, it is possible to navigate to it if needed. Most of the time, you do not see the context object, but when writing more complex applications it comes in handy. This brings us to the next point. Calling Convention `````````````````` When a Click command callback is executed, it's passed all the non-hidden parameters as keyword arguments. Notably absent is the context. However, a callback can opt into being passed to the context object by marking itself with :func:`pass_context`. So how do you invoke a command callback if you don't know if it should receive the context or not? The answer is that the context itself provides a helper function (:meth:`Context.invoke`) which can do this for you. It accepts the callback as first argument and then invokes the function correctly. Building a Git Clone -------------------- In this example, we want to build a command line tool that resembles a version control system. Systems like Git usually provide one over-arching command that already accepts some parameters and configuration, and then have extra subcommands that do other things. The Root Command ```````````````` At the top level, we need a group that can hold all our commands. In this case, we use the basic :func:`click.group` which allows us to register other Click commands below it. For this command, we also want to accept some parameters that configure the state of our tool: .. click:example:: import os import asyncclick as click class Repo(object): def __init__(self, home=None, debug=False): self.home = os.path.abspath(home or '.') self.debug = debug @click.group() @click.option('--repo-home', envvar='REPO_HOME', default='.repo') @click.option('--debug/--no-debug', default=False, envvar='REPO_DEBUG') @click.pass_context def cli(ctx, repo_home, debug): ctx.obj = Repo(repo_home, debug) Let's understand what this does. We create a group command which can have subcommands. When it is invoked, it will create an instance of a ``Repo`` class. This holds the state for our command line tool. In this case, it just remembers some parameters, but at this point it could also start loading configuration files and so on. This state object is then remembered by the context as :attr:`~Context.obj`. This is a special attribute where commands are supposed to remember what they need to pass on to their children. In order for this to work, we need to mark our function with :func:`pass_context`, because otherwise, the context object would be entirely hidden from us. The First Child Command ``````````````````````` Let's add our first child command to it, the clone command: .. click:example:: @cli.command() @click.argument('src') @click.argument('dest', required=False) def clone(src, dest): pass So now we have a clone command, but how do we get access to the repo? As you can imagine, one way is to use the :func:`pass_context` function which again will make our callback also get the context passed on which we memorized the repo. However, there is a second version of this decorator called :func:`pass_obj` which will just pass the stored object, (in our case the repo): .. click:example:: @cli.command() @click.argument('src') @click.argument('dest', required=False) @click.pass_obj def clone(repo, src, dest): pass Interleaved Commands ```````````````````` While not relevant for the particular program we want to build, there is also quite good support for interleaving systems. Imagine for instance that there was a super cool plugin for our version control system that needed a lot of configuration and wanted to store its own configuration as :attr:`~Context.obj`. If we would then attach another command below that, we would all of a sudden get the plugin configuration instead of our repo object. One obvious way to remedy this is to store a reference to the repo in the plugin, but then a command needs to be aware that it's attached below such a plugin. There is a much better system that can be built by taking advantage of the linked nature of contexts. We know that the plugin context is linked to the context that created our repo. Because of that, we can start a search for the last level where the object stored by the context was a repo. Built-in support for this is provided by the :func:`make_pass_decorator` factory, which will create decorators for us that find objects (it internally calls into :meth:`Context.find_object`). In our case, we know that we want to find the closest ``Repo`` object, so let's make a decorator for this: .. click:example:: pass_repo = click.make_pass_decorator(Repo) If we now use ``pass_repo`` instead of ``pass_obj``, we will always get a repo instead of something else: .. click:example:: @cli.command() @click.argument('src') @click.argument('dest', required=False) @pass_repo def clone(repo, src, dest): pass Ensuring Object Creation ```````````````````````` The above example only works if there was an outer command that created a ``Repo`` object and stored it in the context. For some more advanced use cases, this might become a problem. The default behavior of :func:`make_pass_decorator` is to call :meth:`Context.find_object` which will find the object. If it can't find the object, :meth:`make_pass_decorator` will raise an error. The alternative behavior is to use :meth:`Context.ensure_object` which will find the object, and if it cannot find it, will create one and store it in the innermost context. This behavior can also be enabled for :func:`make_pass_decorator` by passing ``ensure=True``: .. click:example:: pass_repo = click.make_pass_decorator(Repo, ensure=True) In this case, the innermost context gets an object created if it is missing. This might replace objects being placed there earlier. In this case, the command stays executable, even if the outer command does not run. For this to work, the object type needs to have a constructor that accepts no arguments. As such it runs standalone: .. click:example:: @click.command() @pass_repo def cp(repo): click.echo(isinstance(repo, Repo)) As you can see: .. click:run:: invoke(cp, []) Lazily Loading Subcommands -------------------------- Large CLIs and CLIs with slow imports may benefit from deferring the loading of subcommands. The interfaces which support this mode of use are :meth:`Group.list_commands` and :meth:`Group.get_command`. A custom :class:`Group` subclass can implement a lazy loader by storing extra data such that :meth:`Group.get_command` is responsible for running imports. Since the primary case for this is a :class:`Group` which loads its subcommands lazily, the following example shows a lazy-group implementation. .. warning:: Lazy loading of python code can result in hard to track down bugs, circular imports in order-dependent codebases, and other surprising behaviors. It is recommended that this technique only be used in concert with testing which will at least run the ``--help`` on each subcommand. That will guarantee that each subcommand can be loaded successfully. Defining the Lazy Group ``````````````````````` The following :class:`Group` subclass adds an attribute, ``lazy_subcommands``, which stores a mapping from subcommand names to the information for importing them. .. code-block:: python # in lazy_group.py import importlib import asyncclick as click class LazyGroup(click.Group): def __init__(self, *args, lazy_subcommands=None, **kwargs): super().__init__(*args, **kwargs) # lazy_subcommands is a map of the form: # # {command-name} -> {module-name}.{command-object-name} # self.lazy_subcommands = lazy_subcommands or {} def list_commands(self, ctx): base = super().list_commands(ctx) lazy = sorted(self.lazy_subcommands.keys()) return base + lazy def get_command(self, ctx, cmd_name): if cmd_name in self.lazy_subcommands: return self._lazy_load(cmd_name) return super().get_command(ctx, cmd_name) def _lazy_load(self, cmd_name): # lazily loading a command, first get the module name and attribute name import_path = self.lazy_subcommands[cmd_name] modname, cmd_object_name = import_path.rsplit(".", 1) # do the import mod = importlib.import_module(modname) # get the Command object from that module cmd_object = getattr(mod, cmd_object_name) # check the result to make debugging easier if not isinstance(cmd_object, click.Command): raise ValueError( f"Lazy loading of {import_path} failed by returning " "a non-command object" ) return cmd_object Using LazyGroup To Define a CLI ``````````````````````````````` With ``LazyGroup`` defined, it's now possible to write a group which lazily loads its subcommands like so: .. code-block:: python # in main.py import asyncclick as click from lazy_group import LazyGroup @click.group( cls=LazyGroup, lazy_subcommands={"foo": "foo.cli", "bar": "bar.cli"}, help="main CLI command for lazy example", ) def cli(): pass .. code-block:: python # in foo.py import asyncclick as click @click.group(help="foo command for lazy example") def cli(): pass .. code-block:: python # in bar.py import asyncclick as click from lazy_group import LazyGroup @click.group( cls=LazyGroup, lazy_subcommands={"baz": "baz.cli"}, help="bar command for lazy example", ) def cli(): pass .. code-block:: python # in baz.py import asyncclick as click @click.group(help="baz command for lazy example") def cli(): pass What triggers Lazy Loading? ``````````````````````````` There are several events which may trigger lazy loading by running the :meth:`Group.get_command` function. Some are intuititve, and some are less so. All cases are described with respect to the above example, assuming the main program name is ``cli``. 1. Command resolution. If a user runs ``cli bar baz``, this must first resolve ``bar``, and then resolve ``baz``. Each subcommand resolution step does a lazy load. 2. Helptext rendering. In order to get the short help description of subcommands, ``cli --help`` will load ``foo`` and ``bar``. Note that it will still not load ``baz``. 3. Shell completion. In order to get the subcommands of a lazy command, ``cli `` will need to resolve the subcommands of ``cli``. This process will trigger the lazy loads. Further Deferring Imports ````````````````````````` It is possible to make the process even lazier, but it is generally more difficult the more you want to defer work. For example, subcommands could be represented as a custom :class:`Command` subclass which defers importing the command until it is invoked, but which provides :meth:`Command.get_short_help_str` in order to support completions and helptext. More simply, commands can be constructed whose callback functions defer any actual work until after an import. This command definition provides ``foo``, but any of the work associated with importing the "real" callback function is deferred until invocation time: .. click:example:: @click.command() @click.option("-n", type=int) @click.option("-w", type=str) def foo(n, w): from mylibrary import foo_concrete foo_concrete(n, w) Because Click builds helptext and usage info from options, arguments, and command attributes, it has no awareness that the underlying function is in any way handling a deferred import. Therefore, all Click-provided utilities and functionality will work as normal on such a command. asyncclick-8.3.0.5-async/docs/conf.py000066400000000000000000000036121507140761400173610ustar00rootroot00000000000000from pallets_sphinx_themes import get_version from pallets_sphinx_themes import ProjectLink # Project -------------------------------------------------------------- project = "Click" copyright = "2014 Pallets" author = "Pallets" release, version = get_version("Click") # General -------------------------------------------------------------- master_doc = "index" default_role = "code" extensions = [ "sphinx.ext.autodoc", "sphinx.ext.extlinks", "sphinx.ext.intersphinx", "sphinx_tabs.tabs", "sphinxcontrib.log_cabinet", "pallets_sphinx_themes", "myst_parser", ] autodoc_member_order = "bysource" autodoc_typehints = "description" autodoc_preserve_defaults = True extlinks = { "issue": ("https://github.com/pallets/click/issues/%s", "#%s"), "pr": ("https://github.com/pallets/click/pull/%s", "#%s"), } intersphinx_mapping = { "python": ("https://docs.python.org/3/", None), } # HTML ----------------------------------------------------------------- html_theme = "click" html_theme_options = {"index_sidebar_logo": False} html_context = { "project_links": [ ProjectLink("Donate", "https://palletsprojects.com/donate"), ProjectLink("PyPI Releases", "https://pypi.org/project/click/"), ProjectLink("Source Code", "https://github.com/pallets/click/"), ProjectLink("Issue Tracker", "https://github.com/pallets/click/issues/"), ProjectLink("Chat", "https://discord.gg/pallets"), ] } html_sidebars = { "index": ["project.html", "localtoc.html", "searchbox.html", "ethicalads.html"], "**": ["localtoc.html", "relations.html", "searchbox.html", "ethicalads.html"], } singlehtml_sidebars = {"index": ["project.html", "localtoc.html", "ethicalads.html"]} html_static_path = ["_static"] html_favicon = "_static/click-icon.svg" html_logo = "_static/click-logo.svg" html_title = f"Click Documentation ({version})" html_show_sourcelink = False asyncclick-8.3.0.5-async/docs/contrib.md000066400000000000000000000075541507140761400200550ustar00rootroot00000000000000(contrib)= # click-contrib As the user number of Click grows, more and more major feature requests are made. To users, it may seem reasonable to include those features with Click; however, many of them are experimental or aren't practical to support generically. Maintainers have to choose what is reasonable to maintain in Click core. The [click-contrib](https://github.com/click-contrib/) GitHub organization exists as a place to collect third-party packages that extend Click's features. It is also meant to ease the effort of searching for such extensions. Please note that the quality and stability of those packages may be different from Click itself. While published under a common organization, they are still separate from Click and the Pallets maintainers. ## Third-party projects Other projects that extend Click's features are available outside the [click-contrib](https://github.com/click-contrib/) organization. Some of the most popular and actively maintained are listed below: | Project | Description | Popularity | Activity | |---------------------------------------------------------|--------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------| | [Typer](https://github.com/fastapi/typer) | Use Python type hints to create CLI apps. | ![GitHub stars](https://img.shields.io/github/stars/fastapi/typer?label=%20&style=flat-square) | ![Last commit](https://img.shields.io/github/last-commit/fastapi/typer?label=%20&style=flat-square) | | [rich-click](https://github.com/ewels/rich-click) | Format help output with Rich. | ![GitHub stars](https://img.shields.io/github/stars/ewels/rich-click?label=%20&style=flat-square) | ![Last commit](https://img.shields.io/github/last-commit/ewels/rich-click?label=%20&style=flat-square) | | [click-app](https://github.com/simonw/click-app) | Cookiecutter template for creating new CLIs. | ![GitHub stars](https://img.shields.io/github/stars/simonw/click-app?label=%20&style=flat-square) | ![Last commit](https://img.shields.io/github/last-commit/simonw/click-app?label=%20&style=flat-square) | | [Cloup](https://github.com/janluke/cloup) | Adds option groups, constraints, command aliases, help themes, suggestions and more. | ![GitHub stars](https://img.shields.io/github/stars/janluke/cloup?label=%20&style=flat-square) | ![Last commit](https://img.shields.io/github/last-commit/janluke/cloup?label=%20&style=flat-square) | | [Click Extra](https://github.com/kdeldycke/click-extra) | Cloup + colorful `--help`, `--config`, `--show-params`, `--verbosity` options, etc. | ![GitHub stars](https://img.shields.io/github/stars/kdeldycke/click-extra?label=%20&style=flat-square) | ![Last commit](https://img.shields.io/github/last-commit/kdeldycke/click-extra?label=%20&style=flat-square) | ```{note} To make it into the list above, a project: - must be actively maintained (at least one commit in the last year) - must have a reasonable number of stars (at least 20) If you have a project that meets these criteria, please open a pull request to add it to the list. If a project is no longer maintained or does not meet the criteria above, please open a pull request to remove it from the list. ``` asyncclick-8.3.0.5-async/docs/documentation.md000066400000000000000000000161321507140761400212560ustar00rootroot00000000000000# Help Pages ```{currentmodule} click ``` Click makes it very easy to document your command line tools. For most things Click automatically generates help pages for you. By design the text is customizable, but the layout is not. ## Help Texts Commands and options accept help arguments. For commands, the docstring of the function is automatically used if provided. Simple example: ```{eval-rst} .. click:example:: @click.command() @click.argument('name') @click.option('--count', default=1, help='number of greetings') def hello(name: str, count: int): """This script prints hello and a name one or more times.""" for x in range(count): if name: click.echo(f"Hello {name}!") else: click.echo("Hello!") .. click:run:: invoke(hello, args=['--help']) ``` ## Command Short Help For subcommands, a short help snippet is generated. By default, it's the first sentence of the docstring. If too long, then it will ellipsize what cannot be fit on a single line with `...`. The short help snippet can also be overridden with `short_help`: ```{eval-rst} .. click:example:: import click @click.group() def cli(): """A simple command line tool.""" @cli.command('init', short_help='init the repo') def init(): """Initializes the repository.""" .. click:run:: invoke(cli, args=['--help']) ``` ## Command Epilog Help The help epilog is printed at the end of the help and is useful for showing example command usages or referencing additional help resources. ```{eval-rst} .. click:example:: import click @click.command( epilog='See https://example.com for more details', ) def init(): """Initializes the repository.""" .. click:run:: invoke(init, args=['--help']) ``` (documenting-arguments)= ## Documenting Arguments {class}`click.argument` does not take a `help` parameter. This follows the Unix Command Line Tools convention of using arguments only for necessary things and documenting them in the command help text by name. This should then be done via the docstring. A brief example: ```{eval-rst} .. click:example:: @click.command() @click.argument('filename') def touch(filename): """Print FILENAME.""" click.echo(filename) .. click:run:: invoke(touch, args=['--help']) ``` Or more explicitly: ```{eval-rst} .. click:example:: @click.command() @click.argument('filename') def touch(filename): """Print FILENAME. FILENAME is the name of the file to check. """ click.echo(filename) .. click:run:: invoke(touch, args=['--help']) ``` ## Showing Defaults To control the appearance of defaults pass `show_default`. ```{eval-rst} .. click:example:: @click.command() @click.option('--n', default=1, show_default=False, help='number of dots') def dots(n): click.echo('.' * n) .. click:run:: invoke(dots, args=['--help']) ``` For single option boolean flags, the default remains hidden if the default value is False, even if show default is set to true. ```{eval-rst} .. click:example:: @click.command() @click.option('--n', default=1, show_default=True) @click.option("--gr", is_flag=True, show_default=True, default=False, help="Greet the world.") @click.option("--br", is_flag=True, show_default=True, default=True, help="Add a thematic break") def dots(n, gr, br): if gr: click.echo('Hello world!') click.echo('.' * n) if br: click.echo('-' * n) .. click:run:: invoke(dots, args=['--help']) ``` ## Click's Wrapping Behavior Click's default wrapping ignores single new lines and rewraps the text based on the width of the terminal to a maximum of 80 characters by default, but this can be modified with {attr}`~Context.max_content_width`. In the example notice how the second grouping of three lines is rewrapped into a single paragraph. ```{eval-rst} .. click:example:: import click @click.command() def cli(): """ This is a very long paragraph and as you can see wrapped very early in the source text but will be rewrapped to the terminal width in the final output. This is a paragraph that is compacted. """ .. click:run:: invoke(cli, args=['--help']) ``` ## Escaping Click's Wrapping Sometimes Click's wrapping can be a problem, such as when showing code examples where new lines are significant. This behavior can be escaped on a per-paragraph basis by adding a line with only `\b` . The `\b` is removed from the rendered help text. Example: ```{eval-rst} .. click:example:: import click @click.command() def cli(): """First paragraph. \b This is a paragraph without rewrapping. And this is a paragraph that will be rewrapped again. """ .. click:run:: invoke(cli, args=['--help']) ``` To change the rendering maximum width, pass `max_content_width` when calling the command. ```bash cli(max_content_width=120) ``` ## Truncating Help Texts Click gets {class}`Command` help text from the docstring. If you do not want to include part of the docstring, add the `\f` escape marker to have Click truncate the help text after the marker. Example: ```{eval-rst} .. click:example:: import click @click.command() def cli(): """First paragraph. \f Words to not be included. """ .. click:run:: invoke(cli, args=['--help']) ``` (doc-meta-variables)= ## Placeholder / Meta Variable The default placeholder variable ([meta variable](https://en.wikipedia.org/wiki/Metasyntactic_variable#IETF_Requests_for_Comments)) in the help pages is the parameter name in uppercase with underscores. This can be changed for Commands and Parameters with the `options_metavar` and `metavar` kwargs. ```{eval-rst} .. click:example:: # This controls entry on the usage line. @click.command(options_metavar='[[options]]') @click.option('--count', default=1, help='number of greetings', metavar='') @click.argument('name', metavar='') def hello(name: str, count: int) -> None: """This script prints 'hello ' a total of times.""" for x in range(count): click.echo(f"Hello {name}!") # Example usage: .. click:run:: invoke(hello, args=['--help']) ``` ## Help Parameter Customization Help parameters are automatically added by Click for any command. The default is `--help` but can be overridden by the context setting {attr}`~Context.help_option_names`. Click also performs automatic conflict resolution on the default help parameter, so if a command itself implements a parameter named `help` then the default help will not be run. This example changes the default parameters to `-h` and `--help` instead of just `--help`: ```{eval-rst} .. click:example:: import click CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help']) @click.command(context_settings=CONTEXT_SETTINGS) def cli(): pass .. click:run:: invoke(cli, ['-h']) ``` asyncclick-8.3.0.5-async/docs/entry-points.rst000066400000000000000000000044311507140761400212670ustar00rootroot00000000000000Packaging Entry Points ====================== It's recommended to write command line utilities as installable packages with entry points instead of telling users to run ``python hello.py``. A distribution package is a ``.whl`` file you install with pip or another Python installer. You use a ``pyproject.toml`` file to describe the project and how it is built into a package. You might upload this package to PyPI, or distribute it to your users in another way. Python installers create executable scripts that will run a specified Python function. These are known as "entry points". The installer knows how to create an executable regardless of the operating system, so it will work on Linux, Windows, MacOS, etc. Project Files ------------- To install your app with an entry point, all you need is the script and a ``pyproject.toml`` file. Here's an example project directory: .. code-block:: text hello-project/ src/ hello/ __init__.py hello.py pyproject.toml Contents of ``hello.py``: .. click:example:: import click @click.command() def cli(): """Prints a greeting.""" click.echo("Hello, World!") Contents of ``pyproject.toml``: .. code-block:: toml [project] name = "hello" version = "1.0.0" description = "Hello CLI" requires-python = ">=3.11" dependencies = [ "click>=8.1", ] [project.scripts] hello = "hello.hello:cli" [build-system] requires = ["flit_core<4"] build-backend = "flit_core.buildapi" The magic is in the ``project.scripts`` section. Each line identifies one executable script. The first part before the equals sign (``=``) is the name of the script that should be generated, the second part is the import path followed by a colon (``:``) with the function to call (the Click command). Installation ------------ When your package is installed, the installer will create an executable script based on the configuration. During development, you can install in editable mode using the ``-e`` option. Remember to use a virtual environment! .. code-block:: console $ python -m venv .venv $ . .venv/bin/activate $ pip install -e . Afterwards, your command should be available: .. click:run:: invoke(cli, prog_name="hello") asyncclick-8.3.0.5-async/docs/exceptions.rst000066400000000000000000000055721507140761400210040ustar00rootroot00000000000000Exception Handling ================== .. currentmodule:: click Click internally uses exceptions to signal various error conditions that the user of the application might have caused. Primarily this is things like incorrect usage. Where are Errors Handled? ------------------------- Click's main error handling is happening in :meth:`Command.main`. In there it handles all subclasses of :exc:`ClickException` as well as the standard :exc:`EOFError` and :exc:`KeyboardInterrupt` exceptions. The latter are internally translated into an :exc:`Abort`. The logic applied is the following: 1. If an :exc:`EOFError` or :exc:`KeyboardInterrupt` happens, reraise it as :exc:`Abort`. 2. If a :exc:`ClickException` is raised, invoke the :meth:`ClickException.show` method on it to display it and then exit the program with :attr:`ClickException.exit_code`. 3. If an :exc:`Abort` exception is raised print the string ``Aborted!`` to standard error and exit the program with exit code ``1``. 4. If it goes through well, exit the program with exit code ``0``. What if I don't want that? -------------------------- Generally you always have the option to invoke the :meth:`invoke` method yourself. For instance if you have a :class:`Command` you can invoke it manually like this:: ctx = await command.make_context('command-name', ['args', 'go', 'here']) with ctx: result = await command.invoke(ctx) In this case exceptions will not be handled at all and bubbled up as you would expect. Starting with Click 3.0 you can also use the :meth:`Command.main` method but disable the standalone mode which will do two things: disable exception handling and disable the implicit :meth:`sys.exit` at the end. So you can do something like this:: await command.main(['command-name', 'args', 'go', 'here'], standalone_mode=False) Which Exceptions Exist? ----------------------- Click has two exception bases: :exc:`ClickException` which is raised for all exceptions that Click wants to signal to the user and :exc:`Abort` which is used to instruct Click to abort the execution. A :exc:`ClickException` has a :meth:`~ClickException.show` method which can render an error message to stderr or the given file object. If you want to use the exception yourself for doing something check the API docs about what else they provide. The following common subclasses exist: * :exc:`UsageError` to inform the user that something went wrong. * :exc:`BadParameter` to inform the user that something went wrong with a specific parameter. These are often handled internally in Click and augmented with extra information if possible. For instance if those are raised from a callback Click will automatically augment it with the parameter name if possible. * :exc:`FileError` this is an error that is raised by the :exc:`FileType` if Click encounters issues opening the file. asyncclick-8.3.0.5-async/docs/extending-click.rst000066400000000000000000000075611507140761400216730ustar00rootroot00000000000000Extending Click ================= .. currentmodule:: click In addition to common functionality that is implemented in the library itself, there are countless patterns that can be implemented by extending Click. This page should give some insight into what can be accomplished. .. contents:: :depth: 2 :local: .. _custom-groups: Custom Groups ------------- You can customize the behavior of a group beyond the arguments it accepts by subclassing :class:`click.Group`. The most common methods to override are :meth:`~click.Group.get_command` and :meth:`~click.Group.list_commands`. The following example implements a basic plugin system that loads commands from Python files in a folder. The command is lazily loaded to avoid slow startup. .. code-block:: python import importlib.util import os import click class PluginGroup(click.Group): def __init__(self, name=None, plugin_folder="commands", **kwargs): super().__init__(name=name, **kwargs) self.plugin_folder = plugin_folder def list_commands(self, ctx): rv = [] for filename in os.listdir(self.plugin_folder): if filename.endswith(".py"): rv.append(filename[:-3]) rv.sort() return rv def get_command(self, ctx, name): path = os.path.join(self.plugin_folder, f"{name}.py") spec = importlib.util.spec_from_file_location(name, path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module.cli cli = PluginGroup( plugin_folder=os.path.join(os.path.dirname(__file__), "commands") ) if __name__ == "__main__": cli() Custom classes can also be used with decorators: .. code-block:: python @click.group( cls=PluginGroup, plugin_folder=os.path.join(os.path.dirname(__file__), "commands") ) def cli(): pass .. _aliases: Command Aliases --------------- Many tools support aliases for commands. For example, you can configure ``git`` to accept ``git ci`` as alias for ``git commit``. Other tools also support auto-discovery for aliases by automatically shortening them. It's possible to customize :class:`Group` to provide this functionality. As explained in :ref:`custom-groups`, a group provides two methods: :meth:`~Group.list_commands` and :meth:`~Group.get_command`. In this particular case, you only need to override the latter as you generally don't want to enumerate the aliases on the help page in order to avoid confusion. The following example implements a subclass of :class:`Group` that accepts a prefix for a command. If there was a command called ``push``, it would accept ``pus`` as an alias (so long as it was unique): .. click:example:: class AliasedGroup(click.Group): def get_command(self, ctx, cmd_name): rv = super().get_command(ctx, cmd_name) if rv is not None: return rv matches = [ x for x in self.list_commands(ctx) if x.startswith(cmd_name) ] if not matches: return None if len(matches) == 1: return click.Group.get_command(self, ctx, matches[0]) ctx.fail(f"Too many matches: {', '.join(sorted(matches))}") def resolve_command(self, ctx, args): # always return the full command name _, cmd, args = super().resolve_command(ctx, args) return cmd.name, cmd, args It can be used like this: .. click:example:: @click.group(cls=AliasedGroup) def cli(): pass @cli.command def push(): pass @cli.command def pop(): pass See the `alias example`_ in Click's repository for another example. .. _alias example: https://github.com/pallets/click/tree/main/examples/aliases asyncclick-8.3.0.5-async/docs/faqs.md000066400000000000000000000021601507140761400173330ustar00rootroot00000000000000# Frequently Asked Questions ```{contents} :depth: 2 :local: true ``` ## General ### Shell Variable Expansion On Windows I have a simple Click app : ``` import click @click.command() @click.argument('message') def main(message: str): click.echo(message) if __name__ == '__main__': main() ``` When you pass an environment variable in the argument, it expands it: ```{code-block} powershell > Desktop python foo.py '$M0/.viola/2025-01-25-17-20-23-307878' > M:/home/ramrachum/.viola/2025-01-25-17-20-23-307878 > ``` Note that I used single quotes above, so my shell is not expanding the environment variable, Click does. How do I get Click to not expand it? #### Answer If you don't want Click to emulate (as best it can) unix expansion on Windows, pass windows_expand_args=False when calling the CLI. Windows command line doesn't do any *, ~, or $ENV expansion. It also doesn't distinguish between double quotes and single quotes (where the later means "don't expand here"). Click emulates the expansion so that the app behaves similarly on both platforms, but doesn't receive information about what quotes were used. asyncclick-8.3.0.5-async/docs/handling-files.rst000066400000000000000000000072651507140761400215100ustar00rootroot00000000000000.. _handling-files: Handling Files ================ .. currentmodule:: click Click has built in features to support file and file path handling. The examples use arguments but the same principle applies to options as well. .. _file-args: File Arguments ----------------- Click supports working with files with the :class:`File` type. Some notable features are: * Support for ``-`` to mean a special file that refers to stdin when used for reading, and stdout when used for writing. This is a common pattern for POSIX command line utilities. * Deals with ``str`` and ``bytes`` correctly for all versions of Python. Example: .. click:example:: @click.command() @click.argument('input', type=click.File('rb')) @click.argument('output', type=click.File('wb')) def inout(input, output): """Copy contents of INPUT to OUTPUT.""" while True: chunk = input.read(1024) if not chunk: break output.write(chunk) And from the command line: .. click:run:: with isolated_filesystem(): invoke(inout, args=['-', 'hello.txt'], input=['hello'], terminate_input=True) invoke(inout, args=['hello.txt', '-']) File Path Arguments ---------------------- For handling paths, the :class:`Path` type is better than a ``str``. Some notable features are: * The ``exists`` argument will verify whether the path exists. * ``readable``, ``writable``, and ``executable`` can perform permission checks. * ``file_okay`` and ``dir_okay`` allow specifying whether files/directories are accepted. * Error messages are nicely formatted using :func:`format_filename` so any undecodable bytes will be printed nicely. See :class:`Path` for all features. Example: .. click:example:: @click.command() @click.argument('filename', type=click.Path(exists=True)) def touch(filename): """Print FILENAME if the file exists.""" click.echo(click.format_filename(filename)) And from the command line: .. click:run:: with isolated_filesystem(): with open('hello.txt', 'w') as f: f.write('Hello World!\n') invoke(touch, args=['hello.txt']) println() invoke(touch, args=['missing.txt']) File Opening Behaviors ----------------------------- The :class:`File` type attempts to be "intelligent" about when to open a file. Stdin/stdout and files opened for reading will be opened immediately. This will give the user direct feedback when a file cannot be opened. Files opened for writing will only be open on the first IO operation. This is done by automatically wrapping the file in a special wrapper. File open behavior can be controlled by the boolean kwarg ``lazy``. If a file is opened lazily: * A failure at first IO operation will happen by raising an :exc:`FileError`. * It can help minimize resource handling confusion. If a file is opened in lazy mode, it will call :meth:`LazyFile.close_intelligently` to help figure out if the file needs closing or not. This is not needed for parameters, but is necessary for manually prompting. For manual prompts with the :func:`prompt` function you do not know if a stream like stdout was opened (which was already open before) or a real file was opened (that needs closing). Since files opened for writing will typically empty the file, the lazy mode should only be disabled if the developer is absolutely sure that this is intended behavior. It is also possible to open files in atomic mode by passing ``atomic=True``. In atomic mode, all writes go into a separate file in the same folder, and upon completion, the file will be moved over to the original location. This is useful if a file regularly read by other users is modified. asyncclick-8.3.0.5-async/docs/index.rst000066400000000000000000000056471507140761400177350ustar00rootroot00000000000000.. rst-class:: hide-header .. image:: _static/click-logo.png Welcome to the AsyncClick Documentation ======================================= .. image:: _static/click-name.svg :align: center :height: 200px AsyncClick is a fork of Click that works well with (some) async frameworks. Supported: asyncio, trio, and curio. Click, in turn, is a Python package for creating beautiful command line interfaces in a composable way with as little code as necessary. It's the "Command Line Interface Creation Kit". It's highly configurable but comes with sensible defaults out of the box. It aims to make the process of writing command line tools quick and fun while also preventing any frustration caused by the inability to implement an intended CLI API. Click in three points: - arbitrary nesting of commands - automatic help page generation - supports lazy loading of subcommands at runtime What does it look like? Here is an example of a simple Click program: .. click:example:: import asyncclick as click import anyio @click.command() @click.option('--count', default=1, help='Number of greetings.') @click.option('--name', prompt='Your name', help='The person to greet.') async def hello(count, name): """Simple program that greets NAME for a total of COUNT times.""" for x in range(count): if x: await anyio.sleep(0.1) click.echo(f"Hello {name}!") if __name__ == '__main__': hello() And what it looks like when run: .. click:run:: invoke(hello, ['--count=3'], prog_name='python hello.py', input='John\n') It automatically generates nicely formatted help pages: .. click:run:: invoke(hello, ['--help'], prog_name='python hello.py') You can get the library directly from PyPI:: pip install asyncclick Documentation ============== .. toctree:: :maxdepth: 2 faqs Tutorials ------------ .. toctree:: :maxdepth: 1 quickstart virtualenv How to Guides --------------- .. toctree:: :maxdepth: 1 entry-points setuptools support-multiple-versions Conceptual Guides ------------------- .. toctree:: :maxdepth: 1 why click-concepts General Reference -------------------- .. toctree:: :maxdepth: 1 parameters parameter-types options option-decorators arguments commands-and-groups commands documentation prompts handling-files advanced complex extending-click testing utils shell-completion exceptions unicode-support wincmd API Reference ------------------- .. toctree:: :maxdepth: 2 api About Project =============== * This documentation is structured according to `Diataxis `_ * `Version Policy `_ * `Contributing `_ * `Donate `_ .. toctree:: :maxdepth: 1 contrib license changes asyncclick-8.3.0.5-async/docs/license.rst000066400000000000000000000001421507140761400202310ustar00rootroot00000000000000BSD-3-Clause License ==================== .. literalinclude:: ../LICENSE.txt :language: text asyncclick-8.3.0.5-async/docs/option-decorators.rst000066400000000000000000000042401507140761400222650ustar00rootroot00000000000000Options Shortcut Decorators =========================== .. currentmodule:: click For convenience commonly used combinations of options arguments are available as their own decorators. .. contents:: :depth: 2 :local: Password Option ------------------ Click supports hidden prompts and asking for confirmation. This is useful for password input: .. click:example:: import codecs @click.command() @click.option( "--password", prompt=True, hide_input=True, confirmation_prompt=True ) def encode(password): click.echo(f"encoded: {codecs.encode(password, 'rot13')}") .. click:run:: invoke(encode, input=['secret', 'secret']) Because this combination of parameters is quite common, this can also be replaced with the :func:`password_option` decorator: .. code-block:: python @click.command() @click.password_option() def encrypt(password): click.echo(f"encoded: to {codecs.encode(password, 'rot13')}") Confirmation Option -------------------- For dangerous operations, it's very useful to be able to ask a user for confirmation. This can be done by adding a boolean ``--yes`` flag and asking for confirmation if the user did not provide it and to fail in a callback: .. click:example:: def abort_if_false(ctx, param, value): if not value: ctx.abort() @click.command() @click.option('--yes', is_flag=True, callback=abort_if_false, expose_value=False, prompt='Are you sure you want to drop the db?') def dropdb(): click.echo('Dropped all tables!') And what it looks like on the command line: .. click:run:: invoke(dropdb, input=['n']) invoke(dropdb, args=['--yes']) Because this combination of parameters is quite common, this can also be replaced with the :func:`confirmation_option` decorator: .. click:example:: @click.command() @click.confirmation_option(prompt='Are you sure you want to drop the db?') def dropdb(): click.echo('Dropped all tables!') Version Option ---------------- :func:`version_option` adds a ``--version`` option which immediately prints the version number and exits the program. asyncclick-8.3.0.5-async/docs/options.md000066400000000000000000000342671507140761400201110ustar00rootroot00000000000000(options)= # Options ```{eval-rst} .. currentmodule:: click ``` Adding options to commands can be accomplished with the {func}`option` decorator. At runtime the decorator invokes the {class}`Option` class. Options in Click are distinct from {ref}`positional arguments `. Useful and often used kwargs are: - `default`: Passes a default. - `help`: Sets help message. - `nargs`: Sets the number of arguments. - `required`: Makes option required. - `type`: Sets {ref}`parameter type ` ```{contents} :depth: 2 :local: true ``` ## Option Decorator Click expects you to pass at least two positional arguments to the option decorator. They are option name and function argument name. ```{eval-rst} .. click:example:: @click.command() @click.option('--string-to-echo', 'string_to_echo') def echo(string_to_echo): click.echo(string_to_echo) .. click:run:: invoke(echo, args=['--help']) ``` However, if you don't pass in the function argument name, then Click will try to infer it. A simple way to name your option is by taking the function argument, adding two dashes to the front and converting underscores to dashes. In this case, Click will infer the function argument name correctly so you can add only the option name. ```{eval-rst} .. click:example:: @click.command() @click.option('--string-to-echo') def echo(string_to_echo): click.echo(string_to_echo) .. click:run:: invoke(echo, args=['--string-to-echo', 'Hi!']) ``` More formally, Click will try to infer the function argument name by: 1. If a positional argument name does not have a prefix, it is chosen. 2. If a positional argument name starts with with two dashes, the first one given is chosen. 3. The first positional argument prefixed with one dash is chosen otherwise. The chosen positional argument is converted to lower case, up to two dashes are removed from the beginning, and other dashes are converted to underscores to get the function argument name. ```{eval-rst} .. list-table:: Examples :widths: 15 10 :header-rows: 1 * - Decorator Arguments - Function Name * - ``"-f", "--foo-bar"`` - foo_bar * - ``"-x"`` - x * - ``"-f", "--filename", "dest"`` - dest * - ``"--CamelCase"`` - camelcase * - ``"-f", "-fb"`` - f * - ``"--f", "--foo-bar"`` - f * - ``"---f"`` - _f ``` ## Basic Example A simple {class}`click.Option` takes one argument. This will assume the argument is not required. If the decorated function takes an positional argument then None is passed it. This will also assume the type is `str`. ```{eval-rst} .. click:example:: @click.command() @click.option('--text') def print_this(text): click.echo(text) .. click:run:: invoke(print_this, args=['--text=this']) invoke(print_this, args=[]) .. click:run:: invoke(print_this, args=['--help']) ``` ## Setting a Default Instead of setting the `type`, you may set a default and Click will try to infer the type. ```{eval-rst} .. click:example:: @click.command() @click.option('--n', default=1) def dots(n): click.echo('.' * n) .. click:run:: invoke(dots, args=['--help']) ``` ## Multi Value Options To make an option take multiple values, pass in `nargs`. Note only a fixed number of arguments is supported. The values are passed to the underlying function as a tuple. ```{eval-rst} .. click:example:: @click.command() @click.option('--pos', nargs=2, type=float) def findme(pos): a, b = pos click.echo(f"{a} / {b}") .. click:run:: invoke(findme, args=['--pos', '2.0', '3.0']) ``` (tuple-type)= ## Multi Value Options as Tuples ```{versionadded} 4.0 ``` As you can see that by using `nargs` set to a specific number each item in the resulting tuple is of the same type. This might not be what you want. Commonly you might want to use different types for different indexes in the tuple. For this you can directly specify a tuple as type: ```{eval-rst} .. click:example:: @click.command() @click.option('--item', type=(str, int)) def putitem(item): name, id = item click.echo(f"name={name} id={id}") And on the command line: .. click:run:: invoke(putitem, args=['--item', 'peter', '1338']) ``` By using a tuple literal as type, `nargs` gets automatically set to the length of the tuple and the {class}`click.Tuple` type is automatically used. The above example is thus equivalent to this: ```{eval-rst} .. click:example:: @click.command() @click.option('--item', nargs=2, type=click.Tuple([str, int])) def putitem(item): name, id = item click.echo(f"name={name} id={id}") ``` (multiple-options)= ## Multiple Options The multiple options format allows you to call the underlying function multiple times with one command line entry. If set, the default must be a list or tuple. Setting a string as a default will be interpreted as list of characters. ```{eval-rst} .. click:example:: @click.command() @click.option('--message', '-m', multiple=True) def commit(message): click.echo('\n'.join(message)) .. click:run:: invoke(commit, args=['-m', 'foo', '-m', 'bar', '-m', 'here']) ``` ## Counting To count the occurrence of an option pass in `count=True`. If the option is not passed in, then the count is 0. Counting is commonly used for verbosity. ```{eval-rst} .. click:example:: @click.command() @click.option('-v', '--verbose', count=True) def log(verbose): click.echo(f"Verbosity: {verbose}") .. click:run:: invoke(log, args=[]) invoke(log, args=['-vvv']) ``` (option-boolean-flag)= ## Boolean Boolean options (boolean flags) take the value True or False. The simplest case sets the default value to `False` if the flag is not passed, and `True` if it is. ```{eval-rst} .. click:example:: import sys @click.command() @click.option('--shout', is_flag=True) def info(shout): rv = sys.platform if shout: rv = rv.upper() + '!!!!111' click.echo(rv) .. click:run:: invoke(info) invoke(info, args=['--shout']) ``` To implement this more explicitly, pass in on-option `/` off-option. Click will automatically set `is_flag=True`. Click always wants you to provide an enable and disable flag so that you can change the default later. ```{eval-rst} .. click:example:: import sys @click.command() @click.option('--shout/--no-shout', default=False) def info(shout): rv = sys.platform if shout: rv = rv.upper() + '!!!!111' click.echo(rv) .. click:run:: invoke(info) invoke(info, args=['--shout']) invoke(info, args=['--no-shout']) ``` If a forward slash(`/`) is contained in your option name already, you can split the parameters using `;`. In Windows `/` is commonly used as the prefix character. ```{eval-rst} .. click:example:: @click.command() @click.option('/debug;/no-debug') def log(debug): click.echo(f"debug={debug}") ``` ```{versionchanged} 6.0 ``` If you want to define an alias for the second option only, then you will need to use leading whitespace to disambiguate the format string. ```{eval-rst} .. click:example:: import sys @click.command() @click.option('--shout/--no-shout', ' /-N', default=False) def info(shout): rv = sys.platform if shout: rv = rv.upper() + '!!!!111' click.echo(rv) .. click:run:: invoke(info, args=['--help']) ``` ## Flag Value To have an flag pass a value to the underlying function set `flag_value`. This automatically sets `is_flag=True`. To mark the flag as default, set `default=True`. Setting flag values can be used to create patterns like this: ```{eval-rst} .. click:example:: import sys @click.command() @click.option('--upper', 'transformation', flag_value='upper', default=True) @click.option('--lower', 'transformation', flag_value='lower') def info(transformation): click.echo(getattr(sys.platform, transformation)()) .. click:run:: invoke(info, args=['--help']) invoke(info, args=['--upper']) invoke(info, args=['--lower']) invoke(info) ``` ````{note} The `default` value is given to the underlying function as-is. So if you set `default=None`, the value passed to the function is the `None` Python value. Same for any other type. But there is a special case for flags. If a flag has a `flag_value`, then setting `default=True` is interpreted as *the flag should be activated by default*. So instead of the underlying function receiving the `True` Python value, it will receive the `flag_value`. Which means, in example above, this option: ```python @click.option('--upper', 'transformation', flag_value='upper', default=True) ``` is equivalent to: ```python @click.option('--upper', 'transformation', flag_value='upper', default='upper') ``` Because the two are equivalent, it is recommended to always use the second form, and set `default` to the actual value you want to pass. And not use the special `True` case. This makes the code more explicit and predictable. ```` ## Values from Environment Variables To pass in a value in from a specific environment variable use `envvar`. ```{eval-rst} .. click:example:: @click.command() @click.option('--username', envvar='USERNAME') def greet(username): click.echo(f"Hello {username}!") .. click:run:: invoke(greet, env={'USERNAME': 'john'}) ``` If a list is passed to `envvar`, the first environment variable found is picked. ```{eval-rst} .. click:example:: @click.command() @click.option('--username', envvar=['ALT_USERNAME', 'USERNAME']) def greet(username): click.echo(f"Hello {username}!") .. click:run:: invoke(greet, env={'ALT_USERNAME': 'Bill', 'USERNAME': 'john'}) ``` Variable names are: - [Case-insensitive on Windows but not on other platforms](https://github.com/python/cpython/blob/aa9eb5f757ceff461e6e996f12c89e5d9b583b01/Lib/os.py#L777-L789). - Not stripped of whitespaces and should match the exact name provided to the `envvar` argument. For flag options, there is two concepts to consider: the activation of the flag driven by the environment variable, and the value of the flag if it is activated. The environment variable need to be interpreted, because values read from them are always strings. We need to transform these strings into boolean values that will determine if the flag is activated or not. Here are the rules used to parse environment variable values for flag options: - `true`, `1`, `yes`, `on`, `t`, `y` are interpreted as activating the flag - `false`, `0`, `no`, `off`, `f`, `n` are interpreted as deactivating the flag - The presence of the environment variable without value is interpreted as deactivating the flag - Empty strings are interpreted as deactivating the flag - Values are case-insensitive, so the `True`, `TRUE`, `tRuE` strings are all activating the flag - Values are stripped of leading and trailing whitespaces before being interpreted, so the `" True "` string is transformed to `"true"` and so activates the flag - If the flag option has a `flag_value` argument, passing that value in the environment variable will activate the flag, in addition to all the cases described above - Any other value is interpreted as deactivating the flag ```{caution} For boolean flags with a pair of values, the only recognized environment variable is the one provided to the `envvar` argument. So an option defined as `--flag\--no-flag`, with a `envvar="FLAG"` parameter, there is no magical `NO_FLAG=` variable that is recognized. Only the `FLAG=` environment variable is recognized. ``` Once the status of the flag has been determine to be activated or not, the `flag_value` is used as the value of the flag if it is activated. If the flag is not activated, the value of the flag is set to `None` by default. ## Multiple Options from Environment Values As options can accept multiple values, pulling in such values from environment variables (which are strings) is a bit more complex. The way Click solves this is by leaving it up to the type to customize this behavior. For both `multiple` and `nargs` with values other than `1`, Click will invoke the {meth}`ParamType.split_envvar_value` method to perform the splitting. The default implementation for all types is to split on whitespace. The exceptions to this rule are the {class}`File` and {class}`Path` types which both split according to the operating system's path splitting rules. On Unix systems like Linux and OS X, the splitting happens on every colon (`:`), and for Windows, splitting on every semicolon (`;`). ```{eval-rst} .. click:example:: @click.command() @click.option('paths', '--path', envvar='PATHS', multiple=True, type=click.Path()) def perform(paths): for path in paths: click.echo(path) if __name__ == '__main__': perform() .. click:run:: import os invoke(perform, env={"PATHS": f"./foo/bar{os.path.pathsep}./test"}) ``` ## Other Prefix Characters Click can deal with prefix characters besides `-` for options. Click can use `/`, `+` as well as others. Note that alternative prefix characters are generally used very sparingly if at all within POSIX. ```{eval-rst} .. click:example:: @click.command() @click.option('+w/-w') def chmod(w): click.echo(f"writable={w}") .. click:run:: invoke(chmod, args=['+w']) invoke(chmod, args=['-w']) ``` There are special considerations for using `/` as prefix character, see {ref}`option-boolean-flag` for more. (optional-value)= ## Optional Value Providing the value to an option can be made optional, in which case providing only the option's flag without a value will either show a prompt or use its `flag_value`. Setting `is_flag=False, flag_value=value` tells Click that the option can still be passed a value, but if only the flag is given, the value will be `flag_value`. ```{eval-rst} .. click:example:: @click.command() @click.option("--name", is_flag=False, flag_value="Flag", default="Default") def hello(name): click.echo(f"Hello, {name}!") .. click:run:: invoke(hello, args=[]) invoke(hello, args=["--name", "Value"]) invoke(hello, args=["--name"]) ``` asyncclick-8.3.0.5-async/docs/parameter-types.rst000066400000000000000000000132771507140761400217460ustar00rootroot00000000000000.. _parameter-types: Parameter Types ================== .. currentmodule:: click When the parameter type is set using ``type``, Click will leverage the type to make your life easier, for example adding data to your help pages. Most examples are done with options, but types are available to options and arguments. .. contents:: :depth: 2 :local: Built-in Types Examples ------------------------ .. _choice-opts: Choice ^^^^^^^^^^^^^^^^^^^^^^ Sometimes, you want to have a parameter be a choice of a list of values. In that case you can use :class:`Choice` type. It can be instantiated with a list of valid values. The originally passed choice will be returned, not the str passed on the command line. Token normalization functions and ``case_sensitive=False`` can cause the two to be different but still match. :meth:`Choice.normalize_choice` for more info. Example: .. click:example:: import enum class HashType(enum.Enum): MD5 = enum.auto() SHA1 = enum.auto() @click.command() @click.option('--hash-type', type=click.Choice(HashType, case_sensitive=False)) def digest(hash_type: HashType): click.echo(hash_type) What it looks like: .. click:run:: invoke(digest, args=['--hash-type=MD5']) println() invoke(digest, args=['--hash-type=md5']) println() invoke(digest, args=['--hash-type=foo']) println() invoke(digest, args=['--help']) Any iterable may be passed to :class:`Choice`. If an ``Enum`` is passed, the names of the enum members will be used as valid choices. Choices work with options that have ``multiple=True``. If a ``default`` value is given with ``multiple=True``, it should be a list or tuple of valid choices. Choices should be unique after normalization, see :meth:`Choice.normalize_choice` for more info. .. versionchanged:: 7.1 The resulting value from an option will always be one of the originally passed choices regardless of ``case_sensitive``. .. _ranges: Int and Float Ranges ^^^^^^^^^^^^^^^^^^^^^^^ The :class:`IntRange` type extends the :data:`INT` type to ensure the value is contained in the given range. The :class:`FloatRange` type does the same for :data:`FLOAT`. If ``min`` or ``max`` is omitted, that side is *unbounded*. Any value in that direction is accepted. By default, both bounds are *closed*, which means the boundary value is included in the accepted range. ``min_open`` and ``max_open`` can be used to exclude that boundary from the range. If ``clamp`` mode is enabled, a value that is outside the range is set to the boundary instead of failing. For example, the range ``0, 5`` would return ``5`` for the value ``10``, or ``0`` for the value ``-1``. When using :class:`FloatRange`, ``clamp`` can only be enabled if both bounds are *closed* (the default). .. click:example:: @click.command() @click.option("--count", type=click.IntRange(0, 20, clamp=True)) @click.option("--digit", type=click.IntRange(0, 9)) def repeat(count, digit): click.echo(str(digit) * count) .. click:run:: invoke(repeat, args=['--count=100', '--digit=5']) invoke(repeat, args=['--count=6', '--digit=12']) Built-in Types Listing ----------------------- The supported parameter :ref:`click-api-types` are: * ``str`` / :data:`click.STRING`: The default parameter type which indicates unicode strings. * ``int`` / :data:`click.INT`: A parameter that only accepts integers. * ``float`` / :data:`click.FLOAT`: A parameter that only accepts floating point values. * ``bool`` / :data:`click.BOOL`: A parameter that accepts boolean values. This is automatically used for boolean flags. The string values "1", "true", "t", "yes", "y", and "on" convert to ``True``. "0", "false", "f", "no", "n", and "off" convert to ``False``. * :data:`click.UUID`: A parameter that accepts UUID values. This is not automatically guessed but represented as :class:`uuid.UUID`. * .. autoclass:: Choice :noindex: * .. autoclass:: DateTime :noindex: * .. autoclass:: File :noindex: * .. autoclass:: FloatRange :noindex: * .. autoclass:: IntRange :noindex: * .. autoclass:: Path :noindex: How to Implement Custom Types ------------------------------- 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. The following code implements an integer type that accepts hex and octal numbers in addition to normal integers, and converts them into regular integers. .. code-block:: python import click class BasedIntParamType(click.ParamType): name = "integer" def convert(self, value, param, ctx): if isinstance(value, int): return value try: if value[:2].lower() == "0x": return int(value[2:], 16) elif value[:1] == "0": return int(value, 8) return int(value, 10) except ValueError: self.fail(f"{value!r} is not a valid integer", param, ctx) BASED_INT = BasedIntParamType() The :attr:`~ParamType.name` attribute is optional and is used for documentation. Call :meth:`~ParamType.fail` if conversion fails. The ``param`` and ``ctx`` arguments may be ``None`` in some cases such as prompts. Values from user input or the command line will be strings, but default values and Python arguments may already be the correct type. The custom type should check at the top if the value is already valid and pass it through to support those cases. asyncclick-8.3.0.5-async/docs/parameters.md000066400000000000000000000037461507140761400205570ustar00rootroot00000000000000(parameters)= # Parameters ```{currentmodule} click ``` Click supports only two principle types of parameters for scripts (by design): options and arguments. ## Options - Are optional. - Recommended to use for everything except subcommands, urls, or files. - Can take a fixed number of arguments. The default is 1. They may be specified multiple times using {ref}`multiple-options`. - Are fully documented by the help page. - Have automatic prompting for missing input. - Can act as flags (boolean or otherwise). - Can be pulled from environment variables. ## Arguments - Are optional with in reason, but not entirely so. - Recommended to use for subcommands, urls, or files. - Can take an arbitrary number of arguments. - Are not fully documented by the help page since they may be too specific to be automatically documented. For more see {ref}`documenting-arguments`. - Can be pulled from environment variables but only explicitly named ones. For more see {ref}`environment-variables`. On each principle type you can specify {ref}`parameter-types`. Specifying these types helps Click add details to your help pages and help with the handling of those types. (parameter-names)= ## Parameter Names Parameters (options and arguments) have a name that will be used as the Python argument name when calling the decorated function with values. In the 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`. The option's names are `-t` and `--times`. More names are available for options and are covered in {ref}`options`. ```{eval-rst} .. click:example:: @click.command() @click.argument('filename') @click.option('-t', '--times', type=int) def multi_echo(filename, times): """Print value filename multiple times.""" for x in range(times): click.echo(filename) .. click:run:: invoke(multi_echo, ['--times=3', 'index.txt'], prog_name='multi_echo') ``` asyncclick-8.3.0.5-async/docs/prompts.md000066400000000000000000000122271507140761400201120ustar00rootroot00000000000000# User Input Prompts ```{currentmodule} click ``` Click supports prompts in two different places. The first is automated prompts when the parameter handling happens, and the second is to ask for prompts at a later point independently. This can be accomplished with the {func}`prompt` function, which asks for valid input according to a type, or the {func}`confirm` function, which asks for confirmation (yes/no). ```{contents} --- depth: 2 local: true --- ``` ## AsyncClick changes AsyncClick now async-izes :func:`asyncclick.prompt`. This may require changes in your program. We are sorry to have to do this in a minor release, but there is no way around this change because the validation callback might be async. On the positive side, :func:`asyncclick.prompt` gained a new parameter ``blocking``. When it is set to `False`, interaction with the user no longer blocks the async event loop. However, this currently interacts badly with interrupting the program, e.g. by pressing Control-C. As most programs prompt the user first and run async tasks later, the default for ``blocking`` is `True` until we can solve the interrupt problem. (option-prompting)= ## Option Prompts Option prompts are integrated into the option interface. Internally, it automatically calls either {func}`prompt` or {func}`confirm` as necessary. In some cases, you want parameters that can be provided from the command line, but if not provided, ask for user input instead. This can be implemented with Click by defining a prompt string. Example: ```{eval-rst} .. click:example:: @click.command() @click.option('--name', prompt=True) def hello(name): click.echo(f"Hello {name}!") And what it looks like: .. click:run:: invoke(hello, args=['--name=John']) invoke(hello, input=['John']) ``` If you are not happy with the default prompt string, you can ask for a different one: ```{eval-rst} .. click:example:: @click.command() @click.option('--name', prompt='Your name please') def hello(name): click.echo(f"Hello {name}!") What it looks like: .. click:run:: invoke(hello, input=['John']) ``` It is advised that prompt not be used in conjunction with the multiple flag set to True. Instead, prompt in the function interactively. By default, the user will be prompted for an input if one was not passed through the command line. To turn this behavior off, see {ref}`optional-value`. ## Input Prompts To manually ask for user input, you can use the {func}`prompt` function. By default, it accepts any Unicode string, but you can ask for any other type. For instance, you can ask for a valid integer: ```python value = await click.prompt('Please enter a valid integer', type=int) ``` Additionally, the type will be determined automatically if a default value is provided. For instance, the following will only accept floats: ```python value = await click.prompt('Please enter a number', default=42.0) ``` ## Optional Prompts If the option has `prompt` enabled, then setting `prompt_required=False` tells Click to only show the prompt if the option's flag is given, instead of if the option is not provided at all. ```{eval-rst} .. click:example:: @click.command() @click.option('--name', prompt=True, prompt_required=False, default="Default") def hello(name): click.echo(f"Hello {name}!") .. click:run:: invoke(hello) invoke(hello, args=["--name", "Value"]) invoke(hello, args=["--name"], input="Prompt") ``` If `required=True`, then the option will still prompt if it is not given, but it will also prompt if only the flag is given. ## Confirmation Prompts To ask if a user wants to continue with an action, the {func}`confirm` function comes in handy. By default, it returns the result of the prompt as a boolean value: ```python if click.confirm('Do you want to continue?'): click.echo('Well done!') ``` There is also the option to make the function automatically abort the execution of the program if it does not return `True`: ```python click.confirm('Do you want to continue?', abort=True) ``` ## Dynamic Defaults for Prompts The `auto_envvar_prefix` and `default_map` options for the context allow the program to read option values from the environment or a configuration file. However, this overrides the prompting mechanism, so that the user does not get the option to change the value interactively. If you want to let the user configure the default value, but still be prompted if the option isn't specified on the command line, you can do so by supplying a callable as the default value. For example, to get a default from the environment: ```python import os @click.command() @click.option( "--username", prompt=True, default=lambda: os.environ.get("USER", "") ) def hello(username): click.echo(f"Hello, {username}!") ``` To describe what the default value will be, set it in ``show_default``. ```{eval-rst} .. click:example:: import os @click.command() @click.option( "--username", prompt=True, default=lambda: os.environ.get("USER", ""), show_default="current user" ) def hello(username): click.echo(f"Hello, {username}!") .. click:run:: invoke(hello, args=["--help"]) ``` asyncclick-8.3.0.5-async/docs/quickstart.md000066400000000000000000000154241507140761400206020ustar00rootroot00000000000000# Quickstart ```{currentmodule} click ``` ## Install Install from PyPI: ```console pip install click ``` Installing into a virtual environment is highly recommended. We suggest {ref}`virtualenv-heading`. ## Examples 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. - [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. - [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. - [naval](https://github.com/pallets/click/tree/main/examples/naval) : Port of the [docopt](http://docopt.org/) naval example. - [colors](https://github.com/pallets/click/tree/main/examples/colors) : A simple example that colorizes text. Uses colorama on Windows. - [aliases](https://github.com/pallets/click/tree/main/examples/aliases) : An advanced example that implements {ref}`aliases`. - [imagepipe](https://github.com/pallets/click/tree/main/examples/imagepipe) : A complex example that implements some {ref}`command-pipelines` . It chains together image processing instructions. Requires pillow. - [repo](https://github.com/pallets/click/tree/main/examples/repo) : An advanced example that implements a Git-/Mercurial-like command line interface. - [complex](https://github.com/pallets/click/tree/main/examples/complex) : A very advanced example that implements loading subcommands dynamically from a plugin folder. - [termui](https://github.com/pallets/click/tree/main/examples/termui) : A simple example that showcases terminal UI helpers provided by click. ## Basic Concepts - Creating a Command Click is based on declaring commands through decorators. Internally, there is a non-decorator interface for advanced use cases, but it's discouraged for high-level usage. A function becomes a Click command line tool by decorating it through {func}`command`. At its simplest, just decorating a function with this decorator will make it into a callable script: ```{eval-rst} .. click:example:: import click @click.command() def hello(): click.echo('Hello World!') What's happening is that the decorator converts the function into a :class:`Command` which then can be invoked: .. click:example:: if __name__ == '__main__': hello() And what it looks like: .. click:run:: invoke(hello, args=[], prog_name='python hello.py') And the corresponding help page: .. click:run:: invoke(hello, args=['--help'], prog_name='python hello.py') ``` ## Echoing Why does this example use {func}`echo` instead of the regular {func}`print` function? The answer to this question is that Click attempts to support different environments consistently and to be very robust even when the environment is misconfigured. Click wants to be functional at least on a basic level even if everything is completely broken. What this means is that the {func}`echo` function applies some error correction in case the terminal is misconfigured instead of dying with a {exc}`UnicodeError`. The echo function also supports color and other styles in output. It will automatically remove styles if the output stream is a file. On Windows, colorama is automatically installed and used. See {ref}`ansi-colors`. If you don't need this, you can also use the `print()` construct / function. ## Nesting Commands Commands can be attached to other commands of type {class}`Group`. This allows arbitrary nesting of scripts. As an example here is a script that implements two commands for managing databases: ```{eval-rst} .. click:example:: @click.group() def cli(): pass @click.command() def initdb(): click.echo('Initialized the database') @click.command() def dropdb(): click.echo('Dropped the database') cli.add_command(initdb) cli.add_command(dropdb) ``` As you can see, the {func}`group` decorator works like the {func}`command` decorator, but creates a {class}`Group` object instead which can be given multiple subcommands that can be attached with {meth}`Group.add_command`. For simple scripts, it's also possible to automatically attach and create a command by using the {meth}`Group.command` decorator instead. The above script can instead be written like this: ```{eval-rst} .. click:example:: @click.group() def cli(): pass @cli.command() def initdb(): click.echo('Initialized the database') @cli.command() def dropdb(): click.echo('Dropped the database') You would then invoke the :class:`Group` in your entry points or other invocations: .. click:example:: if __name__ == '__main__': cli() ``` ## Registering Commands Later Instead of using the `@group.command()` decorator, commands can be decorated with the plain `@command()` decorator and registered with a group later with `group.add_command()`. This could be used to split commands into multiple Python modules. ```{code-block} python @click.command() def greet(): click.echo("Hello, World!") ``` ```{code-block} python @click.group() def group(): pass group.add_command(greet) ``` ## Adding Parameters To add parameters, use the {func}`option` and {func}`argument` decorators: ```{eval-rst} .. click:example:: @click.command() @click.option('--count', default=1, help='number of greetings') @click.argument('name') def hello(count, name): for x in range(count): click.echo(f"Hello {name}!") What it looks like: .. click:run:: invoke(hello, args=['--help'], prog_name='python hello.py') ``` ## Switching to Entry Points In the code you wrote so far there is a block at the end of the file which looks like this: `if __name__ == '__main__':`. This is traditionally how a standalone Python file looks like. With Click you can continue doing that, but a better way is to package your app with an entry point. There are two main (and many more) reasons for this: The first one is that installers automatically generate executable wrappers for Windows so your command line utilities work on Windows too. The second reason is that entry point scripts work with virtualenv on Unix without the virtualenv having to be activated. This is a very useful concept which allows you to bundle your scripts with all requirements into a virtualenv. Click is perfectly equipped to work with that and in fact the rest of the documentation will assume that you are writing applications as distributed packages. Look at the {doc}`entry-points` chapter before reading the rest as the examples assume that you will be using entry points. asyncclick-8.3.0.5-async/docs/setuptools.md000066400000000000000000000001161507140761400206210ustar00rootroot00000000000000--- orphan: true --- # Setuptools Integration Moved to {doc}`entry-points`. asyncclick-8.3.0.5-async/docs/shell-completion.md000066400000000000000000000222531507140761400216640ustar00rootroot00000000000000(shell-completion)= # Shell Completion ```{currentmodule} click.shell_completion ``` Click provides tab completion support for Bash (version 4.4 and up), Zsh, and Fish. It is possible to add support for other shells too, and suggestions can be customized at multiple levels. Shell completion suggests command names, option names, and values for choice, file, and path parameter types. Options are only listed if at least a dash has been entered. Hidden commands and options are not shown. ```console $ repo clone commit copy delete setuser $ repo clone - --deep --help --rev --shallow -r ``` ## Enabling Completion Completion is only available if a script is installed and invoked through an entry point, not through the `python` command. See {doc}`entry-points`. Once the executable is installed, calling it with a special environment variable will put Click in completion mode. To enable shell completion, the user needs to register a special function with their shell. The exact script varies depending on the shell you are using. Click will output it when called with `_{FOO_BAR}_COMPLETE` set to `{shell}_source`. `{FOO_BAR}` is the executable name in uppercase with dashes replaced by underscores. It is conventional but not strictly required for environment variable names to be in upper case. This convention helps distinguish environment variables from regular shell variables and commands, making scripts and configuration files more readable and easier to maintain. The built-in shells are `bash`, `zsh`, and `fish`. Provide your users with the following instructions customized to your program name. This uses `foo-bar` as an example. ```{eval-rst} .. tabs:: .. group-tab:: Bash Add this to ``~/.bashrc``: .. code-block:: bash eval "$(_FOO_BAR_COMPLETE=bash_source foo-bar)" .. group-tab:: Zsh Add this to ``~/.zshrc``: .. code-block:: zsh eval "$(_FOO_BAR_COMPLETE=zsh_source foo-bar)" .. group-tab:: Fish Add this to ``~/.config/fish/completions/foo-bar.fish``: .. code-block:: fish _FOO_BAR_COMPLETE=fish_source foo-bar | source This is the same file used for the activation script method below. For Fish it's probably always easier to use that method. ``` Using `eval` means that the command is invoked and evaluated every time a shell is started, which can delay shell responsiveness. To speed it up, write the generated script to a file, then source that. You can generate the files ahead of time and distribute them with your program to save your users a step. ```{eval-rst} .. tabs:: .. group-tab:: Bash Save the script somewhere. .. code-block:: bash _FOO_BAR_COMPLETE=bash_source foo-bar > ~/.foo-bar-complete.bash Source the file in ``~/.bashrc``. .. code-block:: bash . ~/.foo-bar-complete.bash .. group-tab:: Zsh Save the script somewhere. .. code-block:: bash _FOO_BAR_COMPLETE=zsh_source foo-bar > ~/.foo-bar-complete.zsh Source the file in ``~/.zshrc``. .. code-block:: bash . ~/.foo-bar-complete.zsh .. group-tab:: Fish Save the script to ``~/.config/fish/completions/foo-bar.fish``: .. code-block:: fish _FOO_BAR_COMPLETE=fish_source foo-bar > ~/.config/fish/completions/foo-bar.fish ``` After modifying the shell config, you need to start a new shell in order for the changes to be loaded. ## Custom Type Completion When creating a custom {class}`~click.ParamType`, override its {meth}`~click.ParamType.shell_complete` method to provide shell completion for parameters with the type. The method must return a list of {class}`~CompletionItem` objects. Besides the value, these objects hold metadata that shell support might use. The built-in implementations use `type` to indicate special handling for paths, and `help` for shells that support showing a help string next to a suggestion. In this example, the type will suggest environment variables that start with the incomplete value. ```python class EnvVarType(ParamType): name = "envvar" def shell_complete(self, ctx, param, incomplete): return [ CompletionItem(name) for name in os.environ if name.startswith(incomplete) ] @click.command() @click.option("--ev", type=EnvVarType()) def cli(ev): click.echo(os.environ[ev]) ``` ## Overriding Value Completion Value completions for a parameter can be customized without a custom type by providing a `shell_complete` function. The function is used instead of any completion provided by the type. It is passed 3 positional arguments: - `ctx` - The current command context. - `param` - The current parameter requesting completion. - `incomplete` - The partial word that is being completed. May be an empty string if no characters have been entered yet. It must return a list of {class}`CompletionItem` objects, or as a shortcut it can return a list of strings. In this example, the command will suggest environment variables that start with the incomplete value. ```python def complete_env_vars(ctx, param, incomplete): return [k for k in os.environ if k.startswith(incomplete)] @click.command() @click.argument("name", shell_complete=complete_env_vars) def cli(name): click.echo(f"Name: {name}") click.echo(f"Value: {os.environ[name]}") ``` ## Adding Support for a Shell Support can be added for shells that do not come built in. Be sure to check PyPI to see if there's already a package that adds support for your shell. This topic is very technical, you'll want to look at Click's source to study the built-in implementations. Shell support is provided by subclasses of {class}`ShellComplete` registered with {func}`add_completion_class`. When Click is invoked in completion mode, it calls {meth}`~ShellComplete.source` to output the completion script, or {meth}`~ShellComplete.complete` to output completions. The base class provides default implementations that require implementing some smaller parts. First, you'll need to figure out how your shell's completion system works and write a script to integrate it with Click. It must invoke your program with the environment variable `_{FOO_BAR}_COMPLETE` set to `{shell}_complete` and pass the complete args and incomplete value. How it passes those values, and the format of the completion response from Click is up to you. In your subclass, set {attr}`ShellComplete.source_template` to the completion script. The default implementation will perform `%` formatting with the following variables: - `complete_func` - A safe name for the completion function defined in the script. - `complete_var` - The environment variable name for passing the `{shell}_complete` instruction. - `foo_bar` - The name of the executable being completed. The example code is for a made up shell "My Shell" or "mysh" for short. ```python from click.shell_completion import add_completion_class from click.shell_completion import ShellComplete _mysh_source = """\ %(complete_func)s { response=$(%(complete_var)s=mysh_complete %(foo_bar)s) # parse response and set completions somehow } call-on-complete %(foo_bar)s %(complete_func)s """ @add_completion_class class MyshComplete(ShellComplete): name = "mysh" source_template = _mysh_source ``` Next, implement {meth}`~ShellComplete.get_completion_args`. This must get, parse, and return the complete args and incomplete value from the completion script. For example, for the Bash implementation the `COMP_WORDS` env var contains the command line args as a string, and the `COMP_CWORD` env var contains the index of the incomplete arg. The method must return a `(args, incomplete)` tuple. ```python import os from click.parser import split_arg_string class MyshComplete(ShellComplete): ... def get_completion_args(self): args = split_arg_string(os.environ["COMP_WORDS"]) if os.environ["COMP_PARTIAL"] == "1": incomplete = args.pop() return args, incomplete return args, "" ``` Finally, implement {meth}`~ShellComplete.format_completion`. This is called to format each {class}`CompletionItem` into a string. For example, the Bash implementation returns `f"{item.type},{item.value}` (it doesn't support help strings), and the Zsh implementation returns each part separated by a newline, replacing empty help with a `_` placeholder. This format is entirely up to what you parse with your completion script. The `type` value is usually `plain`, but it can be another value that the completion script can switch on. For example, `file` or `dir` can tell the shell to handle path completion, since the shell is better at that than Click. ```python class MyshComplete(ShellComplete): ... def format_completion(self, item): return f"{item.type}\t{item.value}" ``` With those three things implemented, the new shell support is ready. In case those weren't sufficient, there are more parts that can be overridden, but that probably isn't necessary. The activation instructions will again depend on how your shell works. Use the following to generate the completion script, then load it into the shell somehow. ```console _FOO_BAR_COMPLETE=mysh_source foo-bar ``` asyncclick-8.3.0.5-async/docs/support-multiple-versions.md000066400000000000000000000041051507140761400236150ustar00rootroot00000000000000# Supporting Multiple Versions If you are a library maintainer, you may want to support multiple versions of Click. See the Pallets [version policy] for information about our version numbers and support policy. [version policy]: https://palletsprojects.com/versions Most features of Click are stable across releases, and don't require special handling. However, feature releases may deprecate and change APIs. Occasionally, a change will require special handling. ## Use Feature Detection Prefer using feature detection. Looking at the version can be tempting, but is often more brittle or results in more complicated code. Try to use `if` or `try` blocks to decide whether to use a new or old pattern. If you do need to look at the version, use {func}`importlib.metadata.version`, the standardized way to get versions for any installed Python package. ## Changes in 8.2 ### `ParamType` methods require `ctx` In 8.2, several methods of `ParamType` now have a `ctx: click.Context` argument. Because this changes the signature of the methods from 8.1, it's not obvious how to support both when subclassing or calling. This example uses `ParamType.get_metavar`, and the same technique should be applicable to other methods such as `get_missing_message`. Update your methods overrides to take the new `ctx` argument. Use the following decorator to wrap each method. In 8.1, it will get the context where possible and pass it using the 8.2 signature. ```python import functools import typing as t import click F = t.TypeVar("F", bound=t.Callable[..., t.Any]) def add_ctx_arg(f: F) -> F: @functools.wraps(f) def wrapper(*args: t.Any, **kwargs: t.Any) -> t.Any: if "ctx" not in kwargs: kwargs["ctx"] = click.get_current_context(silent=True) return f(*args, **kwargs) return wrapper # type: ignore[return-value] ``` Here's an example ``ParamType`` subclass which uses this: ```python class CommaDelimitedString(click.ParamType): @add_ctx_arg def get_metavar(self, param: click.Parameter, ctx: click.Context | None) -> str: return "TEXT,TEXT,..." ``` asyncclick-8.3.0.5-async/docs/testing.md000066400000000000000000000107571507140761400200710ustar00rootroot00000000000000# Testing Click Applications ```{eval-rst} .. currentmodule:: click.testing ``` Click provides the {ref}`click.testing ` module to help you invoke command line applications and check their behavior. These tools should only be used for testing since they change the entire interpreter state for simplicity. They are not thread-safe! The examples use [pytest](https://docs.pytest.org/en/stable/) style tests. ```{contents} :depth: 1 :local: true ``` ## Basic Example The key pieces are: - {class}`CliRunner` - used to invoke commands as command line scripts. - {class}`Result` - returned from {meth}`CliRunner.invoke`. Captures output data, exit code, optional exception, and captures the output as bytes and binary data. ```{code-block} python :caption: hello.py import click @click.command() @click.argument('name') def hello(name): click.echo(f'Hello {name}!') ``` ```{code-block} python :caption: test_hello.py from click.testing import CliRunner from hello import hello def test_hello_world(): runner = CliRunner() result = runner.invoke(hello, ['Peter']) assert result.exit_code == 0 assert result.output == 'Hello Peter!\n' ``` ## Subcommands A subcommand name must be specified in the `args` parameter {meth}`CliRunner.invoke`: ```{code-block} python :caption: sync.py import click @click.group() @click.option('--debug/--no-debug', default=False) def cli(debug): click.echo(f"Debug mode is {'on' if debug else 'off'}") @cli.command() def sync(): click.echo('Syncing') ``` ```{code-block} python :caption: test_sync.py from click.testing import CliRunner from sync import cli def test_sync(): runner = CliRunner() result = runner.invoke(cli, ['--debug', 'sync']) assert result.exit_code == 0 assert 'Debug mode is on' in result.output assert 'Syncing' in result.output ``` ## Context Settings Additional keyword arguments passed to {meth}`CliRunner.invoke` will be used to construct the initial {class}`Context object `. For example, setting a fixed terminal width equal to 60: ```{code-block} python :caption: sync.py import click @click.group() def cli(): pass @cli.command() def sync(): click.echo('Syncing') ``` ```{code-block} python :caption: test_sync.py from click.testing import CliRunner from sync import cli def test_sync(): runner = CliRunner() result = runner.invoke(cli, ['sync'], terminal_width=60) assert result.exit_code == 0 assert 'Debug mode is on' in result.output assert 'Syncing' in result.output ``` ## File System Isolation The {meth}`CliRunner.isolated_filesystem` context manager sets the current working directory to a new, empty folder. ```{code-block} python :caption: cat.py import click @click.command() @click.argument('f', type=click.File()) def cat(f): click.echo(f.read()) ``` ```{code-block} python :caption: test_cat.py from click.testing import CliRunner from cat import cat def test_cat(): runner = CliRunner() with runner.isolated_filesystem(): with open('hello.txt', 'w') as f: f.write('Hello World!') result = runner.invoke(cat, ['hello.txt']) assert result.exit_code == 0 assert result.output == 'Hello World!\n' ``` Pass in a path to control where the temporary directory is created. In this case, the directory will not be removed by Click. Its useful to integrate with a framework like Pytest that manages temporary files. ```{code-block} python :caption: test_cat.py from click.testing import CliRunner from cat import cat def test_cat_with_path_specified(): runner = CliRunner() with runner.isolated_filesystem('~/test_folder'): with open('hello.txt', 'w') as f: f.write('Hello World!') result = runner.invoke(cat, ['hello.txt']) assert result.exit_code == 0 assert result.output == 'Hello World!\n' ``` ## Input Streams The test wrapper can provide input data for the input stream (stdin). This is very useful for testing prompts. ```{code-block} python :caption: prompt.py import click @click.command() @click.option('--foo', prompt=True) def prompt(foo): click.echo(f"foo={foo}") ``` ```{code-block} python :caption: test_prompt.py from click.testing import CliRunner from prompt import prompt def test_prompts(): runner = CliRunner() result = runner.invoke(prompt, input='wau wau\n') assert not result.exception assert result.output == 'Foo: wau wau\nfoo=wau wau\n' ``` Prompts will be emulated so they write the input data to the output stream as well. If hidden input is expected then this does not happen. asyncclick-8.3.0.5-async/docs/unicode-support.md000066400000000000000000000102711507140761400215430ustar00rootroot00000000000000# Unicode Support ```{currentmodule} click ``` Click has to take extra care to support Unicode text in different environments. - The command line in Unix is traditionally bytes, not Unicode. While there are encoding hints, there are some situations where this can break. The most common one is SSH connections to machines with different locales. Misconfigured environments can cause a wide range of Unicode problems due to the lack of support for roundtripping surrogate escapes. This will not be fixed in Click itself! - Standard input and output is opened in text mode by default. Click has to reopen the stream in binary mode in certain situations. Because there is no standard way to do this, it might not always work. Primarily this can become a problem when testing command-line applications. This is not supported: ```python sys.stdin = io.StringIO('Input here') sys.stdout = io.StringIO() ``` Instead you need to do this: ```python input = 'Input here' in_stream = io.BytesIO(input.encode('utf-8')) sys.stdin = io.TextIOWrapper(in_stream, encoding='utf-8') out_stream = io.BytesIO() sys.stdout = io.TextIOWrapper(out_stream, encoding='utf-8') ``` Remember in that case, you need to use `out_stream.getvalue()` and not `sys.stdout.getvalue()` if you want to access the buffer contents as the wrapper will not forward that method. - `sys.stdin`, `sys.stdout` and `sys.stderr` are by default text-based. When Click needs a binary stream, it attempts to discover the underlying binary stream. - `sys.argv` is always text. This means that the native type for input values to the types in Click is Unicode, not bytes. This causes problems if the terminal is incorrectly set and Python does not figure out the encoding. In that case, the Unicode string will contain error bytes encoded as surrogate escapes. - When dealing with files, Click will always use the Unicode file system API by using the operating system's reported or guessed filesystem encoding. Surrogates are supported for filenames, so it should be possible to open files through the {func}`File` type even if the environment is misconfigured. ## Surrogate Handling Click does all the Unicode handling in the standard library and is subject to its behavior. Unicode requires extra care. The reason for this is that the encoding detection is done in the interpreter, and on Linux and certain other operating systems, its encoding handling is problematic. The biggest source of frustration is that Click scripts invoked by init systems, deployment tools, or cron jobs will refuse to work unless a Unicode locale is exported. If Click encounters such an environment it will prevent further execution to force you to set a locale. This is done because Click cannot know about the state of the system once it's invoked and restore the values before Python's Unicode handling kicked in. If you see something like this error: ```console Traceback (most recent call last): ... RuntimeError: Click will abort further execution because Python was configured to use ASCII as encoding for the environment. Consult https://click.palletsprojects.com/unicode-support/ for mitigation steps. ``` You are dealing with an environment where Python thinks you are restricted to ASCII data. The solution to these problems is different depending on which locale your computer is running in. For instance, if you have a German Linux machine, you can fix the problem by exporting the locale to `de_DE.utf-8`: ```console export LC_ALL=de_DE.utf-8 export LANG=de_DE.utf-8 ``` If you are on a US machine, `en_US.utf-8` is the encoding of choice. On some newer Linux systems, you could also try `C.UTF-8` as the locale: ```console export LC_ALL=C.UTF-8 export LANG=C.UTF-8 ``` On some systems it was reported that `UTF-8` has to be written as `UTF8` and vice versa. To see which locales are supported you can invoke `locale -a`. You need to export the values before you invoke your Python script. In Python 3.7 and later you will no longer get a `RuntimeError` in many cases thanks to {pep}`538` and {pep}`540`, which changed the default assumption in unconfigured environments. This doesn't change the general issue that your locale may be misconfigured. asyncclick-8.3.0.5-async/docs/utils.md000066400000000000000000000302321507140761400175420ustar00rootroot00000000000000# Utilities ```{currentmodule} click ``` Besides the functionality that Click provides to interface with argument parsing and handling, it also provides a bunch of addon functionality that is useful for writing command line utilities. ## Printing to Stdout The most obvious helper is the {func}`echo` function, which in many ways works like the Python `print` statement or function. The main difference is that it works the same in many different terminal environments. Example: ```python import click click.echo('Hello World!') ``` It can output both text and binary data. It will emit a trailing newline by default, which needs to be suppressed by passing `nl=False`: ```python click.echo(b'\xe2\x98\x83', nl=False) ``` Last but not least {func}`echo` uses click's intelligent internal output streams to stdout and stderr which support unicode output on the Windows console. This means for as long as you are using `click.echo` you can output unicode characters (there are some limitations on the default font with regards to which characters can be displayed). ```{versionadded} 6.0 ``` Click emulates output streams on Windows to support unicode to the Windows console through separate APIs. For more information see {doc}`wincmd`. ```{versionadded} 3.0 ``` You can also easily print to standard error by passing `err=True`: ```python click.echo('Hello World!', err=True) ``` (ansi-colors)= ## ANSI Colors ```{versionadded} 2.0 ``` The {func}`echo` function supports ANSI colors and styles. On Windows this uses [colorama](https://pypi.org/project/colorama/). Primarily this means that: - Click's {func}`echo` function will automatically strip ANSI color codes if the stream is not connected to a terminal. - the {func}`echo` function will transparently connect to the terminal on Windows and translate ANSI codes to terminal API calls. This means that colors will work on Windows the same way they do on other operating systems. On Windows, Click uses colorama without calling `colorama.init()`. You can still call that in your code, but it's not required for Click. For styling a string, the {func}`style` function can be used: ```python import click click.echo(click.style('Hello World!', fg='green')) click.echo(click.style('Some more text', bg='blue', fg='white')) click.echo(click.style('ATTENTION', blink=True, bold=True)) ``` The combination of {func}`echo` and {func}`style` is also available in a single function called {func}`secho`: ```python click.secho('Hello World!', fg='green') click.secho('Some more text', bg='blue', fg='white') click.secho('ATTENTION', blink=True, bold=True) ``` ## Pager Support In some situations, you might want to show long texts on the terminal and let a user scroll through it. This can be achieved by using the {func}`echo_via_pager` function which works similarly to the {func}`echo` function, but always writes to stdout and, if possible, through a pager. Example: ```{eval-rst} .. click:example:: @click.command() def less(): click.echo_via_pager("\n".join(f"Line {idx}" for idx in range(200))) ``` If you want to use the pager for a lot of text, especially if generating everything in advance would take a lot of time, you can pass a generator (or generator function) instead of a string: ```{eval-rst} .. click:example:: def _generate_output(): for idx in range(50000): yield f"Line {idx}\n" @click.command() def less(): click.echo_via_pager(_generate_output()) ``` ## Screen Clearing ```{versionadded} 2.0 ``` To clear the terminal screen, you can use the {func}`clear` function that is provided starting with Click 2.0. It does what the name suggests: it clears the entire visible screen in a platform-agnostic way: ```python import click click.clear() ``` ## Getting Characters from Terminal ```{versionadded} 2.0 ``` Normally, when reading input from the terminal, you would read from standard input. However, this is buffered input and will not show up until the line has been terminated. In certain circumstances, you might not want to do that and instead read individual characters as they are being written. For this, Click provides the {func}`getchar` function which reads a single character from the terminal buffer and returns it as a Unicode character. Note that this function will always read from the terminal, even if stdin is instead a pipe. Example: ```python import click click.echo('Continue? [yn] ', nl=False) c = click.getchar() click.echo() if c == 'y': click.echo('We will go on') elif c == 'n': click.echo('Abort!') else: click.echo('Invalid input :(') ``` Note that this reads raw input, which means that things like arrow keys will show up in the platform's native escape format. The only characters translated are `^C` and `^D` which are converted into keyboard interrupts and end of file exceptions respectively. This is done because otherwise, it's too easy to forget about that and to create scripts that cannot be properly exited. ## Waiting for Key Press ```{versionadded} 2.0 ``` Sometimes, it's useful to pause until the user presses any key on the keyboard. This is especially useful on Windows where `cmd.exe` will close the window at the end of the command execution by default, instead of waiting. In click, this can be accomplished with the {func}`pause` function. This function will print a quick message to the terminal (which can be customized) and wait for the user to press a key. In addition to that, it will also become a NOP (no operation instruction) if the script is not run interactively. Example: ```python import click click.pause() ``` ## Launching Editors ```{versionadded} 2.0 ``` Click supports launching editors automatically through {func}`edit`. This is very useful for asking users for multi-line input. It will automatically open the user's defined editor or fall back to a sensible default. If the user closes the editor without saving, the return value will be `None`, otherwise the entered text. Example usage: ```python import click def get_commit_message(): MARKER = '# Everything below is ignored\n' message = click.edit('\n\n' + MARKER) if message is not None: return message.split(MARKER, 1)[0].rstrip('\n') ``` Alternatively, the function can also be used to launch editors for files by a specific filename. In this case, the return value is always `None`. Example usage: ```python import click click.edit(filename='/etc/passwd') ``` ## Launching Applications ```{versionadded} 2.0 ``` Click supports launching applications through {func}`launch`. This can be used to open the default application associated with a URL or filetype. This can be used to launch web browsers or picture viewers, for instance. In addition to this, it can also launch the file manager and automatically select the provided file. Example usage: ```python click.launch("https://click.palletsprojects.com/") click.launch("/my/downloaded/file.txt", locate=True) ``` ## Printing Filenames Because filenames might not be Unicode, formatting them can be a bit tricky. The way this works with click is through the {func}`format_filename` function. It does a best-effort conversion of the filename to Unicode and will never fail. This makes it possible to use these filenames in the context of a full Unicode string. Example: ```python click.echo(f"Path: {click.format_filename(b'foo.txt')}") ``` ## Standard Streams For command line utilities, it's very important to get access to input and output streams reliably. Python generally provides access to these streams through `sys.stdout` and friends, but unfortunately, there are API differences between 2.x and 3.x, especially with regards to how these streams respond to Unicode and binary data. Because of this, click provides the {func}`get_binary_stream` and {func}`get_text_stream` functions, which produce consistent results with different Python versions and for a wide variety of terminal configurations. The end result is that these functions will always return a functional stream object (except in very odd cases; see {doc}`/unicode-support`). Example: ```python import click stdin_text = click.get_text_stream('stdin') stdout_binary = click.get_binary_stream('stdout') ``` ```{versionadded} 6.0 ``` Click now emulates output streams on Windows to support unicode to the Windows console through separate APIs. For more information see {doc}`wincmd`. ## Intelligent File Opening ```{versionadded} 3.0 ``` Starting with Click 3.0 the logic for opening files from the {func}`File` type is exposed through the {func}`open_file` function. It can intelligently open stdin/stdout as well as any other file. Example: ```python import click stdout = click.open_file('-', 'w') test_file = click.open_file('test.txt', 'w') ``` If stdin or stdout are returned, the return value is wrapped in a special file where the context manager will prevent the closing of the file. This makes the handling of standard streams transparent and you can always use it like this: ```python with click.open_file(filename, 'w') as f: f.write('Hello World!\n') ``` ## Finding Application Folders ```{versionadded} 2.0 ``` Very often, you want to open a configuration file that belongs to your application. However, different operating systems store these configuration files in different locations depending on their standards. Click provides a {func}`get_app_dir` function which returns the most appropriate location for per-user config files for your application depending on the OS. Example usage: ```python import os import click import ConfigParser APP_NAME = 'My Application' def read_config(): cfg = os.path.join(click.get_app_dir(APP_NAME), 'config.ini') parser = ConfigParser.RawConfigParser() parser.read([cfg]) rv = {} for section in parser.sections(): for key, value in parser.items(section): rv[f"{section}.{key}"] = value return rv ``` ## Showing Progress Bars Sometimes, you have command line scripts that need to process a lot of data, but you want to quickly show the user some progress about how long that will take. Click supports simple progress bar rendering for that through the {func}`progressbar` function. ```{note} If you find that you have requirements beyond what Click's progress bar supports, try using [tqdm](https://tqdm.github.io/). ``` The basic usage is very simple: the idea is that you have an iterable that you want to operate on. For each item in the iterable it might take some time to do processing. So say you have a loop like this: ```python for user in all_the_users_to_process: modify_the_user(user) ``` To hook this up with an automatically updating progress bar, all you need to do is to change the code to this: ```python import click with click.progressbar(all_the_users_to_process) as bar: for user in bar: modify_the_user(user) ``` Click will then automatically print a progress bar to the terminal and calculate the remaining time for you. The calculation of remaining time requires that the iterable has a length. If it does not have a length but you know the length, you can explicitly provide it: ```python with click.progressbar(all_the_users_to_process, length=number_of_users) as bar: for user in bar: modify_the_user(user) ``` Note that {func}`progressbar` updates the bar *after* each iteration of the loop. So code like this will render correctly: ```python import time with click.progressbar([1, 2, 3]) as bar: for x in bar: print(f"sleep({x})...") time.sleep(x) ``` Another useful feature is to associate a label with the progress bar which will be shown preceding the progress bar: ```python with click.progressbar(all_the_users_to_process, label='Modifying user accounts', length=number_of_users) as bar: for user in bar: modify_the_user(user) ``` Sometimes, one may need to iterate over an external iterator, and advance the progress bar irregularly. To do so, you need to specify the length (and no iterable), and use the update method on the context return value instead of iterating directly over it: ```python with click.progressbar(length=total_size, label='Unzipping archive') as bar: for archive in zip_file: archive.extract() bar.update(archive.size) ``` asyncclick-8.3.0.5-async/docs/virtualenv.md000066400000000000000000000023431507140761400206030ustar00rootroot00000000000000(virtualenv-heading)= # Virtualenv ## Why Use Virtualenv? You should use [Virtualenv](https://virtualenv.pypa.io/en/latest/) because: - It allows you to install multiple versions of the same dependency. - If you have an operating system version of Python, it prevents you from changing its dependencies and potentially messing up your os. ## How to Use Virtualenv Create your project folder, then a virtualenv within it: ```console $ mkdir myproject $ cd myproject $ python3 -m venv .venv ``` Now, whenever you want to work on a project, you only have to activate the corresponding environment. ```{eval-rst} .. tabs:: .. group-tab:: OSX/Linux .. code-block:: text $ . .venv/bin/activate (venv) $ .. group-tab:: Windows .. code-block:: text > .venv\scripts\activate (venv) > ``` You are now using your virtualenv (notice how the prompt of your shell has changed to show the active environment). To install packages in the virtual environment: ```console $ pip install click ``` And if you want to stop using the virtualenv, use the following command: ```console $ deactivate ``` After doing this, the prompt of your shell should be as familiar as before. asyncclick-8.3.0.5-async/docs/why.md000066400000000000000000000154441507140761400172210ustar00rootroot00000000000000# Why Click? There are so many libraries out there for writing command line utilities; why does Click exist? This question is easy to answer: because there is not a single command line utility for Python out there which ticks the following boxes: - Is lazily composable without restrictions. - Supports implementation of Unix/POSIX command line conventions. - Supports loading values from environment variables out of the box. - Support for prompting of custom values. - Is fully nestable and composable. - Supports file handling out of the box. - Comes with useful common helpers (getting terminal dimensions, ANSI colors, fetching direct keyboard input, screen clearing, finding config paths, launching apps and editors, etc.). There are many alternatives to Click; the obvious ones are `optparse` and `argparse` from the standard library. Have a look to see if something else resonates with you. Click actually implements its own parsing of arguments and does not use `optparse` or `argparse` following the `optparse` parsing behavior. The reason it's not based on `argparse` is that `argparse` does not allow proper nesting of commands by design and has some deficiencies when it comes to POSIX compliant argument handling. Click is designed to be fun and customizable but not overly flexible. For instance, the customizability of help pages is constrained. This constraint is intentional because Click promises multiple Click instances will continue to function as intended when strung together. Too much customizability would break this promise. Click was written to support the [Flask](https://palletsprojects.com/p/flask/) microframework ecosystem because no tool could provide it with the functionality it needed. To get an understanding of what Click is all about, I strongly recommend looking at the {ref}`complex-guide` chapter. ## Why not Argparse? Click is internally based on `optparse` instead of `argparse`. This is an implementation detail that a user does not have to be concerned with. Click is not based on `argparse` because it has some behaviors that make handling arbitrary command line interfaces hard: - `argparse` has built-in behavior to guess if something is an argument or an option. This becomes a problem when dealing with incomplete command lines; the behaviour becomes unpredictable without full knowledge of a command line. This goes against Click's ambitions of dispatching to subparsers. - `argparse` does not support disabling interspersed arguments. Without this feature, it's not possible to safely implement Click's nested parsing. ## Why not Docopt etc.? Docopt, and many tools like it, are cool in how they work, but very few of these tools deal with nesting of commands and composability in a way like Click. To the best of the developer's knowledge, Click is the first Python library that aims to create a level of composability of applications that goes beyond what the system itself supports. Docopt, for instance, acts by parsing your help pages and then parsing according to those rules. The side effect of this is that docopt is quite rigid in how it handles the command line interface. The upside of docopt is that it gives you strong control over your help page; the downside is that due to this it cannot rewrap your output for the current terminal width, and it makes translations hard. On top of that, docopt is restricted to basic parsing. It does not handle argument dispatching and callback invocation or types. This means there is a lot of code that needs to be written in addition to the basic help page to handle the parsing results. Most of all, however, it makes composability hard. While docopt does support dispatching to subcommands, it, for instance, does not directly support any kind of automatic subcommand enumeration based on what's available or it does not enforce subcommands to work in a consistent way. This is fine, but it's different from how Click wants to work. Click aims to support fully composable command line user interfaces by doing the following: - Click does not just parse, it also dispatches to the appropriate code. - Click has a strong concept of an invocation context that allows subcommands to respond to data from the parent command. - Click has strong information available for all parameters and commands, so it can generate unified help pages for the full CLI and assist the user in converting the input data as necessary. - Click has a strong understanding of what types are, and it can give the user consistent error messages if something goes wrong. A subcommand written by a different developer will not suddenly die with a different error message because it's manually handled. - Click has enough meta information available for its whole program to evolve over time and improve the user experience without forcing developers to adjust their programs. For instance, if Click decides to change how help pages are formatted, all Click programs will automatically benefit from this. The aim of Click is to make composable systems. Whereas, the aim of docopt is to build the most beautiful and hand-crafted command line interfaces. These two goals conflict with one another in subtle ways. Click actively prevents people from implementing certain patterns in order to achieve unified command line interfaces. For instance, as a developer, you are given very little choice in formatting your help pages. ## Why Hardcoded Behaviors? The other question is why Click goes away from optparse and hardcodes certain behaviors instead of staying configurable. There are multiple reasons for this. The biggest one is that too much configurability makes it hard to achieve a consistent command line experience. The best example for this is optparse's `callback` functionality for accepting an arbitrary number of arguments. Due to syntactical ambiguities on the command line, there is no way to implement fully variadic arguments. There are always tradeoffs that need to be made and in case of `argparse` these tradeoffs have been critical enough, that a system like Click cannot even be implemented on top of it. In this particular case, Click attempts to stay with a handful of accepted paradigms for building command line interfaces that can be well documented and tested. ## Why No Auto Correction? The question came up why Click does not auto correct parameters given that even optparse and `argparse` support automatic expansion of long arguments. The reason for this is that it's a liability for backwards compatibility. If people start relying on automatically modified parameters and someone adds a new parameter in the future, the script might stop working. These kinds of problems are hard to find, so Click does not attempt to be magical about this. This sort of behavior however can be implemented on a higher level to support things such as explicit aliases. For more information see {ref}`aliases`. asyncclick-8.3.0.5-async/docs/wincmd.md000066400000000000000000000057311507140761400176710ustar00rootroot00000000000000# Windows Console Notes ```{versionadded} 6.0 ``` Click emulates output streams on Windows to support unicode to the Windows console through separate APIs and we perform different decoding of parameters. Here is a brief overview of how this works and what it means to you. ## Unicode Arguments Click internally is generally based on the concept that any argument can come in as either byte string or unicode string and conversion is performed to the type expected value as late as possible. This has some advantages as it allows us to accept the data in the most appropriate form for the operating system and Python version. This caused some problems on Windows where initially the wrong encoding was used and garbage ended up in your input data. We not only fixed the encoding part, but we also now extract unicode parameters from `sys.argv`. There is also another limitation with this: if `sys.argv` was modified prior to invoking a click handler, we have to fall back to the regular byte input in which case not all unicode values are available but only a subset of the codepage used for parameters. ## Unicode Output and Input Unicode output and input on Windows is implemented through the concept of a dispatching text stream. What this means is that when click first needs a text output (or input) stream on windows it goes through a few checks to figure out of a windows console is connected or not. If no Windows console is present then the text output stream is returned as such and the encoding for that stream is set to `utf-8` like on all platforms. However if a console is connected the stream will instead be emulated and use the cmd.exe unicode APIs to output text information. In this case the stream will also use `utf-16-le` as internal encoding. However there is some hackery going on that the underlying raw IO buffer is still bypassing the unicode APIs and byte output through an indirection is still possible. - This unicode support is limited to `click.echo`, `click.prompt` as well as `click.get_text_stream`. - Depending on if unicode values or byte strings are passed the control flow goes completely different places internally which can have some odd artifacts if data partially ends up being buffered. Click attempts to protect against that by manually always flushing but if you are mixing and matching different string types to `stdout` or `stderr` you will need to manually flush. - The raw output stream is set to binary mode, which is a global operation on Windows, so `print` calls will be affected. Prefer `click.echo` over `print`. - On Windows 7 and below, there is a limitation where at most 64k characters can be written in one call in binary mode. In this situation, `sys.stdout` and `sys.stderr` are replaced with wrappers that work around the limitation. Another important thing to note is that the Windows console's default fonts do not support a lot of characters which means that you are mostly limited to international letters but no emojis or special characters. asyncclick-8.3.0.5-async/examples/000077500000000000000000000000001507140761400167465ustar00rootroot00000000000000asyncclick-8.3.0.5-async/examples/README000066400000000000000000000002451507140761400176270ustar00rootroot00000000000000Click Examples This folder contains various Click examples. Note that all of these are not runnable by themselves but should be installed into a virtualenv. asyncclick-8.3.0.5-async/examples/aliases/000077500000000000000000000000001507140761400203675ustar00rootroot00000000000000asyncclick-8.3.0.5-async/examples/aliases/README000066400000000000000000000006751507140761400212570ustar00rootroot00000000000000$ aliases_ aliases is a fairly advanced example that shows how to implement command aliases with Click. It uses a subclass of the default group to customize how commands are located. It supports both aliases read from a config file as well as automatic abbreviations. The aliases from the config are read from the aliases.ini file. Try `aliases st` and `aliases ci`! Usage: $ pip install --editable . $ aliases --help asyncclick-8.3.0.5-async/examples/aliases/aliases.ini000066400000000000000000000000241507140761400225050ustar00rootroot00000000000000[aliases] ci=commit asyncclick-8.3.0.5-async/examples/aliases/aliases.py000066400000000000000000000077531507140761400223760ustar00rootroot00000000000000import configparser import os import asyncclick as click class Config: """The config in this example only holds aliases.""" def __init__(self): self.path = os.getcwd() self.aliases = {} def add_alias(self, alias, cmd): self.aliases.update({alias: cmd}) def read_config(self, filename): parser = configparser.RawConfigParser() parser.read([filename]) try: self.aliases.update(parser.items("aliases")) except configparser.NoSectionError: pass def write_config(self, filename): parser = configparser.RawConfigParser() parser.add_section("aliases") for key, value in self.aliases.items(): parser.set("aliases", key, value) with open(filename, "wb") as file: parser.write(file) pass_config = click.make_pass_decorator(Config, ensure=True) class AliasedGroup(click.Group): """This subclass of a group supports looking up aliases in a config file and with a bit of magic. """ def get_command(self, ctx, cmd_name): # Step one: bulitin commands as normal rv = click.Group.get_command(self, ctx, cmd_name) if rv is not None: return rv # Step two: find the config object and ensure it's there. This # will create the config object is missing. cfg = ctx.ensure_object(Config) # Step three: look up an explicit command alias in the config if cmd_name in cfg.aliases: actual_cmd = cfg.aliases[cmd_name] return click.Group.get_command(self, ctx, actual_cmd) # Alternative option: if we did not find an explicit alias we # allow automatic abbreviation of the command. "status" for # instance will match "st". We only allow that however if # there is only one command. matches = [ x for x in self.list_commands(ctx) if x.lower().startswith(cmd_name.lower()) ] if not matches: return None elif len(matches) == 1: return click.Group.get_command(self, ctx, matches[0]) ctx.fail(f"Too many matches: {', '.join(sorted(matches))}") def resolve_command(self, ctx, args): # always return the command's name, not the alias _, cmd, args = super().resolve_command(ctx, args) return cmd.name, cmd, args def read_config(ctx, param, value): """Callback that is used whenever --config is passed. We use this to always load the correct config. This means that the config is loaded even if the group itself never executes so our aliases stay always available. """ cfg = ctx.ensure_object(Config) if value is None: value = os.path.join(os.path.dirname(__file__), "aliases.ini") cfg.read_config(value) return value @click.command(cls=AliasedGroup) @click.option( "--config", type=click.Path(exists=True, dir_okay=False), callback=read_config, expose_value=False, help="The config file to use instead of the default.", ) def cli(): """An example application that supports aliases.""" @cli.command() def push(): """Pushes changes.""" click.echo("Push") @cli.command() def pull(): """Pulls changes.""" click.echo("Pull") @cli.command() def clone(): """Clones a repository.""" click.echo("Clone") @cli.command() def commit(): """Commits pending changes.""" click.echo("Commit") @cli.command() @pass_config def status(config): """Shows the status.""" click.echo(f"Status for {config.path}") @cli.command() @pass_config @click.argument("alias_", metavar="ALIAS", type=click.STRING) @click.argument("cmd", type=click.STRING) @click.option( "--config_file", type=click.Path(exists=True, dir_okay=False), default="aliases.ini" ) def alias(config, alias_, cmd, config_file): """Adds an alias to the specified configuration file.""" config.add_alias(alias_, cmd) config.write_config(config_file) click.echo(f"Added '{alias_}' as alias for '{cmd}'") asyncclick-8.3.0.5-async/examples/aliases/pyproject.toml000066400000000000000000000005011507140761400232770ustar00rootroot00000000000000[project] name = "click-example-aliases" version = "1.0.0" description = "Click aliases example" requires-python = ">=3.10" dependencies = [ "click>=8.1", ] [project.scripts] aliases = "aliases:cli" [build-system] requires = ["flit_core<4"] build-backend = "flit_core.buildapi" [tool.flit.module] name = "aliases" asyncclick-8.3.0.5-async/examples/colors/000077500000000000000000000000001507140761400202475ustar00rootroot00000000000000asyncclick-8.3.0.5-async/examples/colors/README000066400000000000000000000002361507140761400211300ustar00rootroot00000000000000$ colors_ colors is a simple example that shows how you can colorize text. Uses colorama on Windows. Usage: $ pip install --editable . $ colors asyncclick-8.3.0.5-async/examples/colors/colors.py000066400000000000000000000016541507140761400221300ustar00rootroot00000000000000import asyncclick as click all_colors = ( "black", "red", "green", "yellow", "blue", "magenta", "cyan", "white", "bright_black", "bright_red", "bright_green", "bright_yellow", "bright_blue", "bright_magenta", "bright_cyan", "bright_white", ) @click.command() def cli(): """This script prints some colors. It will also automatically remove all ANSI styles if data is piped into a file. Give it a try! """ for color in all_colors: click.echo(click.style(f"I am colored {color}", fg=color)) for color in all_colors: click.echo(click.style(f"I am colored {color} and bold", fg=color, bold=True)) for color in all_colors: click.echo(click.style(f"I am reverse colored {color}", fg=color, reverse=True)) click.echo(click.style("I am blinking", blink=True)) click.echo(click.style("I am underlined", underline=True)) asyncclick-8.3.0.5-async/examples/colors/pyproject.toml000066400000000000000000000004741507140761400231700ustar00rootroot00000000000000[project] name = "click-example-colors" version = "1.0.0" description = "Click colors example" requires-python = ">=3.10" dependencies = [ "click>=8.1", ] [project.scripts] colors = "colors:cli" [build-system] requires = ["flit_core<4"] build-backend = "flit_core.buildapi" [tool.flit.module] name = "colors" asyncclick-8.3.0.5-async/examples/completion/000077500000000000000000000000001507140761400211175ustar00rootroot00000000000000asyncclick-8.3.0.5-async/examples/completion/README000066400000000000000000000010561507140761400220010ustar00rootroot00000000000000$ completion ============ Demonstrates Click's shell completion support. .. code-block:: bash pip install --editable . For Bash: .. code-block:: bash eval "$(_COMPLETION_COMPLETE=bash_source completion)" For Zsh: .. code-block:: zsh eval "$(_COMPLETION_COMPLETE=zsh_source completion)" For Fish: .. code-block:: fish eval (env _COMPLETION_COMPLETE=fish_source completion) Now press tab (maybe twice) after typing something to see completions. .. code-block:: python $ completion $ completion gr asyncclick-8.3.0.5-async/examples/completion/completion.py000066400000000000000000000025771507140761400236550ustar00rootroot00000000000000import os import asyncclick as click from asyncclick.shell_completion import CompletionItem @click.group() def cli(): pass @cli.command() @click.option("--dir", type=click.Path(file_okay=False)) def ls(dir): click.echo("\n".join(os.listdir(dir))) def get_env_vars(ctx, param, incomplete): # Returning a list of values is a shortcut to returning a list of # CompletionItem(value). return [k for k in os.environ if incomplete in k] @cli.command(help="A command to print environment variables") @click.argument("envvar", shell_complete=get_env_vars) def show_env(envvar): click.echo(f"Environment variable: {envvar}") click.echo(f"Value: {os.environ[envvar]}") @cli.group(help="A group that holds a subcommand") def group(): pass def list_users(ctx, param, incomplete): # You can generate completions with help strings by returning a list # of CompletionItem. You can match on whatever you want, including # the help. items = [("bob", "butcher"), ("alice", "baker"), ("jerry", "candlestick maker")] out = [] for value, help in items: if incomplete in value or incomplete in help: out.append(CompletionItem(value, help=help)) return out @group.command(help="Choose a user") @click.argument("user", shell_complete=list_users) def select_user(user): click.echo(f"Chosen user is {user}") cli.add_command(group) asyncclick-8.3.0.5-async/examples/completion/pyproject.toml000066400000000000000000000005201507140761400240300ustar00rootroot00000000000000[project] name = "click-example-completion" version = "1.0.0" description = "Click completion example" requires-python = ">=3.10" dependencies = [ "click>=8.1", ] [project.scripts] completion = "completion:cli" [build-system] requires = ["flit_core<4"] build-backend = "flit_core.buildapi" [tool.flit.module] name = "completion" asyncclick-8.3.0.5-async/examples/complex/000077500000000000000000000000001507140761400204155ustar00rootroot00000000000000asyncclick-8.3.0.5-async/examples/complex/README000066400000000000000000000007041507140761400212760ustar00rootroot00000000000000$ complex_ complex is an example of building very complex cli applications that load subcommands dynamically from a plugin folder and other things. All the commands are implemented as plugins in the `complex.commands` package. If a python module is placed named "cmd_foo" it will show up as "foo" command and the `cli` object within it will be loaded as nested Click command. Usage: $ pip install --editable . $ complex --help asyncclick-8.3.0.5-async/examples/complex/complex/000077500000000000000000000000001507140761400220645ustar00rootroot00000000000000asyncclick-8.3.0.5-async/examples/complex/complex/__init__.py000066400000000000000000000000001507140761400241630ustar00rootroot00000000000000asyncclick-8.3.0.5-async/examples/complex/complex/cli.py000066400000000000000000000031261507140761400232070ustar00rootroot00000000000000import os import sys import asyncclick as click CONTEXT_SETTINGS = dict(auto_envvar_prefix="COMPLEX") class Environment: def __init__(self): self.verbose = False self.home = os.getcwd() def log(self, msg, *args): """Logs a message to stderr.""" if args: msg %= args click.echo(msg, file=sys.stderr) def vlog(self, msg, *args): """Logs a message to stderr only if verbose is enabled.""" if self.verbose: self.log(msg, *args) pass_environment = click.make_pass_decorator(Environment, ensure=True) cmd_folder = os.path.abspath(os.path.join(os.path.dirname(__file__), "commands")) class ComplexCLI(click.Group): def list_commands(self, ctx): rv = [] for filename in os.listdir(cmd_folder): if filename.endswith(".py") and filename.startswith("cmd_"): rv.append(filename[4:-3]) rv.sort() return rv def get_command(self, ctx, name): try: mod = __import__(f"complex.commands.cmd_{name}", None, None, ["cli"]) except ImportError: return return mod.cli @click.command(cls=ComplexCLI, context_settings=CONTEXT_SETTINGS) @click.option( "--home", type=click.Path(exists=True, file_okay=False, resolve_path=True), help="Changes the folder to operate on.", ) @click.option("-v", "--verbose", is_flag=True, help="Enables verbose mode.") @pass_environment def cli(ctx, verbose, home): """A complex command line interface.""" ctx.verbose = verbose if home is not None: ctx.home = home asyncclick-8.3.0.5-async/examples/complex/complex/commands/000077500000000000000000000000001507140761400236655ustar00rootroot00000000000000asyncclick-8.3.0.5-async/examples/complex/complex/commands/__init__.py000066400000000000000000000000001507140761400257640ustar00rootroot00000000000000asyncclick-8.3.0.5-async/examples/complex/complex/commands/cmd_init.py000066400000000000000000000006171507140761400260310ustar00rootroot00000000000000from complex.cli import pass_environment import asyncclick as click @click.command("init", short_help="Initializes a repo.") @click.argument("path", required=False, type=click.Path(resolve_path=True)) @pass_environment def cli(ctx, path): """Initializes a repository.""" if path is None: path = ctx.home ctx.log(f"Initialized the repository in {click.format_filename(path)}") asyncclick-8.3.0.5-async/examples/complex/complex/commands/cmd_status.py000066400000000000000000000004541507140761400264100ustar00rootroot00000000000000from complex.cli import pass_environment import asyncclick as click @click.command("status", short_help="Shows file changes.") @pass_environment def cli(ctx): """Shows file changes in the current working directory.""" ctx.log("Changed files: none") ctx.vlog("bla bla bla, debug info") asyncclick-8.3.0.5-async/examples/complex/pyproject.toml000066400000000000000000000005051507140761400233310ustar00rootroot00000000000000[project] name = "click-example-complex" version = "1.0.0" description = "Click complex example" requires-python = ">=3.10" dependencies = [ "click>=8.1", ] [project.scripts] complex = "complex.cli:cli" [build-system] requires = ["flit_core<4"] build-backend = "flit_core.buildapi" [tool.flit.module] name = "complex" asyncclick-8.3.0.5-async/examples/imagepipe/000077500000000000000000000000001507140761400207065ustar00rootroot00000000000000asyncclick-8.3.0.5-async/examples/imagepipe/.gitignore000066400000000000000000000000141507140761400226710ustar00rootroot00000000000000processed-* asyncclick-8.3.0.5-async/examples/imagepipe/README000066400000000000000000000004601507140761400215660ustar00rootroot00000000000000$ imagepipe_ imagepipe is an example application that implements some commands that chain image processing instructions together. This requires pillow. Usage: $ pip install --editable . $ imagepipe open -i example01.jpg resize -w 128 display $ imagepipe open -i example02.jpg blur save asyncclick-8.3.0.5-async/examples/imagepipe/example01.jpg000066400000000000000000001447351507140761400232220ustar00rootroot00000000000000JFIF`` XICC_PROFILE HLinomntrRGB XYZ  1acspMSFTIEC sRGB-HP cprtP3desclwtptbkptrXYZgXYZ,bXYZ@dmndTpdmddvuedLview$lumimeas $tech0 rTRC< gTRC< bTRC< textCopyright (c) 1998 Hewlett-Packard CompanydescsRGB IEC61966-2.1sRGB IEC61966-2.1XYZ QXYZ XYZ o8XYZ bXYZ $descIEC http://www.iec.chIEC http://www.iec.chdesc.IEC 61966-2.1 Default RGB colour space - sRGB.IEC 61966-2.1 Default RGB colour space - sRGBdesc,Reference Viewing Condition in IEC61966-2.1,Reference Viewing Condition in IEC61966-2.1view_. \XYZ L VPWmeassig CRT curv #(-27;@EJOTY^chmrw| %+28>ELRY`gnu| &/8AKT]gqz !-8COZfr~ -;HUcq~ +:IXgw'7HYj{+=Oat 2FZn  % : O d y  ' = T j " 9 Q i  * C \ u & @ Z t .Id %A^z &Ca~1Om&Ed#Cc'Ij4Vx&IlAe@e Ek*Qw;c*R{Gp@j>i  A l !!H!u!!!"'"U"""# #8#f###$$M$|$$% %8%h%%%&'&W&&&''I'z''( (?(q(())8)k))**5*h**++6+i++,,9,n,,- -A-v--..L.../$/Z///050l0011J1112*2c223 3F3334+4e4455M555676r667$7`7788P8899B999:6:t::;-;k;;<' >`>>?!?a??@#@d@@A)AjAAB0BrBBC:C}CDDGDDEEUEEF"FgFFG5G{GHHKHHIIcIIJ7J}JK KSKKL*LrLMMJMMN%NnNOOIOOP'PqPQQPQQR1R|RSS_SSTBTTU(UuUVV\VVWDWWX/X}XYYiYZZVZZ[E[[\5\\]']x]^^l^__a_``W``aOaabIbbcCccd@dde=eef=ffg=ggh?hhiCiijHjjkOkklWlmm`mnnknooxop+ppq:qqrKrss]sttptu(uuv>vvwVwxxnxy*yyzFz{{c{|!||}A}~~b~#G k͂0WGrׇ;iΉ3dʋ0cʍ1fΏ6n֑?zM _ɖ4 uL$h՛BdҞ@iءG&vVǥ8nRĩ7u\ЭD-u`ֲK³8%yhYѹJº;.! zpg_XQKFAǿ=ȼ:ɹ8ʷ6˶5̵5͵6ζ7ϸ9к<Ѿ?DINU\dlvۀ܊ݖޢ)߯6DScs 2F[p(@Xr4Pm8Ww)KmExifMM*JR(iZ``РC   %# , #&')*)-0-(0%()(C   (((((((((((((((((((((((((((((((((((((((((((((((((((" }!1AQa"q2#BR$3br %&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz w!1AQaq"2B #3Rbr $4%&'()*56789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz ?֍ޢ.+MbMԻ,њb.ygCG.I'=: ^+ImE?Q\\hz%IX'ytckM|KGj[ޣf Y2`rUf80FQbZ5 n*IRHn13ګ)ہ<yR\KEc\B|nJv.qrpXʛtOm]@cU-o&o+Si`9$nC)#\7Zc>O*O1B2mt=~~'X," dNC181һ& Vqmi|q$3Ӓk(jmhWzOuG2L7H{]}Je7+Ȗ WD_4WZmZ]7e TTd+=~m[Rr\J_'G01_Ins3_72VSs-[\]uoіSsjcG洶smqq" '^-i0i̾`L3q]^wo.VBIc`ǷSEѧִ)m.َ^EfO|ߵκ9sjkUk R -H*\pħ\WjZ`7vEs"4XV>Wֹ\;+r=?ee/2Ꭵ%iW$V9x'O$+bKohKy!Z}jCEFmg.Y&Ѡ;޺06MyjTI%fU%dIyr$Fv5Ff$ZnWM' RR;r ?Qf̵9M7ڮ :y󍈼r&cũjެTc~@WxZoŬmad ;#vJ/e3GyT֨cy~<[x5K\H>?R3Ϛ8a[^I$m~Y.lR0F>zxs-ܓEgi#D@bWq7z5fm8Ɯ6.n@5^Q}$pq+K+PA=}4oJϥC#[#)76k^Hȷw>pXuWkjz-kso2dbX?V[%OK{%cžIԟzK_5-&ɛtfX|%5ҨXp*gZވs} "eW#^O?]ݦBvhO}bu;ͬ-#w] /M*x#~g$g=Me:Ҟ9/k KgQJX#$x uuioNN^%n"8%9&}zkZ_"cO[ZSw{hFbāvKh ZlqqZxԍppkmn] ;}Ptue7 !BW$Soqc8x4 d[Q 4j 79Q'SZGUJJ/~HҞ+ zK%Ը{c<+קOr8-G Y]D6B߂5{KݶP3sm~WQߏZB^=>|gU7'ݷ]sKD(coA2B7k~DTLeM>߫0Յ6ݏ+hv3qSͅBŒO@?JԉZfEKH 9$m*bmW7F~Sl~Iڬ[+Ig[1ܭm,$ռY#Giܶq7!=0NuQguXAxv4jʊkk;ww#Γ>I4ax2)>RzE2;?ZOñWz8lq?J!WcXp<\;l*6 Ek%mQF\'dzS|^"[D"}0 \\]$һG5]Rc9ҹsMX.ԹTv>BTՒIMlys$¢vjy:me"(^WFׅ45!d'rm#uUObcl?|GNd}\5%/#pt5ݔ6q4i4v(fUB㌓ "q]&m}eC!S.B*(8Ydc֯D&4qur풎3ɍ=OX^ݏžnup̶.u}LZW͊u*eMD7fr1M 4 YXEKk]Bج9nGҹg\,iq1G9e77_iDcj =qÐTU5NN|m>ȇ^- W0] zid􅻰2Vkf*0v# kwNqէJo+Z>qumleWRM'^zYHaӮeNUêQ7( {hgx_\ ۻX\F窩e }sޱ|7 9Aec"d> Vht;w nXIA<V85{kEm+,AfeÁUc@qQrz&T[]}k4d3죲+7Ol+TrOrO$Ս79G˔BG,¼njvJ"uT=?*0SVMFŭVdn`tS(66Uњ 'VMdwvֶCUr@+$HV~t'v'OpM=#巅KhNscmimYY٩[hR<5lU[Z7WѮsIl%Nn)sjʄvYX~j /"+$qngtf\ψ;c?ֶ) k}#*}Q?518FПU.j]Ҵm?u{-=ns (u3I${I? g߆_~Dzz#>׉xau"ZBmT}g'*A\ƻpTfti;:=\ibKyє`yEɯ-GsȽ< -o<;`jY?w2ڭx_IeHeϛrСfG>k'S%۠ނaA8P𦐺6Iwc:~Zmϧx<$ڒf&m4=#:" p?3f.%2J`21Ů9cpINwϥb8_sLN̮~"tskŨM-Ɛ#9'AOnj.2}g_}B?JT{%^J_ xsEưs- :OxF5Ƨ4r.4EWoY4? s'6?y:(;?ӎkڍy:BAc4v ?3W7@׷*M' kSؒKXyU1RN{;[0,>syjʩ~Ua'')[NQ]x?@ دFpc$#;Oҡo{-*@؊I GBh6ִ1t/0gy,ry,d:u=3DO2A8'a'x}fO5_xO4H#\dCIA^LJ[|Udwx+]Hn!O>j-$W]Bo }kе^ FbTp>UX{ztڜG%LW#b߽K4~&CyBKiqB#g. jv5.Pc\ |.]02?G]*-6wԪJ]:=q%i9s6nbeu4P|)']zpi0x4K{dm3d kMG,p0K3=-%.L.0#"v7ߊ#ed!߷~2=Imrek1#x!H!|#ϣuHf P|-c?T'lNGOqg$!^>G\ };q$ g ,}'WͻB?3wHxx$Xm+Di+<֭Q4k}8G oEHu[c]&.ہQK]G;0L{z=E{\r58FsYֺtXS0;3\rUOUsВg~BHf?H.dg)4m:e_ƣHŒ vndz~4FY-[8Fm$g]*ۼ;wQA  RIڧu>ZZ*l"x[M>-䄇'<~'\cOҴmվgǙYJ;?@Lp \} 9.~'OWt1AUd>Kd-]laR'mRvHM~wIwiOE^S/5*5@ːA9kI}蝣[ҹp^ݦt[Ҵ1*e<~<,*=jֳlX/v cu_x+K d}sPy=s_=căޝe.q`GzkH>&wtsJ(_zWڬ> {aV:urЌ׸7 2:EyOtG.leo7)r=̻\Sv 3"iy~>:TFR#S G+XթƢȧ-+,m{p#9sƬױs 1ܧԮ~Z<˦kP,qݺA #'9+w IyseE%V+ο[ 8OkCm,T,=c-. 2H?C޻neCڹmQt敾%F/32EvV[2@@m?i'QhT4qlu>o m{ ?Hk**F'-lZ^^~gB=|ö>ڧ ܵ̓(O}x`<]o⛛BNۻboҞ*ئuUaxoŖ1@yX>&![kMyɓw]6}O`=dJo 5dU˔k7*2}f8^Q^BhdXd]}|I1nx5%FHĉvjƟKV{ǚO=0z7S.1M\ώ `?rqV7Io&siϯƝiI\ 59$ f·%p'fgӀ(좽VڳV9gķZWY Ѧ̐0 95_ctHnlZ/N=qZo5e[h5hzTa6u8]^fi#8(F}zq޼pҎװV֩k[,nu(x ԏ\f?ZFa3ZZ5M(sy'g)Z]>I&|0P~OCW4yqRUc^*:+#O\t@aiZ1 &2H#Dm6IZ[{{H[X˛p{3 ,EJWGZ0~O?4~}>PԒH48R_3iz枫;g?^[hZ> R7e(uAWysuqTI͟Nxe{` Q:r>*֮-4E6 1?1~f&HDIpͼ@*d(qj͝URBܳ#Vs%,G8"wfv!nʃ `1.s=?*DWwqҡso&epºaW̒ 1m-.5 2HɄ>en-IJGOAS"Y_pGqMjs*2KVZ︞ۓ© @9Vxnf[aHnl,HEFyRJzkfamN ?mD<05qouH򍴠4y2n|oᭌwWk2n~[9~&G,y}Bn^źy $CUq UKOn|L>A#bK~|/ uvb,1$krø} Z3xWԮC]^62]' w' n򦯡"q~=nY6YDQ*SۏLWLJda^v3ϟ}]`ImgMn ٕN:eϖ)f" v8TETap9XU>K]鷠?RZO7}ୌ}OҷZWEqg8Iu=J /FQ&~>CYrw567,ZkX xv Vx AιJqsbhT|I?C7n@ =jDs g6++asU!? IZյ}tLy(|Ñj>+j66J6+ǣ7P>EtD(Kt]}24f4C:QXܽI#7uGqWDWbUҳcXGn o4̀•F]Z]JAaOwnθ{Ynk.U.Tq?uBcЍdJ=='Y]jҮ弘U`׊YŧvAGh*M"Qh?<ӷʧnOTt9HলT# psݷzVW HCԧQuw§~OspSc'5{xQsfၟ &r\&nΚJ1qaď*7:$27qyDy OjBȎw:2Acnu헹1 :W?,b厜[Nطq p3ҷ7tI (Ā~v=ֻ(׼c(JRrɩ>IfY2"-ONM_[ؙWʷ@ OcV kaBrniMi124C/#>t>sÚƥ^ ?1B$}uZ9\i"[ϖ Q`g J?P4BK[YoG"'v#VW48W+]h>?a ?+>%jg;yml3!zڊy;s+#sSí%ռ&3g\漸oO?v4 ݐIhRӛ5x{݉e=ҲG~AZ7rrp*q&Xp1zc5o,JK6ƸUD@r?V鹍z4 ΡuʟRi0#I% YZ\c?k>@կ|WclfGl#x`^VN;֟r-88ڴa(K+);r:'^Irǯp~m7~y6bXwu?j9ePa|3gYHZ[X `_SSIJ#|bqZY4lON6"}޷m,sn]Ff~ZFjsG%O&Q<  c_ϕZ,ӕ[UӴ}kܢI: XkD3 9 OT|l)LW-S"25 N8#Es"fQ+,Wp¡(YX$h73VrKVQ $ܧa(Sti>X >bkx }A鎪?02rO)#٣vwQv.Rca?`FXS}ߔzcA($3}ַM6[f`z-}S6#C(;+cׯҽ-tBHb lnE\,zrxҡU\MfjZW#G(E{ l Tc5ҁN \ѭ$=CkBfP798sROVmf( E P.aSPH-ALQҦQHLzb' \A 9z/޳s.EvRb8QQI!,ۉ${["ԂZxC$ZTMqQw"EbF 8R;44 942 D 99'zZϼܿ-(Oz`sE}z|q$0? i KڝFݣ8 sv ҥ&9@F݈5)&]Cæt{ho/-ȗ،@jobM HGЃ*}蕛%(4ҊINU)p$+I"C#;U3N 3BR`[E;II#j[oM9S{p?!R)o+GC3G4'洷q3?Uncm_:o#TL}GN[bvD1L?:CZŎ$s5;aԵ+-mqf +HJ\~Fv?u8kuſn,Y|zRx÷z[^)hTʿѽEQҮIl&Ys?7:MW1RMza99Q }aGm"ApEQ՜+ؤ[Tv 5'm/k챗φ#ϛ'M=H=3t6u.K(Hi? >HeI|onG?_cj|wݮ{'G__'k]Α^]YU;)mYy=uV/;ueqk,oFuojP^EJ*}AҾ}Sq'!H$vªMu>>%Ri Y/øchY֥)TN&xZ.|KҼ1ۦѮ$$%bgw ׍uG5s,E,uAr^JMFU;xzD0wɃ!}HsvASlMƆ.5E_ iaYXϽvv7VOFcU,O?yFkn9f2Ma: rv\ukMlç Ҽ_D݆3RK/1Ojyo,E [i q/uXaFtM[n{qJe2*وЬ%`F?B@3q]`@`O۵尵XQrOֱfNœdԔ[geeO[[G*ݸKᥡ>\Kc .,W;s;)%>U:pe4?J#f,pM1rz HrX@jh2@I4m3eoןP$>*ȢgL=# FH'2?F-gV]SzVU9_Ƿ͢[+ƊKBrc`~=W{6I-ޟi +povUB$CyGRĺ(RꧯMDͪ&Z}+Y",YJUKݮF# /=4ݱZVǠcxlzrć?Aӏ+cxGNb4k+D2)Ry~%vvp&B澈d#F,pz^=_IjE:Jϯ[_8Hlo21 ({yMW/XU>qN}CW=-=gg9z oZgFfBqA=sN~iE̚9|3hQs=\m_p#?Jtz%Ŧa0HI@^ضkh`*s (۸җ<1use w؅8$gJmN:fedy%1ְ~x?*uFG==:WkTW*0bdW NXpu M=*؆4O)mm]h;>X=P-(Z =X=*>AM&u 5"!5-J EJԋ*3sDj1ROxRi1i#d ֞#J_.)<1V-ܸD3-Wځr 4)r`SšpSG s RR@W)œ@W8Svʥ\h)qKP%8KP0To'X̙AVm׌]Z(U~xJĒ~@~9 z<00č??3=\ekR^#1ꮡk/4JΝ vWz~5bBgM,o>fp*Ic~~*A?VVu?^!1>Ƭ>?]v;KIMW8km~$V/${8dJ4itߵ.hVreŻdT0z+Ǿ4ˢ_jRX]G&hnD2#-p=iywq]C[ȡTOǰչxGA'H+HrML-~&,EUowĺa-"229ӊ>!;Do_OM 2gblu IO8*r9汮wi'yebRkϧtԬ) S=LC}!7r8~0" UFI=&36< QVdPNz =^µ$vsֱڗg1.A>>п<=Eܧθ#tϠp_.jNEEs迭r)9T<8b1vQݦmevypK?VıAiCo ʖMp:Wz#uN #VKٲ7/H6rncEX : ߮ >(TWVM~-GN:,ԯʹNtٴr.fX Y;p˿)溨?Tqb={Ow\RBL|Zeyy=#C[i~_ 2>!5!xR>bn?ytLl6]7_{jp?J,PFl`"A~b2?+{Cj?un2q=:J_2_MYno/&2miq*>l ?Gp'zyU8pMOQұogf9Z*skځRlM~pRA-V7U?c)vvI⺝wk+cfa_#[Ni;~EдHX؎cҭ=~@WQIHĒ,8x'5Mw}`R%nbtwn}{h2voՆc3jdOk2u*ߘzvob>Fm{( ?n: |'j$_*ʣnUJl}k2ͨ7SMnnA;p:} T;v@(_tECb12kޙvJ0?#{Sm7?)^?XY@=+XATtSIE'01lOo@CtT1Ȍg;G?O.k}a%?<@Tv"K;So:|!LT9E&)R5bSUgQcyٓ&qjrެ{('x SӴ6%5l| ՘y1ҽFL%{qndI z;so&,W3 ú]k=>'COU''ܞIW[E{weP[yjNm?\Vwh4 L;x— ՘Nj%z|sJ ["+󲨇ڜ!8eq /V@[VF)\ #ҭQ9C䊳K+EH!0Mr! xzT*\Q.LF)Du.)@O0(9EGzRJ4r `=*RyB6bg;"4BvPR(Ȣp NۊMoZ)v7易$ }zQT \ACU%j<؟CM&$SIDڔEOֻ :]V𫵖~kOCQ\A$j è\{ԔWQt5#?z1豨QTإ;7&!LV![v2g=?t_|KA.In%Sq+n J|7z{V{N\eEFUTBB²I|av9[6r5N)Ŷj68_ַJvF !j$5 !xN3iI~><% ]1) Q'~BW=k qfurce^#HZyG+b9^+3mQ´b*V^MV2sQ%hPAKcy?x䓚ѹ3nH.`5p"#}~tnsocUƜGqo{-աp1"Hʵe FyQI"G#0J ))L*:>L-zZYXiyG1URbL.jMUIZ9-p$q<6H?{¶/{(!w?ʨ!lă5.tIuKWdKk \ݝ[E-ԋK}>,ׯukfJy-FSߝV6q~+Dl 2LдZZMs*?c'Z 瑜椼?DT_&YQywg\+_@-hש뚱w땅<:c9f5IHPڣ2}I"kӵPg/ *wG"i'' kYɌJQWeIdn텞d6 ;M yPDE#t`v^/chNd06C=y/ *;ڥ54Mʹb{T֮Ӥim m<@'qV}jۚg+|=XVxѳӞFmlp >Wv*:SrwԶif&x:S|qU|ڈɂECJ26y҉=j4[(*zpj|,jyLV%O PZ04LPMJ ( QDI&b)<,@UOzκgiD]m $A]@>\xO5/»bQR!KBPԵ-)oλlֶ lT^SvO~Qug~ /SͦLw'/:Zrv&sN4ts,Qõ^K"?ju[ܣ5q\ :ֿmC#B܎]3oMFOfM>G24N d;J{#̱v,דA*(֯"%!OB:}sXz7W!S+i,ptzkw3S &c$tzrjVNMYJiQª;tiiۊoj/< ?#G]}ov"گ' QG"w /?^ƴ#me:Nk,k$E#X{86ՙ7y"H?Kͤ'"Wi# sOTDG_s0Ij6v92 xv^.Ig;ĐOֽ ziT9 cs9[]V'o ¦Ymq5vsΒәX{PD#,^o9-&%mWB2q H0kPAr?ӬFvG[aGfլ?U3~BLncWA?OJͼ7W2|dTs;WrBZٻgG9GWwdWշ+E82I/ߚWp*Ž-(};.eS}M]b9ZM3HO?fkJ~3-*BLHi]RHѱXI | Er+ZBO\#<{>N)|kd9.EJyF_ʓ& 74l`M1PZƳl!juL H\R)&L5&@E8)wqIp*˻!ozgƸ@ɊkZ7?-FIZ7hr5}d'P'HG'}k38J%>.BfIZY;}Cb4cI17vh0yN؟qQf4ġyLsN iš`~2@i$p8z;?JbA?ZC!UcMN8VO1R@u?=iV!5:TP<Z1D6()vGh80>b$$n/ƪ_Ound cVcwWv/6܃"bW07]x*BNB%guWT~Q ?|4*s{ Dy³e)aӇ?5?fΕ}M< WEsWdx5h[ך{7 }E͘qt/驵Om? H-SvfMŰ\' r>!_V֪גĚ|sǛsiڼ q[^Fy u|.IiܱiW" O\#@=jٝ9ehN6{y?o?S߲ *FA+]LMLww=zW?ſ+hPag?4>~S޽5ֲuU,=W p߅"Gz[P{ u laqarI@zǵ}q8WFGV</ǟ5j37"2 Cxk䳃;UW%[[Zx9m-ؙ1%0o-uSֺBLr}ׂxZWO ?5躯㴻&M"[xhɌȿ#j-XZ9NƗhw` }1^s/yD89f?Һ/^kZf2٢h^ x =Нb!IfU2?+Ѻ3Tw2:{iSY$Uqa}EhL[?VA}~eTsPVU|G\MZgr)bss DʹBzsV'#ۊw>L܈D ܁ԋHQ.CDh?A׊q(Z9EpV(*@(U A֟d-R-D\sMOl wBg8y{mn>Rr}8T*x LQi2~%A`ED=*TPzi\S 8:#3' Ddq)w4`A0AF;\+v>lTe#ץfMI{HOxeݧw@F>x^}|6cio4Ϣ_r띷UQ\8zboAv+Z?nWtZI˰j/ OWQ/5[ LZDJ)KR' -hfbPwrG֟|+R L۸VhrH AW87qMYkJTR]˾<9KMNϖMw`8#0@5WS Ƨe<~kna@I e?ß7q\[j %ŴK%NTcQSsLs%ARMkTEffR$, \* ZzKj+|#ɤ-x o'}F%Ah*pFX{{䵟դݖX_5RNiro-a+1<Ȋr [T+gpϐ1w({ҷծsD 3*;W{xKYI;G z5I<8$`Rp?{v) (kͪ*QVzySI92ϴmRk |a&ZA0s2WPr=3:{wvݲ+#r?6<=Ez ݺ<,I k 08:7 ӧ7YZݺC$ENsW5\~`ֽ^#ӴVv] F={7\ k9% .V]eNKIōFFjJit8O=kڦebJ"2]{hD29_?*YPO@?m[)Vz[~d^A_a_^qaڤ:a8Vy#x]t"4v)\0?:oc-܀ga4iه5cM6KuSbY2ߠeKԋ#JԜ{+h*i'WڞkHG#HGb^[c},G'W[ue-~VdwW6SBݽ GCNX_4gYwjw&{lw3`1FYq$|IYT#R^]My 6cbz$`~elgiM{Rtuų:ͽ-n_*SH1SY^9#( 7QVg5;v=>`g{?ȍ?4TCӃT.T[󾵚e'K,c'>©glĜ4n'B95.ópUC(@)ROLhJ6"= zRJ"v**WDdzlv?e}M/ػB&Z[\L8/1Oӄhu~j,~t23**ePSIޟ)2h*xSSO^O֬0*QĊӢ.~dp8/Jzդsɏ( Z,gr*}*srPԩtL:+; OlhZxҊ,)S :*61jYTwI4fbɘ<QƑ>ڍzB;7RU ,M 7 Kc52&:J),x0SRDc8iVGVP)GJ3Ux-Q'VO5Oio{zX$eQz֋D8SI(]NKy'!ZI*&_4-hJ:LO?Sy%Bi=wz~JYwrjTJ'yGf}+-c{{Bzש㯑6Lٛa2x}ǵQ4Z+-2K>H9>ztP 40xe\yIME0製z78|ZhYAs2rIN+qbzV)eͤ7<`.OfJff#ԏʷC˯߮JKg._<`'$WwyqPaݳW;*8ZVM 0t' /j lD_||}[])hB۽)9n:qg{Υb( qԯ A9T]= 2wFk[pAҝ+!\4ϖ!g]@ U A "g\)TZUt][obuA᪋]DE%I0byO?Zh9$3)m s] KF?LGձNZ=Bd i'*E ?SSvDU&#N0ʟ )Ȧm׊їY@FivbԈH5?JCs | )aNT굢FTԊj&-TUQK❌^.=xCvmpUGґe ~tF|‘",p"1=>;84VWQW9 CE%0ɊYL2Uc-0Qq򖌔%W ]8'T;XU,0>ϵT]ZEɓH*VfF,zE"H* 8Hc8؋\I/=4MH$"䑂ǠxuKW+=+8gPB*5ڈd*u}VYaݴ{i=^255"^ St1^t}sֱִd)xg X≵244{uʤص:3 YVc4aяZƽ a>SPfǡ=Ň5Rf滩N5wRUl5xIb1` `ioj!?7ВqҬ)s$#ぜs(?q<4~f=ojzjׄ-P7_?:qgR%/i[sSik$.X3OH pz~5趶a#QM]MyY,F,"$My4u(%cɼ<~lȞC-n#oa Msha9[C"P^]5/u{dg%3J93j Ȭh[Ee12f;9?~՝?gc͌1ٛQ AM N#6,F@AMVVVb89 ZXM=MWRjU56$z*%> !뜌uqFsd?ZDR QxZpZv&X(`o.v)LΒ E7˭'@A1֗)j=SXq.0_j`ԊAhHW@M8t dnXA,@Y3|}*H' 8tgPǯ04xx<ՀpT@]nh5F^O}*#%C-D^P)'Rj# !`($Te.I-]]炑W5`qrgr}*#4Vƻ~skm?2@X?& cJT j~H$YvVq^oZ+7 ?=5>0 -4J/>Njidzx|N.R!Y3嚼 "$zXDzvYXK{|a$tJW#ݞc];+72a`} }i"A27_ϰ아=[V:t&.۔杠d3o ʌn+^e%d{ybY!pzެG *U?쉞8;Xm-T=L)kvc7!s_FŭtfI%%]Nx'Zl+|v+a֫kčW}N;+#M6w]⌛I U4*b$$r?vSj>6Q:tmj6tF[M2?"}jR^KF=V\ q5}e5& 2*r3m g5 M4h8h3D$Ե杜JD~@3Lk}.r:;佾3/m-lm^ޑ9'nNeHz0\r=^Fv#~⛳搥pҷS~z IET ; q\מrR{8 =5D{~\" 7wJy?X<ͽ@>zЎFF,+ӴE\lBbUViO^XW+] yBGk?:tU*?@+Rs$IJ]$vԟ(8a u깻69(~sO|sIriГv^RXI_&z$C8q3pX& %8ryE,ƫ$XP0AxQ\V&4i55F5|@c:SՃk ,QzR:בQG235FxzֻV>m2yHAG}}+J$KTUPNR+k]]Q#~C#V^1}|KYH)i5&KVPA9HF[xV""& ?oLt5:nHF>mr\HIK? fzs^ :0V c )B MHs?~+Ӻ8=t<'].t=E.9@dO;~U^!^ 5!1Hz`"u%YOU#?:ircR;Rcu؆VTD8V?j,fJjULvUE+1P;4XQRF <,"ECSQbKvGJ fS-ca۽8ܼ .~EI@皌[h'iw \1-UHcRƢI,DYLtfVL7RnXE!4 u!ozzm i7c7BPRlWpiqi^W5d}Ң{ş²̜OXei\9- A/ZDlU1{&Hnyh0GyΊz x'yL҅M+ D9OHV="ROʬƝ(*e*ԣsQңg.yLZBx^0STK 晚BԅbMԌ =Db3-Bu15 '"+Gxn0Ӟʓjb-&Ů&؝F זj0/$>E ? &x)/>/oŽŸr.CҸF])؜nz>rտFutT'ް~ToƩijE 9i);y+Jrw9/,%O'E.6b$OԓϰGj3tTsIJgx2!S51VLVexc& klHT\p=wAR]_Mn-Z`F8;{>c%Rȃe<'-8!%O =hSWgʶG lO<ؠP֋3?DϏKy(Q#1u)$cXe5UT5A裒߇jϒF#$fڊYɥ{Up#Y-rYʮu?~W=\4&D*zkx+e֩Ai?s9qIx" ԰|μ1y&]HS*Lҽ5 fe(Hm+Rd}su1$r c* |!re$,@0ytsK̺,n:HD&_4-L.!oPP?\QGRErC/CU5E&nCV" pT\Yi6Ko!-(x*:ʓ]㡮unԪ P)J"5*) +J)p6Z@JGK"H84aY  ar$FV>BjSZ^jl'MgVij6ޓE(IQ4Q^oz Q- MUoz> o5BҟZ{Ա[Ⱦ)d̩ws}[ǭKދXcHȼ.SLH 9j5Jǁ5$qAJ6655eEXHҫȍXE)X7e{הzgR !Pi"5i Pɦ3꼒{cJ'ZI})%UeI`ڲ6 ^z>d=+UBٱHzz β5&`Y_Un屄}%v0uKz3ouo5A߽VA(VJ~TF=OҽWIta]0Jܱ{  /5X39rGʠN-;ؕ^n|ֵuGn {jP0Xctķ'8(S.aKG[e#&A6^S->lu?8L0u%}9ʾ,kcz[lZ]sޞ&C(AFtZ/4Y-G$ݲZ<3BucJZiNMm`4g`{Mq>`=Oo˚➳<ѵV6. û@8J KOݘɹ;M bʝmUHEj:mi8,do"?:A}N@BEcc5%5;QcQO'z.[Z3Տ$tb+5TtkÕuZ]d]khNŷyyTX}HOd֪;IxQGAR5I uB@Řǩ5u֠k9TZ&Y4qQ]yϸ"5ɷ/'5A˚\ N^Eȫ*ŝБ, $|p)1Z:9ִ_.ܟ`{'ϧҫiˋ<ܹN񤶹{;$#1EZ?0twIYݭ7 knw/WxkYm*䬹kIH%OM9Iau'WSErT+Mҕ`à |?JjFӒCTr=Z{$c*:® ǕS]cNyImd@~h)VjoY yI`;K/;^1V,Yb0ƙs ׌Mn/-ux4͛Veĺ?i.W^?R {(de/c2Ӝ]cLtA^ta x3\x +(+OVdy:d"@0kjs\穔Մ+(LPeQ]҃TAQ&''j/,(isjNXkb!OQLV9֝tdqȠ(4<҃Hv&V;5iw{blK!}J}8=Uy0fXHd/FӏZK\T/?=j`*RT?B1̵,@fi}꩔,0I7A}O‹d2{$ x3XNĹv#2n6I5iZ,fH 8S$(Ķ*jtCK}*|"JC B'N*ŠSHqS([zgvPZ\䜚AKRRIpsM 3L4&1婍%Db\T>I1UnI%ɬ6 5O5I ҖC/~rcsԟSYM9hvF]D:n$3,هʿA[B( SV5N曹.kKω/Jm39Q?34Tʒ/Ub@?IzU@/%$SPYdϵޡ-PK.94rޔKXy֚/ǭɛe >cl "U㐈Ix֦~[%ǗVI}fF7+d-Mu$+<0F72x[Q!S&=떤]g&O6Ud'9"2zJVujQwܥ"I''u֠qe$uBEZbƼ򗯫AVV&%k6RoDRfB<`tҪȵvE Ge6):"0wQϷ_[T3pXO³SFጒ3CᾓbAQ J}8iA좎r:Uu5rk&:סFW;HV#mZrпcQXGSɨ%8h.eb:qz?S %Rtct?oN"e;IO+P{\W_x j1ݪ>8,7xZх:'kѹFTsGQp .y0s՗i,|sSt,W^ 3\q :#u-)[Ys~5 \qȫgT =qS, AHvd2`pqUjW!y皣-\B٬z 3I= 6GeO5W}OLr ҕʐ<0I.06&ൎ>Oޭ`暉}ᶎ"oV y(4CrLњfiE+vjJWTa1VEW*q6Z?QKxV,c)IrIjdj*@Uc;Ҵ>J zA%w.r߀4isJ (54xZ4AP3e$HQ<ު5C.1%^RYRU$桳x䨉&[Z20K5ƌ#뎕q# c敉=Av<ִTG)N1fQڶ'zVu֩#L͑95RV95RAkb}+>-泎;-,1oj| f3:W6F5X[(Է2$SZq˹k5m>GZMfh;UiXع]ǧY ډ\͠IIb!uܬ;^a-.^w$/~Uzm)Iɏ8+tyk5㖧3Z ո"Tn?Փk]q\ax?tV&%aX+J/GVmhR Ojq$?ks#Nh]^IZ{>[] X)ޝt4Pkc$ N%QIZu2 dr5B-OS D52Gڥ:Rc#"PE3 2֢wTT X#6K,!{ZOJPxCiA$&b$R~XAZFPRVf5)F_!Οyg"\}ч},Zb<+Z"nk5dcFFRi9&@qJj%Z.zՈZZxy 1jdiVNi&,iVc^i#ZzL,e3) F^$.}4RBZJL!QM$))L-I1H,Jc5ZYP6;iM?Z4A,RI}I-B^19ȩ"4۽en^S(TrFIxKǩmV=MON䙧dD 8$?5S4!<ұ6,f]7Ftힵc&TcrbrzT;NMi4jJHVjޜ犂Fff)J0k6zbFRI5 SMM#$B*soZn2)8'fܷz2yހ!GҴ!iȨ8~4##ROk5Vf,I#N\wv^$vv ݽ?޵g(6H!5ñ~Tߩ_5OrO6}]RdukJj}3ZZ0d:WFAR2=Os_]L1MۅXznwOhϸ#G+yC0*r= uy+FJW^O$٧*/'^z=9?:d^oy]9K%B^gQ07uU&h&Fj%P"5W NSE,TMZCҦ4^jMsV<4CGvEs.֓FUI1/ef}!HA@ޥ"4ȾpLrA~}kP.0Y>qz:Wjs#-hx298*GM:j0u.L+s{{g ^x5(p?SYR3 YБUdtOLZ:)MG2s]W5VUҿk6>O9,]4lwR!'>a*{9>i/c/mʹu:;BaT=G_znJ|SPf-584-=EbH4f(@XlH=ڋqܸ$, w#g5a,Ơw?ZU gZewzs^DU_SXZkR@ |0&GsX~c%3Ǔg FTr(d`rztG.?Zb]HK} dIx]_ ;mFI:ڷZ!fc~U$Rb#4m܋b&i`sYn;zd I3YsL2rO|**<-=V.Cqw$nTnL>ԡi:rid'&\Ң'&))2@ic-f6`s^25_FאSt ;~UۅmKɞdy4jiףaؔPj-Դ"pqNQ@J "]%!۩fMC5P)59M 4)ƐnGDb0@)RSi*dpjU>*ATg(Iv83j%sQgZ1(u GW:F5i]276?ŹENzdU+D܀~\{jcJnlp׭5ӗR7 a?ke;Ocq!Y{ !9x'[U ؁=z#Idi#3:S I7cӌU|׹J$TN+Jj iIp54ҰX<)IX4yxI&sM-FBqQ搚Lc^@QOԊ*No 5RvV##-FV ֩NA?JYxiXf8I8`ZK}3F8R:`VaOVoi.XvJ';MlkFZ&W$+*VH4l{BZLF{huӯ(鹯`qڭFB.I<=Me؆9؜Mh gV{%wE?Szţ*$=OVRK'ʠd9?AWE 鹕Xցb6nqYYՁ_g[U iUp@q\'^s4<6mFqy{vXYʷ af$ÌIvf6m\>a0\~psR-TfT,ޑ~ERSB5QR=fe,90x*EVZZqP5R+0ST\2sNߝ;m.*!s4Zp+T܄ OJQW[ TR?ew-j֩ O|OTqHÚRqM&!6Q*dآ%杈lu.i+fLg<hf m;W=yˋS-ǽPzfXb~D\5j7fDJ i[y`RmS:*yn4۲u.=uA'a9?*-VQ0Ӡyq=\V R B9{%Ǚ+nltsG [jLӃT9]&d$IG 9'kxRz,LLܝ=L,[JZ.h3se:CPZ٨fݚ3Z]b0E 5 ]Ԅ3KH.i(j: zkGt*EjEd٠i괪2TY*O R*ԁ3[FG DAga)l03=г*ZU:\ȣ38"VzcHc ~ q5zgQ\20\!כTlӴS<̚|7 U#qxIPu%NE8NM%ĒGABۻ Ճ`*奜#I(ҺeM `ٔ,>>U9CFJ#+NwKk2]Y0%8<oCZQ4=यe[eNJC[fe-*pqZ+ ls+Lm%у{˗ 0SU$(z{{Vz1wQFMicVN_i:*-HA2Z֫qdbH .$ +UԛQ6"4(zs;W^/[3ϭ(R7+&d٤>85Y}Ōw$&bA vϧq5uF"[3qQ5kDx5fZmuf}ǚj65#LRL23L才MSL.(L5<+hGdijIMHzI&4KM5d1hFl\iBN*%G,U@I'Y>^k.'D)OqYP6OZϚį&j2lќұ7VI(ޢۉf7:{hf>4c2@isLB$Pj:\"L҃Q#:fEv:{yG.,hD #Xڒf5(4b\ӁA=iaC58b,sY.h.iXV%\"G~C5e`{+:楫wD+8trTG}Aڞ"B(cL o_moEsK#">c^yv<qε ([x K ՟cL+n)E=Q#4d4náV ԒfN i۲1J8 5z֩+=QRF>eU%'h苓]8Jżڤ{3P$T+wM-}Xj:T*v4JsJhQ TH֮8f"H3zEy<65hHڙ(٢ BqEƓQZb( EXQEj4QZ"̍^YqҊ*<]^hFU=k>YsPuE酨`iXZ94sK((Fh)sE.jq?Q(j(j.i)N }9,I<\E#(4E8K(amI aE!ӨץWC*ԩE3(uĦYUQA*tQViOa%P=ɢU%fri@*=^~kUFEŋQ"tEEOz(إ6,1Gr*GE2iIB?(TW6ȋQNhѻA'˗݀{j(swF]]s0M4Q_[&\_&ieJ(EeƔQX!Ji+3X:U)l|cR9asyncclick-8.3.0.5-async/examples/imagepipe/example02.jpg000066400000000000000000001143021507140761400232060ustar00rootroot00000000000000JFIF`` XICC_PROFILE HLinomntrRGB XYZ  1acspMSFTIEC sRGB-HP cprtP3desclwtptbkptrXYZgXYZ,bXYZ@dmndTpdmddvuedLview$lumimeas $tech0 rTRC< gTRC< bTRC< textCopyright (c) 1998 Hewlett-Packard CompanydescsRGB IEC61966-2.1sRGB IEC61966-2.1XYZ QXYZ XYZ o8XYZ bXYZ $descIEC http://www.iec.chIEC http://www.iec.chdesc.IEC 61966-2.1 Default RGB colour space - sRGB.IEC 61966-2.1 Default RGB colour space - sRGBdesc,Reference Viewing Condition in IEC61966-2.1,Reference Viewing Condition in IEC61966-2.1view_. \XYZ L VPWmeassig CRT curv #(-27;@EJOTY^chmrw| %+28>ELRY`gnu| &/8AKT]gqz !-8COZfr~ -;HUcq~ +:IXgw'7HYj{+=Oat 2FZn  % : O d y  ' = T j " 9 Q i  * C \ u & @ Z t .Id %A^z &Ca~1Om&Ed#Cc'Ij4Vx&IlAe@e Ek*Qw;c*R{Gp@j>i  A l !!H!u!!!"'"U"""# #8#f###$$M$|$$% %8%h%%%&'&W&&&''I'z''( (?(q(())8)k))**5*h**++6+i++,,9,n,,- -A-v--..L.../$/Z///050l0011J1112*2c223 3F3334+4e4455M555676r667$7`7788P8899B999:6:t::;-;k;;<' >`>>?!?a??@#@d@@A)AjAAB0BrBBC:C}CDDGDDEEUEEF"FgFFG5G{GHHKHHIIcIIJ7J}JK KSKKL*LrLMMJMMN%NnNOOIOOP'PqPQQPQQR1R|RSS_SSTBTTU(UuUVV\VVWDWWX/X}XYYiYZZVZZ[E[[\5\\]']x]^^l^__a_``W``aOaabIbbcCccd@dde=eef=ffg=ggh?hhiCiijHjjkOkklWlmm`mnnknooxop+ppq:qqrKrss]sttptu(uuv>vvwVwxxnxy*yyzFz{{c{|!||}A}~~b~#G k͂0WGrׇ;iΉ3dʋ0cʍ1fΏ6n֑?zM _ɖ4 uL$h՛BdҞ@iءG&vVǥ8nRĩ7u\ЭD-u`ֲK³8%yhYѹJº;.! zpg_XQKFAǿ=ȼ:ɹ8ʷ6˶5̵5͵6ζ7ϸ9к<Ѿ?DINU\dlvۀ܊ݖޢ)߯6DScs 2F[p(@Xr4Pm8Ww)KmExifMM*JR(iZ``РC   %# , #&')*)-0-(0%()(C   (((((((((((((((((((((((((((((((((((((((((((((((((((" }!1AQa"q2#BR$3br %&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz w!1AQaq"2B #3Rbr $4%&'()*56789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz ?њnhOcILi\.h%٥拊p4(q\x4)h~iE2QqI4\hvh&i \43ACKfh4Ա~i.is@g][iеCA4:2>qcL*ah 7a.iÅJ횵ƈE/ZjʚcIC=)&i搚w)!4AI@4 1ؐpK)~h'qO4vf im7C8?{iZ0Ag_NZV{5`n$>lc?d{xCd_+v/g02{Exu)k}Ξ(B((*+D\HG.AP5ƌi ZF"#^1VDKQE ( (n#cF4w`&wÿ[{/$X+q‘$^ӃZU*NQEQ@Q@Q@Q@RPzs /uK\_S{5|T)ifީmnJ$œzVdqK}WWV{;#6m.$?<? q2ƫN{ɣZV~}z5mC*M#z3Z nLG̡7t˄vf{&4 (X1ԠE-Kd* ;E+ZZm-+].}j((&hh= Vpjj>}k9M&i͒<I3LL;f`<$Z`<p4#("GJMeȥkǚ"*VfYw0rxʉ!&lk+fZ6mQBAVT+f-VwV7W1eJ Q{ryI[֒O<>qoZV] V05VPޯ,fUAV5ym,lK}\dU m,hg=~qTyY5 :UrG'Nnճ3Ƿ0/u\557zDBOU*}ZOWN8E#z`ӔZ\mkg>;I;ۛ E7v`#1m~#>.[?y-5$n.X~Ҿ4xdyOQ58W] uJi'1qèC"8}[K<[G}auz|.--RَKf }A#^+8>(Omh?,2E|smF,)1'VYJ>kqM(#YN Fv~_EL5ZJGWͩY5Au 8xp` H%E/A!>-ZcW0Ŭ}W;&qx-W icqqTe^Ij\H۟2 M.OW:2%E`F9"i˩_qtKGH@jivJE!#?Ry;{=E=8淋Sѫ9MGTgg{ ҭUd}C%.J8Jd*dPr:(*]\QQM&ݐ[ЇucPt Vݶ= ^}sX:osr~â{TױƕersOӡ0*.X={_U[[:"s gd\(f}OzKUt&kw=?OͶ}áЊ^IeϦݭųr8e'^jv]6cq=T}x;\+V+ z"ms"&k{ zzYݝس,䟭rV(iY)7:Jռ]?Jߵ;hNcqku=vrq'" Zu$ԅR &bkȶc 77Phm#@؝$uEĸܕN4YhPN-:Ӂfh:oV7ׯ8}/p9PћDӁǑ =qӃCnexxFI(nkOB`9>W Cdy}+R8$ Q]| %9 ng-p@t_ /m 򉏝VӃQM#DSH֖*QKISq (RP4:Bv*EI `+Hv,R5pBfԕE!zTڦRFMcH(!Hk#d.i &i?4f3LK`4iRL֔Zd3@4X+ 4@V1E&{ENYqb2"OR+-gt=͘nEEOSVM#n*zUXf}=*42r KDy%̊#Ebz\}rޅ[k~>N{-^~j(TX|r-QZܺ4?1]FGڻp Z|E J6uC S_SaHf#9ܞ=eMFw:F^A;G"򬤏ڸwfuĊy?tHO<[9v-kF T@sbGg:+=N#AQВEW2b#Rd5=JC nt!OCұb=K#<$ٓt5NeA+ѣ3M]VD,I3F@'ZΛEܥ<7ǰ#@r*_Ղ^:"ML5 г/M iH6M#(\\ pq]L!9 z~UIqZ- 1Wa؎A*EN.,r)el Wgv@zqßL9bI$'|*n҅.oyPWJ kZkb3WaQXۀ{V|/`k?ϩ2ָ ZK f9%KdrI7 Z#y1'UYmXKa誃SVg8?> u&U8;  tS8KZIi` Gcf;nc3yc'$v5,^%ּzuӖ8V -n#QV-5t )W]/\ٳ͵E< ~k>/xkkY _2;¾}jB˟ӇLSOc.{cW?c誴R= ᇵ08HQIY1X^P( JSIEƃqҐ(,G(?{NO4z[Fjx_3I=)DYsOQfR5H SF S(\曚)zPpi ,&J .j0i٦@ {P;ҹ6\"RI0Wi44<5r6R!7ST;Kw!N PJlBR3qP3dԶ4Lipz՗L Q*Ԭ0)T$}*OP8056MUpCd9"O~Rx]Xp{Ak ENuУ;4ZBY9^Uia.m7msd]Gַ\Y7Iַ-N2х6=Tl͜C!q9GSޟt)`lC>JnW̾o{ڭmb\$s28m̨Woϓq{i[Bқ[`ӕ1> xſ /;εB]GQW?zIFJ7|qƪVoV{o,c^dK/C|>ok, 2WSv^ Y קg;`Cڶx)C/;?fV'ֹ I.8Ү-"-yO,?tEm ^O UETUFjx5Z?dN sXnDO*Ta~8HvjӃTؗCKk{; 5hZd7QJn n@+OF.<}YP2I:O 6/xYO1߫oj)u%ʅ>TyD|MKbl6径zWMF-O[VJCG~xf,Jso aGx}F0J[7Sr@LV >az՜ब͢2lS yrVv,;QE i~ %2 IFGzi-!4&"4f3VZ IIޙh\f4SE Fi(vqHZMF@2pjF@gu#?n)2Egҹz< K1V'U ei3Z7ԃWcTnBbQTmP?hc̺(&oBH*gjVc=8jy-Gn[p}z՞i3'?A&q-*#rC92GNR7Uiw kϠ+Xܻ1 z߇|GaǛG+:ïX]<qFfh^H'G_Bg63K]ZoŦݮã"TG+]F8,<NHc_W_ӋK 2aEmJ9~Rϔ~x5mx%>=#mOW^P4I+beRNRmݓ4NUzvq^A\U*'n>bxK]A K+,Jp@<iYYJ ";HC=GX U/]#Ji9#mgOo"W~#^)PcԴ&e\n%Xr}eԶWRh[i#:t;//OiVxux D95TIMCMD]>OzR(rɒUc'O\jwZYդs֧I+NU#)%TĒI+P,k(u4*:*sI=Mz7-#Vf.ziF5{h$Y M@jZZT:m9똩"U(@*z)rZZ) 03|G[:-֥w+#8 n{⻫]Z\tr~*}0QA?:\MɒO*5SrvghWxCBÚ E{]pVkƉkjt(W!)QON p%¡,V#S+̩-!sFiR@O4m A4HvJLfH٤& UH\RA ;^1~[^ {^q~-fhbȎzXF+J*^UY;!"2!TǠȨ3ƠV V!뎧k&I K~[k?tbY,y$Tua.m(WIMDjW5s)>aQy8=j0ЌՃU5vM*MجjJXuWSikI]FKw~)sWd[z֧+ē."z/6=ǟϊh$U3-4qK KrF  O%xN⻭"`օ3y܍_gZ)3uu\2zGgtl&ﲷ`X*fj/:Ȟ6 e'5i&sqX.^ WF%RއdWG~n8Ԝ]jSүZPzUa%}'ͧٵKHTM[ 1}TWq=tƤ%<( נZiSb@~>>iV\.:!Z\oc4-P׮daSX/ӯz<7mY>m̘3\0se]LPY%AoEUQ^+ lm[Vd8/Iu6m5kS64${@?:&qR&Ik+?9G۔Yl891k)T-6o~Qqwȣ|108yA^6.*gi:,úQ;zV$0mXQE%0qT770Zd8Pu28Q+W/TJh.'qnP6ruS\卢2i9Xy]_hn7ERvEf; jm/h zj֑#.-.VV9/`O խU]lj^b(V84Y_OMN/+ʽR=qej )E?1Ua~A֢UAҗ4jH{dV{< *fҰ/zkzh4a؆HPWFI$TWPӱHM%# >f 4fHq4f3THvi3Mh;8f41٠nh&SO*i)](J;-*`F4FM݀G>P)Ч3`U`F gk 4r %y|U&TZ\v;!BI3RY6~9r*yaRlj9W+0 V*,dՌ둚eL|IH5v8kbU$Qtq:]U.%]9<0Erdx,@Zk뀻Qa\14NVk*r@ʒW&orU(?ݷ?֩L%8K !\P>1iX'/e=ǒ)pe^W< uWPЙU~NO^O^Nsk%l 66Kty&s[/b.n6y[78UeFA] ].Gm [ףx;@O hc^C4 v9涉>_'dryj`U`Lc\VwEF&cޭBu*hzW`ua"*Ez)_Z3 PT9SkJ\HiG;\LXbf79s?O,AdWI@upCA^wunuI rPF4wo04hݶ%OZB$rsHO}nmM?Q]>񥦋i,$Ku$UO #fbT'xQc!a?lX)- uE^TfU rMҨf2,xK,:0e9|_AִoKieu{s3I=ù e{J~8iEKjPZb\WApBBj0~4gUJQxQs-ͤD]_<=g$7gH*?5e:=Xt6X#$}'-G &VVSEPI2>>ffpy5NcV8re8K-P4lB,nd1og+=X+[#/$(Tswj'|MO5kJQx`T(׸g)/SRME yU"bEsZ| 1ƒ h+UpBA1ߟꪹcI!HA zW+B.RVK͍y7dt4+!ʜ)OWBmHiylh8?q ׭z3Zjt=7\\nE_kLC3}t YH$1 ! v ?Q5hF>\߿nHWО>S?Sv` Z'XP@pٻcƶc(s^V&F&m*\f9Q="Glo:"/"#5xE٦r@9e(Ւh6H GRr<֯j6xV>C]|O[:d5uaEUoC+ʦLcm![V⠇H!3ЄOB75V7uEY:-2"ЌUZ&o_=0=j `?Eҹf"ZG Z羻59n$W{X >c'~내LKMQT@WQڅC1A:d$kv>$5:M}*Y4.uk {fIbIJuo\W,\]΁E j5V ] X 8ZhV& W }яQ,yo=j,43Iftu &6GQ0BiiH$\ǥ+6>$sKQN44&"<$gnsQI+;fF,}雫Hƪ6%IFj.7Ty4X 3Fi,Q&h34f&h0\aS٩`k@)sMhK49 CFR 2nٙMk&m\sb_sC= 5JIBXG$4fg=ARҶzw?Z*JFqvQu,s/C޴!=+:~HhWb5BW WucOJOjH"7jaRo+K1+FG' p?JI-̅Fƥ o;??U-Jmbaiӏ5Gq"[[ LF$|ryb?̎X)Hҹy,p+E7#Q45jN92n#JrvFQՙL&9#NN~ws4G #(kNdRST5fS]4W+TƷ)(T<ק< ^[iȲ02A>歨TRZ2_-܅l G$};U?=+N%aY~FDM7F;9|dI\UmV F@y^yVAk*e+^˩IKִ-nZЊ<`*w:շBXdk56D550烑BbJqq6%’ >0/UZKd_I2f:m=bc'u"=*EZrH܎iLj+DuTV2u,gMm9CڑCǡC`T5EWh6!]Y\ZElp㒿A2=O;w2,h#5[=NU" v.NANNkdS4c+ܒ$@e9%p0}A+buf1Sոյ|%p]5LJ+Yw]3P5-b;K-/Gq!>_>&ǣ薒\wQ\\tveO;W_"kVtkz_IX5Īr@6 8dL^$f%A#ӊ}JIۖ(P)UozZ:Z 85V 85f6,nPu.QطGU)qxr)OΣ49ԛ򏐹5q25XF[ޓuZEb]ԛ-nHdQn4&-Ի,K CPX,MFV(4j i`vj<4RE?4f /jv uys[o5FF &uPO y[5A a#ޣ>d" Z4z j8&DzU5r6q<ʱ-ޜv櫚66#޸1nw.g̊-֭iDY8QAVTS¨xؒ_n2[֞]kEdf<#BGiس'1ù<6)qLcO&km%8FIOEԬY=tWHH`ARZZGi1ǫZɿY5;[GJ0Tsۢ+j>%+kq;S z{X-}aْC>c.4]6a,`>O+d#XU h_dԭDx6?qǡ&[nm&p#І#ڴLsV_NJfk0iz{ο6O@y k呤ݹ,ܓYT>TU:ՆMF4p߇4{964Ȓ8cPuOֵ ޽:[ ţF>2WUj7'BWv4ϣ!WnzyZK^WÑfcɋYӯotD]͛G(?)A=^t>Ii^Y$L֊&F!@Ub:+lt@3{35˻Hfc'֦)Iy Uޫjݞ=p[<=@FSՒZ MOUEZ}#\׌l,vLaiK;Y86kӕk(J"+ K@U 6w*-xnDJv!E0_J2})UiDeX^߅Cf2*T&}8Pr9! nrMe~g= ]3~"ۺr7k:O쐘"Ԕw\'KJzS9}CF%_B J0O#]~o[XpyIx;~hJ ;I.4Ź#wFF{Wc^IN6fӧ̴ckp>NWHF} nĕҡ*r89&AU:W%A8 p ҭB(SKկfѮ$mC[?xkWIDS0:`nOކO_E  lUUj5w4vCSU` ō7RXw ѾbmԛԅDnwP[;wQCRu;sSA%sz  8QA]HF1G@*dHUM p*qcl?蠮ۦ<-ɪgB:-X*њɣibWajψMMJш՘کDjfGR%5aOJ>a58ѪUozhK ӃW NEy!o`[sކYrF 5A}yKc 𫞦57ℜ]kNApa9o[k$ckYu42Gm@?@kWK-rurhqַɕV՚duloxH gsCR][&HWdtjg}uuu%G\ZVVQ͘B犞8 m>K xN$hѵ?TtɍcVy*4tBs8j*t ,qjGƤu:RDTtdo_CJ:}^; }T7G&0$Cч#歹DRE&K61(xe>^7ta;/gu=i;:x_j[d'q#2 kX$EQPM&yLz(ԕة_vJMNc{i ë]-{8eېNߧjهš2nt`Ôj_NqSq07 ]rXXyCcNSΰx9#؎yH{KU:WU|BԭT&wBn׃i~6/ܛIO\CF,6 )rG۩뽣hX?(zXҰO7;nCuRC67{;;{ѻޡFz,;w֡J[>aX鴈vj||0`C?I\s4њQRʌS@/#m_ޕ%V$ReJ U "%+[ 'ҬT-eeyz3.pUKbOSQ$$PjX4 tUk:52:̜UI1sHhsY2Un#U!Qucv*үC 0E 5,c5aM1!QS,\|5G= Hx5r̓442G4wU[4Jqy56iȻE/MgpIo" d5\HL%:2: {K$jF\qZ\x8SKV֛wQ7k$3ASg34''7va99;hYcoBE\ȂD(:nph!.Y\)HV"#lNqԟZ?yr]ԹWf^ZR8MƞЬ,>זKۗ#,'Pt=?z]i亨I?56d*iWXsDSq~Vj~}vFMMmmZ0F+VZq,DzoCVI^9uY q8>.W xq _3_!zMr9eAF\2-&[,Pkimh$h捷#U>s{{;Jr[k/A O Г+tV)okG.JrM]]Z=sLKڳ/mNvnJ?-SEPW1G}ȉ_kCÑ<"eSo/ݽCϩF]SCsZ/޺<ב{ *0\)JS#ltGT+#su85W 85sz,PuMŝnwQ'Fu.\bmowѿ4PNJuC\`&KjPh(U=^vsr}{(ُ;D3̗j1ɩ)i#݃rjbE1N+"'bҠjkL$]}+AE @beIݏ^Z jZ9=pjqPÚQ9fniOs& 7'4CX4d" `2[i׊]9r)G_Σ$I'=˸!✠#N ȅ-L?)ZLɐATT 棘~j$gLٖU\ctҥy67$uIbhE&Ydz^-O Qk) ky<p/0}kV~ctѹK19me%VomӊqͧͶA"~YC5rq^9Ƣ拺9%fTڥ*sgjS-b I8$hwe_pQ2G܏+2*t3F{ wslq|#|#pT)%-ަe Z=L'Gq]u;4'xCjG/ieܖy`z/$]ܢ0#{VBn9N?ʼKGyQ W>լcIȎF0UNյ_AN?]REh.ߍj9_cB 2*}{IIVrXt$tax:!Glܟ˥tN󦳥xoS2WFvEn^ 'V@Kifn^1VRSH {j{HiN|N UNEVŀԻԻX,N}@b}nwQ۩CT;KwRsK٣uDb`ԻXV& V+Á'c>9nwJ2T#i~eL!ex'hjH ?±tYF=J VM^Z+9mÐOCTm9m!bI$\3KNQҙs0IOj,G& ֞ uD)A!_Sf.j^׋& Ӗ**%G5ab>Eg7C"Z>:S*tP)ܹʃ*` 򞝪rRN QYJC8RHTz$g\E:&bsI3mLS_4F:)\#bZxZ-<%tF&lo@Jh߅a ̷Cҵ}~uE_4+1ךh bW5wnAQx:sruE\OzCRDմ)ƜTcpu=rKSk,YOOv.T\zcO'DTOP܂0 ɭ Zol__!G_ʼv[%AuXEDk5_De`T uF$lV̎ (SZm&>Jz~U*);ӕ#߄l$x (*=s DL^$0V|?j$xbmo^*{2i.l:YkQQWza܊m85FI`~&-Ǚt# F½10{,_Ii!0\\}ASq.ǕQmt5z%Q*\c֔#5QRCc_&g\jF*FQAYSDQRAC/hY=Pv*ż۟dcަQNxD#}+79+<.xm;lq0Ag|d,rƸO-3G( B22 vG+ѡM954xE8d޵(j>/*OO֘ISՠhl0\[u.lɳʣRIuB (jV uEP S .8e#vqZV) 0 ' s!˱K/ٮ$*ՒL @_Q?ZĥݚPj# 4Y0aN QN=((jp54y5}C>C у(*AR29QW,林ȉSXΟ6p+-tc+9m²R2f`$$ՁqSx*\J'Pi | j5TǃNOQR؅SR:Ӆ&Ʈ9EHR)楰w&JjԲY"9ȨT\ɓGz(ǹiE.1ĒyR($U5%cҊbSJ8yИ()q\DX@*X" 4'Qɰ ZF=:3CN RL FLiTH=+mDVW 3WQ-&F.:aQ_K죱bK!)ZC 0=f]yGrIQ _Bq~~STǩ\Rlw j4|VZmdk+F˨N\ PUJּNŁ?(X*;(jč ۍ:(R⺚ƣzDG'۠ 6Ong-Ni-z$Վ*+ͭ1 l_&B0O8*ûV{+9-rZ"fwvF\p2p6U fO9O˷/-$/?OΪ ?uR*R}N贺 zVg ӵPqҽJiMY\7$zBc!+J!%*6dLj'8Ɍ[F#ٽ鏇R#pL#<,lm%On*&Op7^Ra%chYa\q'7_jϼ!ګrkݎ@Ŷzͩ i^'z:gZjܧ(,K1=껯y֫2GT$Ru$AdFxz d/~QGoC]MԛX!b0:=*Wd^AXS)8DA vvjAQMǰu'/;u:yȣrl0:; %자V UZm 2x*Pz*( VU淮e\B2Ƈ`o,u )r;ף֋閶oSgtM9\?*uϛbIRǕV` N2}?F&֩C% t ?7Oclfg;NlN{_'V]wۨ%& ڥb?REB$С%N{]&\db6R*Zy0GV"H1)Aelbe`:zj4=QmsZpڅ}ق(TD\J9Ia*WEkh9Q4ueAwѴced\*K1ltG5P;WRt$zNUȇ¡qXNu"AU.oܑ8s/q.aAze})>? }͒hOZAP5ZY}Mc4ˁ֫&RTEj/ھyVqWd^3Ud.MKb!f 8$>s!ڿAZ `:zUId駫ξi6q#  8+[@p.n6ʃ-AU} MmNi6r1yeܲ*"  1^l㵓9qXXpmMe-D[3]I긫Qg8?B }%\~$fW\t+{]BLu(6[d8#pe[#->5zrTS*x >NΥ]D6/g[J=jQ#畽VLr7ַ>ule4WRY=Tk trVx$7̿ʭB 2IXۭ 5QW0.Q֖pۏݨݏ&LAS(69m]i&Z RIm!RUuݼVƫn0&QFȮyFꌹvO"2j<ўk) "L֎8(b'VQj@X25+NV:T`Q&[p§+"T˕Bi©f (&Kyy 'y5wz(hF73L*SVQk\jtjSQc&;e9M#?Znꈽ75J%UTzG!ju5B6vrUtT*@UeknE TU&zo6"M4&*o}Vް4h$5H==^-J$SR,3q47ި )|ʴ.4u-A$EV]Ԋ3Oc^Jd7fy,hGJgl5`iVzdZo[sDqS!رV@rvQ5]QGeEk!XC|[rʚ3%8\vĬ k]ϒ '?ZK9X1^rm=c,1;t^ ٞ/R}\x!'9Aֻxʺ+FB;6=&][];M:6 ۖ~ESXƥD|G3_̢BnG< k׾$K@D`HIў߽uz>ck-[\`= -_@t+da^iX9`d*Xv3`&7|Ӵ˭Je M"cv< ?E} pLcu@B3w۞J=qWANҕ-팑W?^=`,{ϥzJzj{ռԨcPS6[>dJX2]nUf\}xRm%V;x%xv61/ x歯/Nm^bj„ݏ+Z}-2[wC曛YTy,~x/~cN,AWei?4duI;3FlkЬ.-eCс=*&RqGTڒ_qj 5OT3Te$kZZf֤G(Uz+5H MK yc`Kn11 Xw4T 5"hԨ+gHPU5Oj8XE*➫OSqLei\EFl9L,W\(ǵI\b(R(R9 Meһ.-9H낎Fݣ? =N*6gKDT%r"bԁ DlFj2;˨j'u5 l U#Y.GЇ%PAԠ{Xfm)2wsF*64|5=ZnS,=VVblXIT%#U&ޖGSpyAu?{19ܹ9Ԛ$P&ٓWZ,R:\*U1U;h5_Y*0Zm#ɩ+"ͥ+^c*Օ88m#RN*NV[(v?-ݔ2۫]|dt9? !VTz^*̲pd5#E^m[>Y?b!OAZk`<΅H ɍWz׵;J5**m̪S'u 枷ռSǴy?݊?UW`U$뼇Gmƫ{v/u4H'`>%b1U((yõõàFC!E { eVrB2~ : ч `Us֭/iȯuk$mp14NH:|pQUnOzw>d(xS#^s$Y}93 k3mwZ0X.A#=uϭzzA2ᢑ_m*ON޵jvvPIp >gϷ0H5_θnL(оOHwƹ\< ժoVOp5x5B<\/5*-H#1^g"-YzS*iL.>5Vi*/bVRlD;id´\ \ejZ@aM09)}]-YD-=@uVU*2Wү,he~͘l5Lylm?Q}2FK_J-5*%t<#2*[M"~ =:r"nx8Av80jvu-{SIy)v¯7U:wBޣk)6,M+뚕B;n敏5ʻ x:=FT}kԅG1tR.gCèQi C8B'oE{ ]e/꜐=WHZ|PwXVTrl_ {5 }ƍ0>fU73Md#ylzOR@'%` }'񯃭k5DW2=ϳ^o%Š|伌3\Ml.Dߴ瑎K>6U'C)S}YW4WPK]pG?u 8๸˃9-JNx8s[º=y+&~|Ek9%9#z?.@iNj3Xx:U=Qf:FFہ[~sv'3J.Y!\Y۹P _= cJUyjGri]yJ!5UL"?jR)1XEGLXƪԊ<¹Md[)h\QUJ׊i@LWSonQ*ֳtH];~&WE%z;y<1b <F)hjv?v2{U`ko]@a~Me(ٝP|4u)-#2!ICZꖎ?l>1\lS i4Dsj2n#jַ[)cq=NvJ.Kr^F,5KU ƖK-/Fc%FSNTL&J)DZ-M-JXh Pnu>Pc֜4V-GT]n>#RUکLy NTjZd$o>zm5]Uⱞ{5BƆjDv'ScS,>բ0cRGiA>S:`TY#;hcrQ6; !?xWo9/O>ҷ@qv칷%<~n_}$c69&*8V99`~_/":WdːA,D?t OTtү}"uV:֋ǟWtu)ZԶ%cWڵ"]СVb- Ε_1SD\ї0Xy[U[x;trՑnҞ)-;U4cRF%s8h6:Ҝj&YI=H撔i`+Q TEYYG~=ڲX.$Cwo4{4r?2Jzj#]N$^ZˢY6CLIW?C/QiZj- ud7vˍ-Wđl~WRF*KQ<`\#gslp\&GUa|IőnL}De%'H]zuq<Yv:"IFWvzWWũAh;ĩ\wAk_> =V>~ͷ;xV8Fz>F5=iOzm g7hF[iݫ(+7>]'BP}`u=7z,݉iTgb^jRXfK ;!Ζ͑EpM-qhyըakiHJfpڞU&CY9TXEJ"8GY9%.ڟe)\9v ՂI̹* 1gCU=?ֻ '`yt )H#N7RqZ4M&3 `Gvu6[޴5-V.{cRGU5hPn =RF&i*6i=7Hv'i*3! IVXd'Қ_Nñ9ziz!j,2b@j,&IޢJ u87aX4S=ZFz(jua\͵䰮nE_T?`ѼRnsIEnF˱'޳lJ n=:)7%+;b|e-M"xϘAW*,߃Wl2zRĿ:Gɽ! 2~ZQM ɩVk"_ 8T{akoSHmMbgԎ>H$dK:\Ww̕jLg})Y) pGz)ů.S_[Ҭ9Xl1WGՀUXGQwJa+YoI9*@ZnnՉǢku鶮SUJsw \MH# ,NN/] 9JҬ @k7C6ߊո;a֩e9MCzjq,-"#\[-}#NCZr8(33bzi(=EE3JIs'SQǽU\qqaljzi[Q7pQZerK 6QVji|1{RrZƸclIs7hP;J{i*'z]Eؕ䨚Jޣ/Z$;)UaJ_ސjL wEz2h n4`.iCTYu*҃41X5HUTEj[*LPЋ2TUz =^#6&Ű櫡&ZʘOUxD\֝I9^Қf3WԸS*SP˹HaV?jfaG?ZY2FOl!Κ9"( RSVc ZR#QW̿!#5J qwfC)''zc-[e{W9T1ʫ[hW9W˩zEKsӏSҶ9!๩z1ڠ떫)o>?U^5#AP6AԽ &SJ*6jl=ߊއ~*z5cfJ^A/5j&pqhC? 1]tXvCJu1#'$@9*GӊRkTc)(}Hf 1#ҕf#& UWҮ,+Nc>H ZaUe=jeR)1LWPR61M^T` Ik#ϩ!+jU=xԈTSG}J*6&fcV.9XkBNcQ5+Oj|AgZE#+ sk5Ȯd!8fQQ'VÏMYU.0BЌY9I\Zs7"}.c2.y<p*OL?ȭUȠr-ŦpwM-%U(3$j:jXQ+(?eƲ# uv|1#qt[;qo2)\Bz 9Iݳ˝5"o&ϓnֳWauj|ʒ2Z%%XN=wQ4u<%HbbJ0̈́gz~UБ*+wuLG~s\ 5zjv'FS׶~wMN[I؏Csҕ/.Fs"vS5X5N\JEHri94V ȳl5`"m"0+z.Sg jcRM&%qҢaJj&Ⱃ)2'PLVw4LJnjg|߅ic_W~a5Ey @Ʀk QkNԎ9:}V?~3G bőx[;?AcutYKGq7Wc~avNբ<ʺuمmŶ e̸OWD OjξI,$eNFq?J̯J4­{ҠqZv}mEP,$j,xӤ9d;Lo }B*jSi泸@qC[qөKY9qY-zӡx:ƲJ2C%֋rl.ՏqỀY+rSMnQ*UED..a`RiXj=XeR+ݑe?6H*r&a21y[mF汮VͬXEm;V V'sKR&|4Q\)jЅ.(ZW\h"UQ]0f+H8Ӆ sEfZs ('DJstQEoDU~(Q"cQEh74P3E(4QL,.iADPh\E p44QRJ P?uJEɐMTlkV۵VlfZVL呥 U؏J($sH~(ك$/LfRFlFZ+hSdlW-M1RW1Dur6 J(iI`d9Q]%2'872!zw4QNm bQҚ(F)(bi\vGLK=&*dVa#v?SϨ}*g1t($^.n-[/&qV{If(RcQEգϮ8 &hXǴ4k#F*U>àZcǾxfmqw`r (ĵd'L] ƥY,i7nE{{ٝ~2ܑ?gY,!Hқo-4QX'Q;&Ӳ5LVc(asyncclick-8.3.0.5-async/examples/imagepipe/imagepipe.py000066400000000000000000000201171507140761400232210ustar00rootroot00000000000000from functools import update_wrapper from PIL import Image from PIL import ImageEnhance from PIL import ImageFilter import asyncclick as click @click.group(chain=True) def cli(): """This script processes a bunch of images through pillow in a unix pipe. One commands feeds into the next. Example: \b imagepipe open -i example01.jpg resize -w 128 display imagepipe open -i example02.jpg blur save """ @cli.result_callback() def process_commands(processors): """This result callback is invoked with an iterable of all the chained subcommands. As in this example each subcommand returns a function we can chain them together to feed one into the other, similar to how a pipe on unix works. """ # Start with an empty iterable. stream = () # Pipe it through all stream processors. for processor in processors: stream = processor(stream) # Evaluate the stream and throw away the items. for _ in stream: pass def processor(f): """Helper decorator to rewrite a function so that it returns another function from it. """ def new_func(*args, **kwargs): def processor(stream): return f(stream, *args, **kwargs) return processor return update_wrapper(new_func, f) def generator(f): """Similar to the :func:`processor` but passes through old values unchanged and does not pass through the values as parameter. """ @processor def new_func(stream, *args, **kwargs): yield from stream yield from f(*args, **kwargs) return update_wrapper(new_func, f) def copy_filename(new, old): new.filename = old.filename return new @cli.command("open") @click.option( "-i", "--image", "images", type=click.Path(), multiple=True, help="The image file to open.", ) @generator def open_cmd(images): """Loads one or multiple images for processing. The input parameter can be specified multiple times to load more than one image. """ for image in images: try: click.echo(f"Opening '{image}'") if image == "-": img = Image.open(click.get_binary_stdin()) img.filename = "-" else: img = Image.open(image) yield img except Exception as e: click.echo(f"Could not open image '{image}': {e}", err=True) @cli.command("save") @click.option( "--filename", default="processed-{:04}.png", type=click.Path(), help="The format for the filename.", show_default=True, ) @processor def save_cmd(images, filename): """Saves all processed images to a series of files.""" for idx, image in enumerate(images): try: fn = filename.format(idx + 1) click.echo(f"Saving '{image.filename}' as '{fn}'") yield image.save(fn) except Exception as e: click.echo(f"Could not save image '{image.filename}': {e}", err=True) @cli.command("display") @processor def display_cmd(images): """Opens all images in an image viewer.""" for image in images: click.echo(f"Displaying '{image.filename}'") image.show() yield image @cli.command("resize") @click.option("-w", "--width", type=int, help="The new width of the image.") @click.option("-h", "--height", type=int, help="The new height of the image.") @processor def resize_cmd(images, width, height): """Resizes an image by fitting it into the box without changing the aspect ratio. """ for image in images: w, h = (width or image.size[0], height or image.size[1]) click.echo(f"Resizing '{image.filename}' to {w}x{h}") image.thumbnail((w, h)) yield image @cli.command("crop") @click.option( "-b", "--border", type=int, help="Crop the image from all sides by this amount." ) @processor def crop_cmd(images, border): """Crops an image from all edges.""" for image in images: box = [0, 0, image.size[0], image.size[1]] if border is not None: for idx, val in enumerate(box): box[idx] = max(0, val - border) click.echo(f"Cropping '{image.filename}' by {border}px") yield copy_filename(image.crop(box), image) else: yield image def convert_rotation(ctx, param, value): if value is None: return value = value.lower() if value in ("90", "r", "right"): return (Image.ROTATE_90, 90) if value in ("180", "-180"): return (Image.ROTATE_180, 180) if value in ("-90", "270", "l", "left"): return (Image.ROTATE_270, 270) raise click.BadParameter(f"invalid rotation '{value}'") def convert_flip(ctx, param, value): if value is None: return value = value.lower() if value in ("lr", "leftright"): return (Image.FLIP_LEFT_RIGHT, "left to right") if value in ("tb", "topbottom", "upsidedown", "ud"): return (Image.FLIP_LEFT_RIGHT, "top to bottom") raise click.BadParameter(f"invalid flip '{value}'") @cli.command("transpose") @click.option( "-r", "--rotate", callback=convert_rotation, help="Rotates the image (in degrees)" ) @click.option("-f", "--flip", callback=convert_flip, help="Flips the image [LR / TB]") @processor def transpose_cmd(images, rotate, flip): """Transposes an image by either rotating or flipping it.""" for image in images: if rotate is not None: mode, degrees = rotate click.echo(f"Rotate '{image.filename}' by {degrees}deg") image = copy_filename(image.transpose(mode), image) if flip is not None: mode, direction = flip click.echo(f"Flip '{image.filename}' {direction}") image = copy_filename(image.transpose(mode), image) yield image @cli.command("blur") @click.option("-r", "--radius", default=2, show_default=True, help="The blur radius.") @processor def blur_cmd(images, radius): """Applies gaussian blur.""" blur = ImageFilter.GaussianBlur(radius) for image in images: click.echo(f"Blurring '{image.filename}' by {radius}px") yield copy_filename(image.filter(blur), image) @cli.command("smoothen") @click.option( "-i", "--iterations", default=1, show_default=True, help="How many iterations of the smoothen filter to run.", ) @processor def smoothen_cmd(images, iterations): """Applies a smoothening filter.""" for image in images: click.echo( f"Smoothening {image.filename!r} {iterations}" f" time{'s' if iterations != 1 else ''}" ) for _ in range(iterations): image = copy_filename(image.filter(ImageFilter.BLUR), image) yield image @cli.command("emboss") @processor def emboss_cmd(images): """Embosses an image.""" for image in images: click.echo(f"Embossing '{image.filename}'") yield copy_filename(image.filter(ImageFilter.EMBOSS), image) @cli.command("sharpen") @click.option( "-f", "--factor", default=2.0, help="Sharpens the image.", show_default=True ) @processor def sharpen_cmd(images, factor): """Sharpens an image.""" for image in images: click.echo(f"Sharpen '{image.filename}' by {factor}") enhancer = ImageEnhance.Sharpness(image) yield copy_filename(enhancer.enhance(max(1.0, factor)), image) @cli.command("paste") @click.option("-l", "--left", default=0, help="Offset from left.") @click.option("-r", "--right", default=0, help="Offset from right.") @processor def paste_cmd(images, left, right): """Pastes the second image on the first image and leaves the rest unchanged. """ imageiter = iter(images) image = next(imageiter, None) to_paste = next(imageiter, None) if to_paste is None: if image is not None: yield image return click.echo(f"Paste '{to_paste.filename}' on '{image.filename}'") mask = None if to_paste.mode == "RGBA" or "transparency" in to_paste.info: mask = to_paste image.paste(to_paste, (left, right), mask) image.filename += f"+{to_paste.filename}" yield image yield from imageiter asyncclick-8.3.0.5-async/examples/imagepipe/pyproject.toml000066400000000000000000000005311507140761400236210ustar00rootroot00000000000000[project] name = "click-example-imagepipe" version = "1.0.0" description = "Click imagepipe example" requires-python = ">=3.10" dependencies = [ "click>=8.1", "pillow", ] [project.scripts] imagepipe = "imagepipe:cli" [build-system] requires = ["flit_core<4"] build-backend = "flit_core.buildapi" [tool.flit.module] name = "imagepipe" asyncclick-8.3.0.5-async/examples/inout/000077500000000000000000000000001507140761400201045ustar00rootroot00000000000000asyncclick-8.3.0.5-async/examples/inout/README000066400000000000000000000003541507140761400207660ustar00rootroot00000000000000$ inout_ inout is a simple example of an application that can read from files and write to files but also accept input from stdin or write to stdout. Usage: $ pip install --editable . $ inout input_file.txt output_file.txt asyncclick-8.3.0.5-async/examples/inout/inout.py000066400000000000000000000013401507140761400216120ustar00rootroot00000000000000import asyncclick as click @click.command() @click.argument("input", type=click.File("rb"), nargs=-1) @click.argument("output", type=click.File("wb")) def cli(input, output): """This script works similar to the Unix `cat` command but it writes into a specific file (which could be the standard output as denoted by the ``-`` sign). \b Copy stdin to stdout: inout - - \b Copy foo.txt and bar.txt to stdout: inout foo.txt bar.txt - \b Write stdin into the file foo.txt inout - foo.txt """ for f in input: while True: chunk = f.read(1024) if not chunk: break output.write(chunk) output.flush() asyncclick-8.3.0.5-async/examples/inout/pyproject.toml000066400000000000000000000004671507140761400230270ustar00rootroot00000000000000[project] name = "click-example-inout" version = "1.0.0" description = "Click inout example" requires-python = ">=3.10" dependencies = [ "click>=8.1", ] [project.scripts] inout = "inout:cli" [build-system] requires = ["flit_core<4"] build-backend = "flit_core.buildapi" [tool.flit.module] name = "inout" asyncclick-8.3.0.5-async/examples/naval/000077500000000000000000000000001507140761400200475ustar00rootroot00000000000000asyncclick-8.3.0.5-async/examples/naval/README000066400000000000000000000005421507140761400207300ustar00rootroot00000000000000$ naval_ naval is a simple example of an application that is ported from the docopt example of the same name. Unlike the original this one also runs some code and prints messages and it's command line interface was changed slightly to make more sense with established POSIX semantics. Usage: $ pip install --editable . $ naval --help asyncclick-8.3.0.5-async/examples/naval/naval.py000066400000000000000000000032571507140761400215310ustar00rootroot00000000000000import asyncclick as click @click.group() @click.version_option() def cli(): """Naval Fate. This is the docopt example adopted to Click but with some actual commands implemented and not just the empty parsing which really is not all that interesting. """ @cli.group() def ship(): """Manages ships.""" @ship.command("new") @click.argument("name") def ship_new(name): """Creates a new ship.""" click.echo(f"Created ship {name}") @ship.command("move") @click.argument("ship") @click.argument("x", type=float) @click.argument("y", type=float) @click.option("--speed", metavar="KN", default=10, help="Speed in knots.") def ship_move(ship, x, y, speed): """Moves SHIP to the new location X,Y.""" click.echo(f"Moving ship {ship} to {x},{y} with speed {speed}") @ship.command("shoot") @click.argument("ship") @click.argument("x", type=float) @click.argument("y", type=float) def ship_shoot(ship, x, y): """Makes SHIP fire to X,Y.""" click.echo(f"Ship {ship} fires to {x},{y}") @cli.group("mine") def mine(): """Manages mines.""" @mine.command("set") @click.argument("x", type=float) @click.argument("y", type=float) @click.option( "ty", "--moored", flag_value="moored", default=True, help="Moored (anchored) mine. Default.", ) @click.option("ty", "--drifting", flag_value="drifting", help="Drifting mine.") def mine_set(x, y, ty): """Sets a mine at a specific coordinate.""" click.echo(f"Set {ty} mine at {x},{y}") @mine.command("remove") @click.argument("x", type=float) @click.argument("y", type=float) def mine_remove(x, y): """Removes a mine at a specific coordinate.""" click.echo(f"Removed mine at {x},{y}") asyncclick-8.3.0.5-async/examples/naval/pyproject.toml000066400000000000000000000004671507140761400227720ustar00rootroot00000000000000[project] name = "click-example-naval" version = "1.0.0" description = "Click naval example" requires-python = ">=3.10" dependencies = [ "click>=8.1", ] [project.scripts] naval = "naval:cli" [build-system] requires = ["flit_core<4"] build-backend = "flit_core.buildapi" [tool.flit.module] name = "naval" asyncclick-8.3.0.5-async/examples/repo/000077500000000000000000000000001507140761400177135ustar00rootroot00000000000000asyncclick-8.3.0.5-async/examples/repo/README000066400000000000000000000002311507140761400205670ustar00rootroot00000000000000$ repo_ repo is a simple example of an application that looks and works similar to hg or git. Usage: $ pip install --editable . $ repo --help asyncclick-8.3.0.5-async/examples/repo/pyproject.toml000066400000000000000000000004621507140761400226310ustar00rootroot00000000000000[project] name = "click-example-repo" version = "1.0.0" description = "Click repo example" requires-python = ">=3.10" dependencies = [ "click>=8.1", ] [project.scripts] repo = "repo:cli" [build-system] requires = ["flit_core<4"] build-backend = "flit_core.buildapi" [tool.flit.module] name = "repo" asyncclick-8.3.0.5-async/examples/repo/repo.py000066400000000000000000000111731507140761400212350ustar00rootroot00000000000000import os import posixpath import sys import asyncclick as click class Repo: def __init__(self, home): self.home = home self.config = {} self.verbose = False def set_config(self, key, value): self.config[key] = value if self.verbose: click.echo(f" config[{key}] = {value}", file=sys.stderr) def __repr__(self): return f"" pass_repo = click.make_pass_decorator(Repo) @click.group() @click.option( "--repo-home", envvar="REPO_HOME", default=".repo", metavar="PATH", help="Changes the repository folder location.", ) @click.option( "--config", nargs=2, multiple=True, metavar="KEY VALUE", help="Overrides a config key/value pair.", ) @click.option("--verbose", "-v", is_flag=True, help="Enables verbose mode.") @click.version_option("1.0") @click.pass_context def cli(ctx, repo_home, config, verbose): """Repo is a command line tool that showcases how to build complex command line interfaces with Click. This tool is supposed to look like a distributed version control system to show how something like this can be structured. """ # Create a repo object and remember it as as the context object. From # this point onwards other commands can refer to it by using the # @pass_repo decorator. ctx.obj = Repo(os.path.abspath(repo_home)) ctx.obj.verbose = verbose for key, value in config: ctx.obj.set_config(key, value) @cli.command() @click.argument("src") @click.argument("dest", required=False) @click.option( "--shallow/--deep", default=False, help="Makes a checkout shallow or deep. Deep by default.", ) @click.option( "--rev", "-r", default="HEAD", help="Clone a specific revision instead of HEAD." ) @pass_repo def clone(repo, src, dest, shallow, rev): """Clones a repository. This will clone the repository at SRC into the folder DEST. If DEST is not provided this will automatically use the last path component of SRC and create that folder. """ if dest is None: dest = posixpath.split(src)[-1] or "." click.echo(f"Cloning repo {src} to {os.path.basename(dest)}") repo.home = dest if shallow: click.echo("Making shallow checkout") click.echo(f"Checking out revision {rev}") @cli.command() @click.confirmation_option() @pass_repo def delete(repo): """Deletes a repository. This will throw away the current repository. """ click.echo(f"Destroying repo {repo.home}") click.echo("Deleted!") @cli.command() @click.option("--username", prompt=True, help="The developer's shown username.") @click.option("--email", prompt="E-Mail", help="The developer's email address") @click.password_option(help="The login password.") @pass_repo def setuser(repo, username, email, password): """Sets the user credentials. This will override the current user config. """ repo.set_config("username", username) repo.set_config("email", email) repo.set_config("password", "*" * len(password)) click.echo("Changed credentials.") @cli.command() @click.option( "--message", "-m", multiple=True, help="The commit message. If provided multiple times each" " argument gets converted into a new line.", ) @click.argument("files", nargs=-1, type=click.Path()) @pass_repo def commit(repo, files, message): """Commits outstanding changes. Commit changes to the given files into the repository. You will need to "repo push" to push up your changes to other repositories. If a list of files is omitted, all changes reported by "repo status" will be committed. """ if not message: marker = "# Files to be committed:" hint = ["", "", marker, "#"] for file in files: hint.append(f"# U {file}") message = click.edit("\n".join(hint)) if message is None: click.echo("Aborted!") return msg = message.split(marker)[0].rstrip() if not msg: click.echo("Aborted! Empty commit message") return else: msg = "\n".join(message) click.echo(f"Files to be committed: {files}") click.echo(f"Commit message:\n{msg}") @cli.command(short_help="Copies files.") @click.option( "--force", is_flag=True, help="forcibly copy over an existing managed file" ) @click.argument("src", nargs=-1, type=click.Path()) @click.argument("dst", type=click.Path()) @pass_repo def copy(repo, src, dst, force): """Copies one or multiple files to a new location. This copies all files from SRC to DST. """ for fn in src: click.echo(f"Copy from {fn} -> {dst}") asyncclick-8.3.0.5-async/examples/termui/000077500000000000000000000000001507140761400202535ustar00rootroot00000000000000asyncclick-8.3.0.5-async/examples/termui/README000066400000000000000000000002171507140761400211330ustar00rootroot00000000000000$ termui_ termui showcases the different terminal UI helpers that Click provides. Usage: $ pip install --editable . $ termui --help asyncclick-8.3.0.5-async/examples/termui/pyproject.toml000066400000000000000000000004741507140761400231740ustar00rootroot00000000000000[project] name = "click-example-termui" version = "1.0.0" description = "Click termui example" requires-python = ">=3.10" dependencies = [ "click>=8.1", ] [project.scripts] termui = "termui:cli" [build-system] requires = ["flit_core<4"] build-backend = "flit_core.buildapi" [tool.flit.module] name = "termui" asyncclick-8.3.0.5-async/examples/termui/termui.py000066400000000000000000000101041507140761400221260ustar00rootroot00000000000000import math import random import time import asyncclick as click @click.group() def cli(): """This script showcases different terminal UI helpers in Click.""" pass @cli.command() def colordemo(): """Demonstrates ANSI color support.""" for color in "red", "green", "blue": click.echo(click.style(f"I am colored {color}", fg=color)) click.echo(click.style(f"I am background colored {color}", bg=color)) @cli.command() def pager(): """Demonstrates using the pager.""" lines = [] for x in range(200): lines.append(f"{click.style(str(x), fg='green')}. Hello World!") click.echo_via_pager("\n".join(lines)) @cli.command() @click.option( "--count", default=8000, type=click.IntRange(1, 100000), help="The number of items to process.", ) def progress(count): """Demonstrates the progress bar.""" items = range(count) def process_slowly(item): time.sleep(0.002 * random.random()) def filter(items): for item in items: if random.random() > 0.3: yield item with click.progressbar( items, label="Processing accounts", fill_char=click.style("#", fg="green") ) as bar: for item in bar: process_slowly(item) def show_item(item): if item is not None: return f"Item #{item}" with click.progressbar( filter(items), label="Committing transaction", fill_char=click.style("#", fg="yellow"), item_show_func=show_item, ) as bar: for item in bar: process_slowly(item) with click.progressbar( length=count, label="Counting", bar_template="%(label)s %(bar)s | %(info)s", fill_char=click.style("█", fg="cyan"), empty_char=" ", ) as bar: for item in bar: process_slowly(item) with click.progressbar( length=count, width=0, show_percent=False, show_eta=False, fill_char=click.style("#", fg="magenta"), ) as bar: for item in bar: process_slowly(item) # 'Non-linear progress bar' steps = [math.exp(x * 1.0 / 20) - 1 for x in range(20)] count = int(sum(steps)) with click.progressbar( length=count, show_percent=False, label="Slowing progress bar", fill_char=click.style("█", fg="green"), ) as bar: for item in steps: time.sleep(item) bar.update(item) @cli.command() @click.argument("url") def open(url): """Opens a file or URL In the default application.""" click.launch(url) @cli.command() @click.argument("url") def locate(url): """Opens a file or URL In the default application.""" click.launch(url, locate=True) @cli.command() def edit(): """Opens an editor with some text in it.""" MARKER = "# Everything below is ignored\n" message = click.edit(f"\n\n{MARKER}") if message is not None: msg = message.split(MARKER, 1)[0].rstrip("\n") if not msg: click.echo("Empty message!") else: click.echo(f"Message:\n{msg}") else: click.echo("You did not enter anything!") @cli.command() def clear(): """Clears the entire screen.""" click.clear() @cli.command() def pause(): """Waits for the user to press a button.""" click.pause() @cli.command() def menu(): """Shows a simple menu.""" menu = "main" while True: if menu == "main": click.echo("Main menu:") click.echo(" d: debug menu") click.echo(" q: quit") char = click.getchar() if char == "d": menu = "debug" elif char == "q": menu = "quit" else: click.echo("Invalid input") elif menu == "debug": click.echo("Debug menu") click.echo(" b: back") char = click.getchar() if char == "b": menu = "main" else: click.echo("Invalid input") elif menu == "quit": return asyncclick-8.3.0.5-async/examples/validation/000077500000000000000000000000001507140761400211005ustar00rootroot00000000000000asyncclick-8.3.0.5-async/examples/validation/README000066400000000000000000000003611507140761400217600ustar00rootroot00000000000000$ validation_ validation is a simple example of an application that performs custom validation of parameters in different ways. This example requires Click 2.0 or higher. Usage: $ pip install --editable . $ validation --help asyncclick-8.3.0.5-async/examples/validation/pyproject.toml000066400000000000000000000005201507140761400240110ustar00rootroot00000000000000[project] name = "click-example-validation" version = "1.0.0" description = "Click validation example" requires-python = ">=3.10" dependencies = [ "click>=8.1", ] [project.scripts] validation = "validation:cli" [build-system] requires = ["flit_core<4"] build-backend = "flit_core.buildapi" [tool.flit.module] name = "validation" asyncclick-8.3.0.5-async/examples/validation/validation.py000066400000000000000000000026151507140761400236100ustar00rootroot00000000000000from urllib import parse as urlparse import asyncclick as click def validate_count(ctx, param, value): if value < 0 or value % 2 != 0: raise click.BadParameter("Should be a positive, even integer.") return value class URL(click.ParamType): name = "url" def convert(self, value, param, ctx): if not isinstance(value, tuple): value = urlparse.urlparse(value) if value.scheme not in ("http", "https"): self.fail( f"invalid URL scheme ({value.scheme}). Only HTTP URLs are allowed", param, ctx, ) return value @click.command() @click.option( "--count", default=2, callback=validate_count, help="A positive even number." ) @click.option("--foo", help="A mysterious parameter.") @click.option("--url", help="A URL", type=URL()) @click.version_option() def cli(count, foo, url): """Validation. This example validates parameters in different ways. It does it through callbacks, through a custom type as well as by validating manually in the function. """ if foo is not None and foo != "wat": raise click.BadParameter( 'If a value is provided it needs to be the value "wat".', param_hint=["--foo"], ) click.echo(f"count: {count}") click.echo(f"foo: {foo}") click.echo(f"url: {url!r}") asyncclick-8.3.0.5-async/pyproject.toml000066400000000000000000000104641507140761400200510ustar00rootroot00000000000000[project] name = "asyncclick" description = "Composable command line interface toolkit, async fork" readme = "README.md" license = "BSD-3-Clause" license-files = ["LICENSE.txt"] maintainers = [{name = "Matthias Urlichs", email = "matthias@urlichs.de"}] classifiers = [ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Operating System :: OS Independent", "Programming Language :: Python", "Typing :: Typed", ] requires-python = ">=3.11" dependencies = [ "colorama; platform_system == 'Windows'", ] version = "8.3.0.5" [project.urls] Source = "https://github.com/python-trio/asyncclick/" [dependency-groups] dev = [ "anyio", "trio", "ruff", "tox", "tox-uv", ] docs = [ "myst-parser", "pallets-sphinx-themes", "sphinx", "sphinx-tabs", "sphinxcontrib-log-cabinet", ] docs-auto = [ "sphinx-autobuild", ] gha-update = [ "gha-update ; python_full_version >= '3.12'", ] pre-commit = [ "pre-commit", "pre-commit-uv", ] tests = [ "pytest", "anyio", "trio", ] typing = [ "anyio", "mypy", "pyright", "pytest", ] anyio = [ "anyio ~= 4.0", ] trio = [ "trio ~= 0.22", ] [build-system] requires = ["flit_core<4"] build-backend = "flit_core.buildapi" [tool.flit.module] name = "asyncclick" [tool.flit.sdist] include = [ "docs/", "tests/", "CHANGES.rst", "uv.lock" ] exclude = [ "docs/_build/", ] [tool.uv] default-groups = ["dev", "pre-commit", "tests", "typing"] [tool.pytest.ini_options] testpaths = ["tests"] filterwarnings = [ "error", ] [tool.coverage.run] branch = true source = ["asyncclick", "tests"] [tool.coverage.paths] source = ["src", "*/site-packages"] [tool.coverage.report] exclude_also = [ "if t.TYPE_CHECKING", "raise NotImplementedError", ": \\.{3}", ] [tool.mypy] python_version = "3.11" files = ["src", "tests/typing"] show_error_codes = true pretty = true strict = true [[tool.mypy.overrides]] module = [ "colorama.*", ] ignore_missing_imports = true [tool.pyright] pythonVersion = "3.11" include = ["src", "tests/typing"] typeCheckingMode = "basic" [tool.ruff] extend-exclude = ["examples/"] src = ["src"] fix = true show-fixes = true output-format = "full" [tool.ruff.lint] select = [ "B", # flake8-bugbear "E", # pycodestyle error "F", # pyflakes "I", # isort "UP", # pyupgrade "W", # pycodestyle warning ] ignore = [ "UP038", # keep isinstance tuple ] [tool.ruff.lint.isort] force-single-line = true order-by-type = false [tool.tox] env_list = [ "py3.13", "py3.12", "py3.11", "pypy3.11", "style", "typing", "docs", ] [tool.tox.env_run_base] description = "pytest on latest dependency versions" runner = "uv-venv-lock-runner" package = "wheel" wheel_build_env = ".pkg" constrain_package_deps = true use_frozen_constraints = true dependency_groups = ["tests"] commands = [[ "pytest", "-v", "--tb=short", "--basetemp={env_tmp_dir}", {replace = "posargs", default = [], extend = true}, ]] [tool.tox.env.style] description = "run all pre-commit hooks on all files" dependency_groups = ["pre-commit"] skip_install = true commands = [["pre-commit", "run", "--all-files"]] [tool.tox.env.typing] description = "run static type checkers" dependency_groups = ["typing"] commands = [ ["mypy"], ] [tool.tox.env.docs] description = "build docs" dependency_groups = ["docs"] commands = [["sphinx-build", "-E", "-W", "-b", "dirhtml", "docs", "docs/_build/dirhtml"]] [tool.tox.env.docs-auto] description = "continuously rebuild docs and start a local server" dependency_groups = ["docs", "docs-auto"] commands = [["sphinx-autobuild", "-W", "-b", "dirhtml", "--watch", "src", "docs", "docs/_build/dirhtml"]] [tool.tox.env.update-actions] description = "update GitHub Actions pins" labels = ["update"] dependency_groups = ["gha-update"] skip_install = true commands = [["gha-update"]] [tool.tox.env.update-pre_commit] description = "update pre-commit pins" labels = ["update"] dependency_groups = ["pre-commit"] skip_install = true commands = [["pre-commit", "autoupdate", "--freeze", "-j4"]] [tool.tox.env.update-requirements] description = "update uv lock" labels = ["update"] dependency_groups = [] no_default_groups = true skip_install = true commands = [["uv", "lock", {replace = "posargs", default = ["-U"], extend = true}]] asyncclick-8.3.0.5-async/requirements/000077500000000000000000000000001507140761400176535ustar00rootroot00000000000000asyncclick-8.3.0.5-async/requirements/build.txt000066400000000000000000000006111507140761400215110ustar00rootroot00000000000000# # This file is autogenerated by pip-compile with Python 3.12 # by the following command: # # pip-compile requirements/build.in # --trusted-host pypi.python.org --trusted-host pypi.org --trusted-host files.pythonhosted.org --trusted-host pypi01vp.office.noris.de build==1.2.2.post1 # via -r requirements/build.in packaging==24.2 # via build pyproject-hooks==1.2.0 # via build asyncclick-8.3.0.5-async/requirements/dev.in000066400000000000000000000001201507140761400207520ustar00rootroot00000000000000-r docs.in -r tests.in -r typing.in pip-compile-multi pre-commit tox anyio trio asyncclick-8.3.0.5-async/requirements/dev.txt000066400000000000000000000067741507140761400212100ustar00rootroot00000000000000# # This file is autogenerated by pip-compile with Python 3.12 # by the following command: # # pip-compile requirements/dev.in # --trusted-host pypi.python.org --trusted-host pypi.org --trusted-host files.pythonhosted.org --trusted-host pypi01vp.office.noris.de alabaster==1.0.0 # via sphinx anyio==4.8.0 # via -r requirements/dev.in attrs==24.3.0 # via # outcome # trio babel==2.16.0 # via sphinx build==1.2.2.post1 # via pip-tools cachetools==5.5.0 # via tox certifi==2024.8.30 # via requests cfgv==3.4.0 # via pre-commit chardet==5.2.0 # via tox charset-normalizer==3.4.0 # via requests click==8.1.7 # via # pip-compile-multi # pip-tools colorama==0.4.6 # via tox distlib==0.3.9 # via virtualenv docutils==0.21.2 # via # sphinx # sphinx-tabs filelock==3.16.1 # via # tox # virtualenv identify==2.6.3 # via pre-commit idna==3.10 # via # anyio # requests # trio imagesize==1.4.1 # via sphinx iniconfig==2.0.0 # via pytest jinja2==3.1.4 # via sphinx markupsafe==3.0.2 # via jinja2 mypy==1.13.0 # via -r /src/asyncclick/requirements/typing.in mypy-extensions==1.0.0 # via mypy nodeenv==1.9.1 # via # pre-commit # pyright outcome==1.3.0.post0 # via trio packaging==24.2 # via # build # pallets-sphinx-themes # pyproject-api # pytest # sphinx # tox pallets-sphinx-themes==2.3.0 # via -r /src/asyncclick/requirements/docs.in pip-compile-multi==2.7.1 # via -r requirements/dev.in pip-tools==7.4.1 # via pip-compile-multi platformdirs==4.3.6 # via # tox # virtualenv pluggy==1.5.0 # via # pytest # tox pre-commit==4.0.1 # via -r requirements/dev.in pygments==2.18.0 # via # sphinx # sphinx-tabs pyproject-api==1.8.0 # via tox pyproject-hooks==1.2.0 # via # build # pip-tools pyright==1.1.390 # via -r /src/asyncclick/requirements/typing.in pytest==8.3.4 # via -r /src/asyncclick/requirements/tests.in pyyaml==6.0.2 # via pre-commit requests==2.32.3 # via sphinx sniffio==1.3.1 # via # anyio # trio snowballstemmer==2.2.0 # via sphinx sortedcontainers==2.4.0 # via trio sphinx==8.1.3 # via # -r /src/asyncclick/requirements/docs.in # pallets-sphinx-themes # sphinx-issues # sphinx-notfound-page # sphinx-tabs # sphinxcontrib-log-cabinet sphinx-issues==5.0.0 # via -r /src/asyncclick/requirements/docs.in sphinx-notfound-page==1.0.4 # via pallets-sphinx-themes sphinx-tabs==3.4.7 # via -r /src/asyncclick/requirements/docs.in sphinxcontrib-applehelp==2.0.0 # via sphinx sphinxcontrib-devhelp==2.0.0 # via sphinx sphinxcontrib-htmlhelp==2.1.0 # via sphinx sphinxcontrib-jsmath==1.0.1 # via sphinx sphinxcontrib-log-cabinet==1.0.1 # via -r /src/asyncclick/requirements/docs.in sphinxcontrib-qthelp==2.0.0 # via sphinx sphinxcontrib-serializinghtml==2.0.0 # via sphinx toposort==1.10 # via pip-compile-multi tox==4.23.2 # via -r requirements/dev.in trio==0.28.0 # via # -r /src/asyncclick/requirements/tests.in # -r requirements/dev.in typing-extensions==4.12.2 # via # anyio # mypy # pyright urllib3==2.2.3 # via requests virtualenv==20.28.0 # via # pre-commit # tox wheel==0.45.1 # via pip-tools # The following packages are considered to be unsafe in a requirements file: # pip # setuptools asyncclick-8.3.0.5-async/requirements/docs.txt000066400000000000000000000031261507140761400213460ustar00rootroot00000000000000# # This file is autogenerated by pip-compile with Python 3.12 # by the following command: # # pip-compile requirements/docs.in # --trusted-host pypi.python.org --trusted-host pypi.org --trusted-host files.pythonhosted.org --trusted-host pypi01vp.office.noris.de alabaster==1.0.0 # via sphinx babel==2.16.0 # via sphinx certifi==2024.8.30 # via requests charset-normalizer==3.4.0 # via requests docutils==0.21.2 # via # sphinx # sphinx-tabs idna==3.10 # via requests imagesize==1.4.1 # via sphinx jinja2==3.1.4 # via sphinx markupsafe==3.0.2 # via jinja2 packaging==24.2 # via # pallets-sphinx-themes # sphinx pallets-sphinx-themes==2.3.0 # via -r requirements/docs.in pygments==2.18.0 # via # sphinx # sphinx-tabs requests==2.32.3 # via sphinx snowballstemmer==2.2.0 # via sphinx sphinx==8.1.3 # via # -r requirements/docs.in # pallets-sphinx-themes # sphinx-issues # sphinx-notfound-page # sphinx-tabs # sphinxcontrib-log-cabinet sphinx-issues==5.0.0 # via -r requirements/docs.in sphinx-notfound-page==1.0.4 # via pallets-sphinx-themes sphinx-tabs==3.4.7 # via -r requirements/docs.in sphinxcontrib-applehelp==2.0.0 # via sphinx sphinxcontrib-devhelp==2.0.0 # via sphinx sphinxcontrib-htmlhelp==2.1.0 # via sphinx sphinxcontrib-jsmath==1.0.1 # via sphinx sphinxcontrib-log-cabinet==1.0.1 # via -r requirements/docs.in sphinxcontrib-qthelp==2.0.0 # via sphinx sphinxcontrib-serializinghtml==2.0.0 # via sphinx urllib3==2.2.3 # via requests asyncclick-8.3.0.5-async/requirements/tests.in000066400000000000000000000000141507140761400213400ustar00rootroot00000000000000pytest trio asyncclick-8.3.0.5-async/requirements/tests.txt000066400000000000000000000012071507140761400215560ustar00rootroot00000000000000# # This file is autogenerated by pip-compile with Python 3.12 # by the following command: # # pip-compile requirements/tests.in # --trusted-host pypi.python.org --trusted-host pypi.org --trusted-host files.pythonhosted.org --trusted-host pypi01vp.office.noris.de attrs==24.3.0 # via # outcome # trio idna==3.10 # via trio iniconfig==2.0.0 # via pytest outcome==1.3.0.post0 # via trio packaging==24.2 # via pytest pluggy==1.5.0 # via pytest pytest==8.3.4 # via -r requirements/tests.in sniffio==1.3.1 # via trio sortedcontainers==2.4.0 # via trio trio==0.28.0 # via -r requirements/tests.in asyncclick-8.3.0.5-async/requirements/typing.txt000066400000000000000000000007731507140761400217350ustar00rootroot00000000000000# # This file is autogenerated by pip-compile with Python 3.12 # by the following command: # # pip-compile requirements/typing.in # --trusted-host pypi.python.org --trusted-host pypi.org --trusted-host files.pythonhosted.org --trusted-host pypi01vp.office.noris.de mypy==1.13.0 # via -r requirements/typing.in mypy-extensions==1.0.0 # via mypy nodeenv==1.9.1 # via pyright pyright==1.1.390 # via -r requirements/typing.in typing-extensions==4.12.2 # via # mypy # pyright asyncclick-8.3.0.5-async/src/000077500000000000000000000000001507140761400157175ustar00rootroot00000000000000asyncclick-8.3.0.5-async/src/asyncclick/000077500000000000000000000000001507140761400200425ustar00rootroot00000000000000asyncclick-8.3.0.5-async/src/asyncclick/__init__.py000066400000000000000000000105711507140761400221570ustar00rootroot00000000000000""" Click is a simple Python module inspired by the stdlib optparse to make writing command line scripts fun. Unlike other modules, it's based around a simple API that does not come with too much magic and is composable. """ from __future__ import annotations from .core import Argument as Argument from .core import Command as Command from .core import CommandCollection as CommandCollection from .core import Context as Context from .core import Group as Group from .core import Option as Option from .core import Parameter as Parameter from .decorators import argument as argument from .decorators import command as command from .decorators import confirmation_option as confirmation_option from .decorators import group as group from .decorators import help_option as help_option from .decorators import make_pass_decorator as make_pass_decorator from .decorators import option as option from .decorators import pass_context as pass_context from .decorators import pass_obj as pass_obj from .decorators import password_option as password_option from .decorators import version_option as version_option from .exceptions import Abort as Abort from .exceptions import BadArgumentUsage as BadArgumentUsage from .exceptions import BadOptionUsage as BadOptionUsage from .exceptions import BadParameter as BadParameter from .exceptions import ClickException as ClickException from .exceptions import FileError as FileError from .exceptions import MissingParameter as MissingParameter from .exceptions import NoSuchOption as NoSuchOption from .exceptions import UsageError as UsageError from .formatting import HelpFormatter as HelpFormatter from .formatting import wrap_text as wrap_text from .globals import get_current_context as get_current_context from .termui import clear as clear from .termui import confirm as confirm from .termui import echo_via_pager as echo_via_pager from .termui import edit as edit from .termui import getchar as getchar from .termui import launch as launch from .termui import pause as pause from .termui import progressbar as progressbar from .termui import prompt as prompt from .termui import secho as secho from .termui import style as style from .termui import unstyle as unstyle from .types import BOOL as BOOL from .types import Choice as Choice from .types import DateTime as DateTime from .types import File as File from .types import FLOAT as FLOAT from .types import FloatRange as FloatRange from .types import INT as INT from .types import IntRange as IntRange from .types import ParamType as ParamType from .types import Path as Path from .types import STRING as STRING from .types import Tuple as Tuple from .types import UNPROCESSED as UNPROCESSED from .types import UUID as UUID from .utils import echo as echo from .utils import format_filename as format_filename from .utils import get_app_dir as get_app_dir from .utils import get_binary_stream as get_binary_stream from .utils import get_text_stream as get_text_stream from .utils import open_file as open_file def __getattr__(name: str) -> object: import warnings if name == "BaseCommand": from .core import _BaseCommand warnings.warn( "'BaseCommand' is deprecated and will be removed in Click 9.0. Use" " 'Command' instead.", DeprecationWarning, stacklevel=2, ) return _BaseCommand if name == "MultiCommand": from .core import _MultiCommand warnings.warn( "'MultiCommand' is deprecated and will be removed in Click 9.0. Use" " 'Group' instead.", DeprecationWarning, stacklevel=2, ) return _MultiCommand if name == "OptionParser": from .parser import _OptionParser warnings.warn( "'OptionParser' is deprecated and will be removed in Click 9.0. The" " old parser is available in 'optparse'.", DeprecationWarning, stacklevel=2, ) return _OptionParser if name == "__version__": import importlib.metadata import warnings warnings.warn( "The '__version__' attribute is deprecated and will be removed in" " Click 9.1. Use feature detection or" " 'importlib.metadata.version(\"click\")' instead.", DeprecationWarning, stacklevel=2, ) return importlib.metadata.version("click") raise AttributeError(name) asyncclick-8.3.0.5-async/src/asyncclick/_compat.py000066400000000000000000000444051507140761400220450ustar00rootroot00000000000000from __future__ import annotations import codecs import collections.abc as cabc import io import os import re import sys import typing as t from types import TracebackType from weakref import WeakKeyDictionary CYGWIN = sys.platform.startswith("cygwin") WIN = sys.platform.startswith("win") auto_wrap_for_ansi: t.Callable[[t.TextIO], t.TextIO] | None = None _ansi_re = re.compile(r"\033\[[;?0-9]*[a-zA-Z]") def _make_text_stream( stream: t.BinaryIO, encoding: str | None, errors: str | None, force_readable: bool = False, force_writable: bool = False, ) -> t.TextIO: if encoding is None: encoding = get_best_encoding(stream) if errors is None: errors = "replace" return _NonClosingTextIOWrapper( stream, encoding, errors, line_buffering=True, force_readable=force_readable, force_writable=force_writable, ) def is_ascii_encoding(encoding: str) -> bool: """Checks if a given encoding is ascii.""" try: return codecs.lookup(encoding).name == "ascii" except LookupError: return False def get_best_encoding(stream: t.IO[t.Any]) -> str: """Returns the default stream encoding if not found.""" rv = getattr(stream, "encoding", None) or sys.getdefaultencoding() if is_ascii_encoding(rv): return "utf-8" return rv class _NonClosingTextIOWrapper(io.TextIOWrapper): def __init__( self, stream: t.BinaryIO, encoding: str | None, errors: str | None, force_readable: bool = False, force_writable: bool = False, **extra: t.Any, ) -> None: self._stream = stream = t.cast( t.BinaryIO, _FixupStream(stream, force_readable, force_writable) ) super().__init__(stream, encoding, errors, **extra) def __del__(self) -> None: try: self.detach() except Exception: pass def isatty(self) -> bool: # https://bitbucket.org/pypy/pypy/issue/1803 return self._stream.isatty() class _FixupStream: """The new io interface needs more from streams than streams traditionally implement. As such, this fix-up code is necessary in some circumstances. The forcing of readable and writable flags are there because some tools put badly patched objects on sys (one such offender are certain version of jupyter notebook). """ def __init__( self, stream: t.BinaryIO, force_readable: bool = False, force_writable: bool = False, ): self._stream = stream self._force_readable = force_readable self._force_writable = force_writable def __getattr__(self, name: str) -> t.Any: return getattr(self._stream, name) def read1(self, size: int) -> bytes: f = getattr(self._stream, "read1", None) if f is not None: return t.cast(bytes, f(size)) return self._stream.read(size) def readable(self) -> bool: if self._force_readable: return True x = getattr(self._stream, "readable", None) if x is not None: return t.cast(bool, x()) try: self._stream.read(0) except Exception: return False return True def writable(self) -> bool: if self._force_writable: return True x = getattr(self._stream, "writable", None) if x is not None: return t.cast(bool, x()) try: self._stream.write(b"") except Exception: try: self._stream.write(b"") except Exception: return False return True def seekable(self) -> bool: x = getattr(self._stream, "seekable", None) if x is not None: return t.cast(bool, x()) try: self._stream.seek(self._stream.tell()) except Exception: return False return True def _is_binary_reader(stream: t.IO[t.Any], default: bool = False) -> bool: try: return isinstance(stream.read(0), bytes) except Exception: return default # This happens in some cases where the stream was already # closed. In this case, we assume the default. def _is_binary_writer(stream: t.IO[t.Any], default: bool = False) -> bool: try: stream.write(b"") except Exception: try: stream.write("") return False except Exception: pass return default return True def _find_binary_reader(stream: t.IO[t.Any]) -> t.BinaryIO | None: # We need to figure out if the given stream is already binary. # This can happen because the official docs recommend detaching # the streams to get binary streams. Some code might do this, so # we need to deal with this case explicitly. if _is_binary_reader(stream, False): return t.cast(t.BinaryIO, stream) buf = getattr(stream, "buffer", None) # Same situation here; this time we assume that the buffer is # actually binary in case it's closed. if buf is not None and _is_binary_reader(buf, True): return t.cast(t.BinaryIO, buf) return None def _find_binary_writer(stream: t.IO[t.Any]) -> t.BinaryIO | None: # We need to figure out if the given stream is already binary. # This can happen because the official docs recommend detaching # the streams to get binary streams. Some code might do this, so # we need to deal with this case explicitly. if _is_binary_writer(stream, False): return t.cast(t.BinaryIO, stream) buf = getattr(stream, "buffer", None) # Same situation here; this time we assume that the buffer is # actually binary in case it's closed. if buf is not None and _is_binary_writer(buf, True): return t.cast(t.BinaryIO, buf) return None def _stream_is_misconfigured(stream: t.TextIO) -> bool: """A stream is misconfigured if its encoding is ASCII.""" # If the stream does not have an encoding set, we assume it's set # to ASCII. This appears to happen in certain unittest # environments. It's not quite clear what the correct behavior is # but this at least will force Click to recover somehow. return is_ascii_encoding(getattr(stream, "encoding", None) or "ascii") def _is_compat_stream_attr(stream: t.TextIO, attr: str, value: str | None) -> bool: """A stream attribute is compatible if it is equal to the desired value or the desired value is unset and the attribute has a value. """ stream_value = getattr(stream, attr, None) return stream_value == value or (value is None and stream_value is not None) def _is_compatible_text_stream( stream: t.TextIO, encoding: str | None, errors: str | None ) -> bool: """Check if a stream's encoding and errors attributes are compatible with the desired values. """ return _is_compat_stream_attr( stream, "encoding", encoding ) and _is_compat_stream_attr(stream, "errors", errors) def _force_correct_text_stream( text_stream: t.IO[t.Any], encoding: str | None, errors: str | None, is_binary: t.Callable[[t.IO[t.Any], bool], bool], find_binary: t.Callable[[t.IO[t.Any]], t.BinaryIO | None], force_readable: bool = False, force_writable: bool = False, ) -> t.TextIO: if is_binary(text_stream, False): binary_reader = t.cast(t.BinaryIO, text_stream) else: text_stream = t.cast(t.TextIO, text_stream) # If the stream looks compatible, and won't default to a # misconfigured ascii encoding, return it as-is. if _is_compatible_text_stream(text_stream, encoding, errors) and not ( encoding is None and _stream_is_misconfigured(text_stream) ): return text_stream # Otherwise, get the underlying binary reader. possible_binary_reader = find_binary(text_stream) # If that's not possible, silently use the original reader # and get mojibake instead of exceptions. if possible_binary_reader is None: return text_stream binary_reader = possible_binary_reader # Default errors to replace instead of strict in order to get # something that works. if errors is None: errors = "replace" # Wrap the binary stream in a text stream with the correct # encoding parameters. return _make_text_stream( binary_reader, encoding, errors, force_readable=force_readable, force_writable=force_writable, ) def _force_correct_text_reader( text_reader: t.IO[t.Any], encoding: str | None, errors: str | None, force_readable: bool = False, ) -> t.TextIO: return _force_correct_text_stream( text_reader, encoding, errors, _is_binary_reader, _find_binary_reader, force_readable=force_readable, ) def _force_correct_text_writer( text_writer: t.IO[t.Any], encoding: str | None, errors: str | None, force_writable: bool = False, ) -> t.TextIO: return _force_correct_text_stream( text_writer, encoding, errors, _is_binary_writer, _find_binary_writer, force_writable=force_writable, ) def get_binary_stdin() -> t.BinaryIO: reader = _find_binary_reader(sys.stdin) if reader is None: raise RuntimeError("Was not able to determine binary stream for sys.stdin.") return reader def get_binary_stdout() -> t.BinaryIO: writer = _find_binary_writer(sys.stdout) if writer is None: raise RuntimeError("Was not able to determine binary stream for sys.stdout.") return writer def get_binary_stderr() -> t.BinaryIO: writer = _find_binary_writer(sys.stderr) if writer is None: raise RuntimeError("Was not able to determine binary stream for sys.stderr.") return writer def get_text_stdin(encoding: str | None = None, errors: str | None = None) -> t.TextIO: rv = _get_windows_console_stream(sys.stdin, encoding, errors) if rv is not None: return rv return _force_correct_text_reader(sys.stdin, encoding, errors, force_readable=True) def get_text_stdout(encoding: str | None = None, errors: str | None = None) -> t.TextIO: rv = _get_windows_console_stream(sys.stdout, encoding, errors) if rv is not None: return rv return _force_correct_text_writer(sys.stdout, encoding, errors, force_writable=True) def get_text_stderr(encoding: str | None = None, errors: str | None = None) -> t.TextIO: rv = _get_windows_console_stream(sys.stderr, encoding, errors) if rv is not None: return rv return _force_correct_text_writer(sys.stderr, encoding, errors, force_writable=True) def _wrap_io_open( file: str | os.PathLike[str] | int, mode: str, encoding: str | None, errors: str | None, ) -> t.IO[t.Any]: """Handles not passing ``encoding`` and ``errors`` in binary mode.""" if "b" in mode: return open(file, mode) return open(file, mode, encoding=encoding, errors=errors) def open_stream( filename: str | os.PathLike[str], mode: str = "r", encoding: str | None = None, errors: str | None = "strict", atomic: bool = False, ) -> tuple[t.IO[t.Any], bool]: binary = "b" in mode filename = os.fspath(filename) # Standard streams first. These are simple because they ignore the # atomic flag. Use fsdecode to handle Path("-"). if os.fsdecode(filename) == "-": if any(m in mode for m in ["w", "a", "x"]): if binary: return get_binary_stdout(), False return get_text_stdout(encoding=encoding, errors=errors), False if binary: return get_binary_stdin(), False return get_text_stdin(encoding=encoding, errors=errors), False # Non-atomic writes directly go out through the regular open functions. if not atomic: return _wrap_io_open(filename, mode, encoding, errors), True # Some usability stuff for atomic writes if "a" in mode: raise ValueError( "Appending to an existing file is not supported, because that" " would involve an expensive `copy`-operation to a temporary" " file. Open the file in normal `w`-mode and copy explicitly" " if that's what you're after." ) if "x" in mode: raise ValueError("Use the `overwrite`-parameter instead.") if "w" not in mode: raise ValueError("Atomic writes only make sense with `w`-mode.") # Atomic writes are more complicated. They work by opening a file # as a proxy in the same folder and then using the fdopen # functionality to wrap it in a Python file. Then we wrap it in an # atomic file that moves the file over on close. import errno import random try: perm: int | None = os.stat(filename).st_mode except OSError: perm = None flags = os.O_RDWR | os.O_CREAT | os.O_EXCL if binary: flags |= getattr(os, "O_BINARY", 0) while True: tmp_filename = os.path.join( os.path.dirname(filename), f".__atomic-write{random.randrange(1 << 32):08x}", ) try: fd = os.open(tmp_filename, flags, 0o666 if perm is None else perm) break except OSError as e: if e.errno == errno.EEXIST or ( os.name == "nt" and e.errno == errno.EACCES and os.path.isdir(e.filename) and os.access(e.filename, os.W_OK) ): continue raise if perm is not None: os.chmod(tmp_filename, perm) # in case perm includes bits in umask f = _wrap_io_open(fd, mode, encoding, errors) af = _AtomicFile(f, tmp_filename, os.path.realpath(filename)) return t.cast(t.IO[t.Any], af), True class _AtomicFile: def __init__(self, f: t.IO[t.Any], tmp_filename: str, real_filename: str) -> None: self._f = f self._tmp_filename = tmp_filename self._real_filename = real_filename self.closed = False @property def name(self) -> str: return self._real_filename def close(self, delete: bool = False) -> None: if self.closed: return self._f.close() os.replace(self._tmp_filename, self._real_filename) self.closed = True def __getattr__(self, name: str) -> t.Any: return getattr(self._f, name) def __enter__(self) -> _AtomicFile: return self def __exit__( self, exc_type: type[BaseException] | None, exc_value: BaseException | None, tb: TracebackType | None, ) -> None: self.close(delete=exc_type is not None) def __repr__(self) -> str: return repr(self._f) def strip_ansi(value: str) -> str: return _ansi_re.sub("", value) def _is_jupyter_kernel_output(stream: t.IO[t.Any]) -> bool: while isinstance(stream, (_FixupStream, _NonClosingTextIOWrapper)): stream = stream._stream return stream.__class__.__module__.startswith("ipykernel.") def should_strip_ansi( stream: t.IO[t.Any] | None = None, color: bool | None = None ) -> bool: if color is None: if stream is None: stream = sys.stdin return not isatty(stream) and not _is_jupyter_kernel_output(stream) return not color # On Windows, wrap the output streams with colorama to support ANSI # color codes. # NOTE: double check is needed so mypy does not analyze this on Linux if sys.platform.startswith("win") and WIN: from ._winconsole import _get_windows_console_stream def _get_argv_encoding() -> str: import locale return locale.getpreferredencoding() _ansi_stream_wrappers: cabc.MutableMapping[t.TextIO, t.TextIO] = WeakKeyDictionary() def auto_wrap_for_ansi(stream: t.TextIO, color: bool | None = None) -> t.TextIO: """Support ANSI color and style codes on Windows by wrapping a stream with colorama. """ try: cached = _ansi_stream_wrappers.get(stream) except Exception: cached = None if cached is not None: return cached import colorama strip = should_strip_ansi(stream, color) ansi_wrapper = colorama.AnsiToWin32(stream, strip=strip) rv = t.cast(t.TextIO, ansi_wrapper.stream) _write = rv.write def _safe_write(s: str) -> int: try: return _write(s) except BaseException: ansi_wrapper.reset_all() raise rv.write = _safe_write # type: ignore[method-assign] try: _ansi_stream_wrappers[stream] = rv except Exception: pass return rv else: def _get_argv_encoding() -> str: return getattr(sys.stdin, "encoding", None) or sys.getfilesystemencoding() def _get_windows_console_stream( f: t.TextIO, encoding: str | None, errors: str | None ) -> t.TextIO | None: return None def term_len(x: str) -> int: return len(strip_ansi(x)) def isatty(stream: t.IO[t.Any]) -> bool: try: return stream.isatty() except Exception: return False def _make_cached_stream_func( src_func: t.Callable[[], t.TextIO | None], wrapper_func: t.Callable[[], t.TextIO], ) -> t.Callable[[], t.TextIO | None]: cache: cabc.MutableMapping[t.TextIO, t.TextIO] = WeakKeyDictionary() def func() -> t.TextIO | None: stream = src_func() if stream is None: return None try: rv = cache.get(stream) except Exception: rv = None if rv is not None: return rv rv = wrapper_func() try: cache[stream] = rv except Exception: pass return rv return func _default_text_stdin = _make_cached_stream_func(lambda: sys.stdin, get_text_stdin) _default_text_stdout = _make_cached_stream_func(lambda: sys.stdout, get_text_stdout) _default_text_stderr = _make_cached_stream_func(lambda: sys.stderr, get_text_stderr) binary_streams: cabc.Mapping[str, t.Callable[[], t.BinaryIO]] = { "stdin": get_binary_stdin, "stdout": get_binary_stdout, "stderr": get_binary_stderr, } text_streams: cabc.Mapping[str, t.Callable[[str | None, str | None], t.TextIO]] = { "stdin": get_text_stdin, "stdout": get_text_stdout, "stderr": get_text_stderr, } asyncclick-8.3.0.5-async/src/asyncclick/_termui_impl.py000066400000000000000000000642571507140761400231170ustar00rootroot00000000000000""" This module contains implementations for the termui module. To keep the import time of Click down, some infrequently used functionality is placed in this module and only imported as needed. """ from __future__ import annotations import collections.abc as cabc import contextlib import math import os import shlex import sys import time import typing as t from gettext import gettext as _ from io import StringIO from pathlib import Path from types import TracebackType from ._compat import _default_text_stdout from ._compat import CYGWIN from ._compat import get_best_encoding from ._compat import isatty from ._compat import open_stream from ._compat import strip_ansi from ._compat import term_len from ._compat import WIN from .exceptions import ClickException from .utils import echo V = t.TypeVar("V") if os.name == "nt": BEFORE_BAR = "\r" AFTER_BAR = "\n" else: BEFORE_BAR = "\r\033[?25l" AFTER_BAR = "\033[?25h\n" class ProgressBar(t.Generic[V]): def __init__( self, iterable: cabc.Iterable[V] | None, length: int | None = None, fill_char: str = "#", empty_char: str = " ", bar_template: str = "%(bar)s", info_sep: str = " ", hidden: bool = False, show_eta: bool = True, show_percent: bool | None = None, show_pos: bool = False, item_show_func: t.Callable[[V | None], str | None] | None = None, label: str | None = None, file: t.TextIO | None = None, color: bool | None = None, update_min_steps: int = 1, width: int = 30, ) -> None: self.fill_char = fill_char self.empty_char = empty_char self.bar_template = bar_template self.info_sep = info_sep self.hidden = hidden self.show_eta = show_eta self.show_percent = show_percent self.show_pos = show_pos self.item_show_func = item_show_func self.label: str = label or "" if file is None: file = _default_text_stdout() # There are no standard streams attached to write to. For example, # pythonw on Windows. if file is None: file = StringIO() self.file = file self.color = color self.update_min_steps = update_min_steps self._completed_intervals = 0 self.width: int = width self.autowidth: bool = width == 0 if length is None: from operator import length_hint length = length_hint(iterable, -1) if length == -1: length = None if iterable is None: if length is None: raise TypeError("iterable or length is required") iterable = t.cast("cabc.Iterable[V]", range(length)) self.iter: cabc.Iterable[V] = iter(iterable) self.length = length self.pos: int = 0 self.avg: list[float] = [] self.last_eta: float self.start: float self.start = self.last_eta = time.time() self.eta_known: bool = False self.finished: bool = False self.max_width: int | None = None self.entered: bool = False self.current_item: V | None = None self._is_atty = isatty(self.file) self._last_line: str | None = None def __enter__(self) -> ProgressBar[V]: self.entered = True self.render_progress() return self def __exit__( self, exc_type: type[BaseException] | None, exc_value: BaseException | None, tb: TracebackType | None, ) -> None: self.render_finish() def __iter__(self) -> cabc.Iterator[V]: if not self.entered: raise RuntimeError("You need to use progress bars in a with block.") self.render_progress() return self.generator() def __next__(self) -> V: # Iteration is defined in terms of a generator function, # returned by iter(self); use that to define next(). This works # because `self.iter` is an iterable consumed by that generator, # so it is re-entry safe. Calling `next(self.generator())` # twice works and does "what you want". return next(iter(self)) def render_finish(self) -> None: if self.hidden or not self._is_atty: return self.file.write(AFTER_BAR) self.file.flush() @property def pct(self) -> float: if self.finished: return 1.0 return min(self.pos / (float(self.length or 1) or 1), 1.0) @property def time_per_iteration(self) -> float: if not self.avg: return 0.0 return sum(self.avg) / float(len(self.avg)) @property def eta(self) -> float: if self.length is not None and not self.finished: return self.time_per_iteration * (self.length - self.pos) return 0.0 def format_eta(self) -> str: if self.eta_known: t = int(self.eta) seconds = t % 60 t //= 60 minutes = t % 60 t //= 60 hours = t % 24 t //= 24 if t > 0: return f"{t}d {hours:02}:{minutes:02}:{seconds:02}" else: return f"{hours:02}:{minutes:02}:{seconds:02}" return "" def format_pos(self) -> str: pos = str(self.pos) if self.length is not None: pos += f"/{self.length}" return pos def format_pct(self) -> str: return f"{int(self.pct * 100): 4}%"[1:] def format_bar(self) -> str: if self.length is not None: bar_length = int(self.pct * self.width) bar = self.fill_char * bar_length bar += self.empty_char * (self.width - bar_length) elif self.finished: bar = self.fill_char * self.width else: chars = list(self.empty_char * (self.width or 1)) if self.time_per_iteration != 0: chars[ int( (math.cos(self.pos * self.time_per_iteration) / 2.0 + 0.5) * self.width ) ] = self.fill_char bar = "".join(chars) return bar def format_progress_line(self) -> str: show_percent = self.show_percent info_bits = [] if self.length is not None and show_percent is None: show_percent = not self.show_pos if self.show_pos: info_bits.append(self.format_pos()) if show_percent: info_bits.append(self.format_pct()) if self.show_eta and self.eta_known and not self.finished: info_bits.append(self.format_eta()) if self.item_show_func is not None: item_info = self.item_show_func(self.current_item) if item_info is not None: info_bits.append(item_info) return ( self.bar_template % { "label": self.label, "bar": self.format_bar(), "info": self.info_sep.join(info_bits), } ).rstrip() def render_progress(self) -> None: if self.hidden: return if not self._is_atty: # Only output the label once if the output is not a TTY. if self._last_line != self.label: self._last_line = self.label echo(self.label, file=self.file, color=self.color) return buf = [] # Update width in case the terminal has been resized if self.autowidth: import shutil old_width = self.width self.width = 0 clutter_length = term_len(self.format_progress_line()) new_width = max(0, shutil.get_terminal_size().columns - clutter_length) if new_width < old_width and self.max_width is not None: buf.append(BEFORE_BAR) buf.append(" " * self.max_width) self.max_width = new_width self.width = new_width clear_width = self.width if self.max_width is not None: clear_width = self.max_width buf.append(BEFORE_BAR) line = self.format_progress_line() line_len = term_len(line) if self.max_width is None or self.max_width < line_len: self.max_width = line_len buf.append(line) buf.append(" " * (clear_width - line_len)) line = "".join(buf) # Render the line only if it changed. if line != self._last_line: self._last_line = line echo(line, file=self.file, color=self.color, nl=False) self.file.flush() def make_step(self, n_steps: int) -> None: self.pos += n_steps if self.length is not None and self.pos >= self.length: self.finished = True if (time.time() - self.last_eta) < 1.0: return self.last_eta = time.time() # self.avg is a rolling list of length <= 7 of steps where steps are # defined as time elapsed divided by the total progress through # self.length. if self.pos: step = (time.time() - self.start) / self.pos else: step = time.time() - self.start self.avg = self.avg[-6:] + [step] self.eta_known = self.length is not None def update(self, n_steps: int, current_item: V | None = None) -> None: """Update the progress bar by advancing a specified number of steps, and optionally set the ``current_item`` for this new position. :param n_steps: Number of steps to advance. :param current_item: Optional item to set as ``current_item`` for the updated position. .. versionchanged:: 8.0 Added the ``current_item`` optional parameter. .. versionchanged:: 8.0 Only render when the number of steps meets the ``update_min_steps`` threshold. """ if current_item is not None: self.current_item = current_item self._completed_intervals += n_steps if self._completed_intervals >= self.update_min_steps: self.make_step(self._completed_intervals) self.render_progress() self._completed_intervals = 0 def finish(self) -> None: self.eta_known = False self.current_item = None self.finished = True def generator(self) -> cabc.Iterator[V]: """Return a generator which yields the items added to the bar during construction, and updates the progress bar *after* the yielded block returns. """ # WARNING: the iterator interface for `ProgressBar` relies on # this and only works because this is a simple generator which # doesn't create or manage additional state. If this function # changes, the impact should be evaluated both against # `iter(bar)` and `next(bar)`. `next()` in particular may call # `self.generator()` repeatedly, and this must remain safe in # order for that interface to work. if not self.entered: raise RuntimeError("You need to use progress bars in a with block.") if not self._is_atty: yield from self.iter else: for rv in self.iter: self.current_item = rv # This allows show_item_func to be updated before the # item is processed. Only trigger at the beginning of # the update interval. if self._completed_intervals == 0: self.render_progress() yield rv self.update(1) self.finish() self.render_progress() def pager(generator: cabc.Iterable[str], color: bool | None = None) -> None: """Decide what method to use for paging through text.""" stdout = _default_text_stdout() # There are no standard streams attached to write to. For example, # pythonw on Windows. if stdout is None: stdout = StringIO() if not isatty(sys.stdin) or not isatty(stdout): return _nullpager(stdout, generator, color) # Split and normalize the pager command into parts. pager_cmd_parts = shlex.split(os.environ.get("PAGER", ""), posix=False) if pager_cmd_parts: if WIN: if _tempfilepager(generator, pager_cmd_parts, color): return elif _pipepager(generator, pager_cmd_parts, color): return if os.environ.get("TERM") in ("dumb", "emacs"): return _nullpager(stdout, generator, color) if (WIN or sys.platform.startswith("os2")) and _tempfilepager( generator, ["more"], color ): return if _pipepager(generator, ["less"], color): return import tempfile fd, filename = tempfile.mkstemp() os.close(fd) try: if _pipepager(generator, ["more"], color): return return _nullpager(stdout, generator, color) finally: os.unlink(filename) def _pipepager( generator: cabc.Iterable[str], cmd_parts: list[str], color: bool | None ) -> bool: """Page through text by feeding it to another program. Invoking a pager through this might support colors. Returns `True` if the command was found, `False` otherwise and thus another pager should be attempted. """ # Split the command into the invoked CLI and its parameters. if not cmd_parts: return False import shutil cmd = cmd_parts[0] cmd_params = cmd_parts[1:] cmd_filepath = shutil.which(cmd) if not cmd_filepath: return False # Resolves symlinks and produces a normalized absolute path string. cmd_path = Path(cmd_filepath).resolve() cmd_name = cmd_path.name import subprocess # Make a local copy of the environment to not affect the global one. env = dict(os.environ) # If we're piping to less and the user hasn't decided on colors, we enable # them by default we find the -R flag in the command line arguments. if color is None and cmd_name == "less": less_flags = f"{os.environ.get('LESS', '')}{' '.join(cmd_params)}" if not less_flags: env["LESS"] = "-R" color = True elif "r" in less_flags or "R" in less_flags: color = True c = subprocess.Popen( [str(cmd_path)] + cmd_params, shell=True, stdin=subprocess.PIPE, env=env, errors="replace", text=True, ) assert c.stdin is not None try: for text in generator: if not color: text = strip_ansi(text) c.stdin.write(text) except BrokenPipeError: # In case the pager exited unexpectedly, ignore the broken pipe error. pass except Exception as e: # In case there is an exception we want to close the pager immediately # and let the caller handle it. # Otherwise the pager will keep running, and the user may not notice # the error message, or worse yet it may leave the terminal in a broken state. c.terminate() raise e finally: # We must close stdin and wait for the pager to exit before we continue try: c.stdin.close() # Close implies flush, so it might throw a BrokenPipeError if the pager # process exited already. except BrokenPipeError: pass # Less doesn't respect ^C, but catches it for its own UI purposes (aborting # search or other commands inside less). # # That means when the user hits ^C, the parent process (click) terminates, # but less is still alive, paging the output and messing up the terminal. # # If the user wants to make the pager exit on ^C, they should set # `LESS='-K'`. It's not our decision to make. while True: try: c.wait() except KeyboardInterrupt: pass else: break return True def _tempfilepager( generator: cabc.Iterable[str], cmd_parts: list[str], color: bool | None ) -> bool: """Page through text by invoking a program on a temporary file. Returns `True` if the command was found, `False` otherwise and thus another pager should be attempted. """ # Split the command into the invoked CLI and its parameters. if not cmd_parts: return False import shutil cmd = cmd_parts[0] cmd_filepath = shutil.which(cmd) if not cmd_filepath: return False # Resolves symlinks and produces a normalized absolute path string. cmd_path = Path(cmd_filepath).resolve() import subprocess import tempfile fd, filename = tempfile.mkstemp() # TODO: This never terminates if the passed generator never terminates. text = "".join(generator) if not color: text = strip_ansi(text) encoding = get_best_encoding(sys.stdout) with open_stream(filename, "wb")[0] as f: f.write(text.encode(encoding)) try: subprocess.call([str(cmd_path), filename]) except OSError: # Command not found pass finally: os.close(fd) os.unlink(filename) return True def _nullpager( stream: t.TextIO, generator: cabc.Iterable[str], color: bool | None ) -> None: """Simply print unformatted text. This is the ultimate fallback.""" for text in generator: if not color: text = strip_ansi(text) stream.write(text) class Editor: def __init__( self, editor: str | None = None, env: cabc.Mapping[str, str] | None = None, require_save: bool = True, extension: str = ".txt", ) -> None: self.editor = editor self.env = env self.require_save = require_save self.extension = extension def get_editor(self) -> str: if self.editor is not None: return self.editor for key in "VISUAL", "EDITOR": rv = os.environ.get(key) if rv: return rv if WIN: return "notepad" from shutil import which for editor in "sensible-editor", "vim", "nano": if which(editor) is not None: return editor return "vi" def edit_files(self, filenames: cabc.Iterable[str]) -> None: import subprocess editor = self.get_editor() environ: dict[str, str] | None = None if self.env: environ = os.environ.copy() environ.update(self.env) exc_filename = " ".join(f'"{filename}"' for filename in filenames) try: c = subprocess.Popen( args=f"{editor} {exc_filename}", env=environ, shell=True ) exit_code = c.wait() if exit_code != 0: raise ClickException( _("{editor}: Editing failed").format(editor=editor) ) except OSError as e: raise ClickException( _("{editor}: Editing failed: {e}").format(editor=editor, e=e) ) from e @t.overload def edit(self, text: bytes | bytearray) -> bytes | None: ... # We cannot know whether or not the type expected is str or bytes when None # is passed, so str is returned as that was what was done before. @t.overload def edit(self, text: str | None) -> str | None: ... def edit(self, text: str | bytes | bytearray | None) -> str | bytes | None: import tempfile if text is None: data: bytes | bytearray = b"" elif isinstance(text, (bytes, bytearray)): data = text else: if text and not text.endswith("\n"): text += "\n" if WIN: data = text.replace("\n", "\r\n").encode("utf-8-sig") else: data = text.encode("utf-8") fd, name = tempfile.mkstemp(prefix="editor-", suffix=self.extension) f: t.BinaryIO try: with os.fdopen(fd, "wb") as f: f.write(data) # If the filesystem resolution is 1 second, like Mac OS # 10.12 Extended, or 2 seconds, like FAT32, and the editor # closes very fast, require_save can fail. Set the modified # time to be 2 seconds in the past to work around this. os.utime(name, (os.path.getatime(name), os.path.getmtime(name) - 2)) # Depending on the resolution, the exact value might not be # recorded, so get the new recorded value. timestamp = os.path.getmtime(name) self.edit_files((name,)) if self.require_save and os.path.getmtime(name) == timestamp: return None with open(name, "rb") as f: rv = f.read() if isinstance(text, (bytes, bytearray)): return rv return rv.decode("utf-8-sig").replace("\r\n", "\n") finally: os.unlink(name) def open_url(url: str, wait: bool = False, locate: bool = False) -> int: import subprocess def _unquote_file(url: str) -> str: from urllib.parse import unquote if url.startswith("file://"): url = unquote(url[7:]) return url if sys.platform == "darwin": args = ["open"] if wait: args.append("-W") if locate: args.append("-R") args.append(_unquote_file(url)) null = open("/dev/null", "w") try: return subprocess.Popen(args, stderr=null).wait() finally: null.close() elif WIN: if locate: url = _unquote_file(url) args = ["explorer", f"/select,{url}"] else: args = ["start"] if wait: args.append("/WAIT") args.append("") args.append(url) try: return subprocess.call(args) except OSError: # Command not found return 127 elif CYGWIN: if locate: url = _unquote_file(url) args = ["cygstart", os.path.dirname(url)] else: args = ["cygstart"] if wait: args.append("-w") args.append(url) try: return subprocess.call(args) except OSError: # Command not found return 127 try: if locate: url = os.path.dirname(_unquote_file(url)) or "." else: url = _unquote_file(url) c = subprocess.Popen(["xdg-open", url]) if wait: return c.wait() return 0 except OSError: if url.startswith(("http://", "https://")) and not locate and not wait: import webbrowser webbrowser.open(url) return 0 return 1 def _translate_ch_to_exc(ch: str) -> None: if ch == "\x03": raise KeyboardInterrupt() if ch == "\x04" and not WIN: # Unix-like, Ctrl+D raise EOFError() if ch == "\x1a" and WIN: # Windows, Ctrl+Z raise EOFError() return None if sys.platform == "win32": import msvcrt @contextlib.contextmanager def raw_terminal() -> cabc.Iterator[int]: yield -1 def getchar(echo: bool) -> str: # The function `getch` will return a bytes object corresponding to # the pressed character. Since Windows 10 build 1803, it will also # return \x00 when called a second time after pressing a regular key. # # `getwch` does not share this probably-bugged behavior. Moreover, it # returns a Unicode object by default, which is what we want. # # Either of these functions will return \x00 or \xe0 to indicate # a special key, and you need to call the same function again to get # the "rest" of the code. The fun part is that \u00e0 is # "latin small letter a with grave", so if you type that on a French # keyboard, you _also_ get a \xe0. # E.g., consider the Up arrow. This returns \xe0 and then \x48. The # resulting Unicode string reads as "a with grave" + "capital H". # This is indistinguishable from when the user actually types # "a with grave" and then "capital H". # # When \xe0 is returned, we assume it's part of a special-key sequence # and call `getwch` again, but that means that when the user types # the \u00e0 character, `getchar` doesn't return until a second # character is typed. # The alternative is returning immediately, but that would mess up # cross-platform handling of arrow keys and others that start with # \xe0. Another option is using `getch`, but then we can't reliably # read non-ASCII characters, because return values of `getch` are # limited to the current 8-bit codepage. # # Anyway, Click doesn't claim to do this Right(tm), and using `getwch` # is doing the right thing in more situations than with `getch`. if echo: func = t.cast(t.Callable[[], str], msvcrt.getwche) else: func = t.cast(t.Callable[[], str], msvcrt.getwch) rv = func() if rv in ("\x00", "\xe0"): # \x00 and \xe0 are control characters that indicate special key, # see above. rv += func() _translate_ch_to_exc(rv) return rv else: import termios import tty @contextlib.contextmanager def raw_terminal() -> cabc.Iterator[int]: f: t.TextIO | None fd: int if not isatty(sys.stdin): f = open("/dev/tty") fd = f.fileno() else: fd = sys.stdin.fileno() f = None try: old_settings = termios.tcgetattr(fd) try: tty.setraw(fd) yield fd finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) sys.stdout.flush() if f is not None: f.close() except termios.error: pass def getchar(echo: bool) -> str: with raw_terminal() as fd: ch = os.read(fd, 32).decode(get_best_encoding(sys.stdin), "replace") if echo and isatty(sys.stdout): sys.stdout.write(ch) _translate_ch_to_exc(ch) return ch asyncclick-8.3.0.5-async/src/asyncclick/_textwrap.py000066400000000000000000000025701507140761400224350ustar00rootroot00000000000000from __future__ import annotations import collections.abc as cabc import textwrap from contextlib import contextmanager class TextWrapper(textwrap.TextWrapper): def _handle_long_word( self, reversed_chunks: list[str], cur_line: list[str], cur_len: int, width: int, ) -> None: space_left = max(width - cur_len, 1) if self.break_long_words: last = reversed_chunks[-1] cut = last[:space_left] res = last[space_left:] cur_line.append(cut) reversed_chunks[-1] = res elif not cur_line: cur_line.append(reversed_chunks.pop()) @contextmanager def extra_indent(self, indent: str) -> cabc.Iterator[None]: old_initial_indent = self.initial_indent old_subsequent_indent = self.subsequent_indent self.initial_indent += indent self.subsequent_indent += indent try: yield finally: self.initial_indent = old_initial_indent self.subsequent_indent = old_subsequent_indent def indent_only(self, text: str) -> str: rv = [] for idx, line in enumerate(text.splitlines()): indent = self.initial_indent if idx > 0: indent = self.subsequent_indent rv.append(f"{indent}{line}") return "\n".join(rv) asyncclick-8.3.0.5-async/src/asyncclick/_utils.py000066400000000000000000000016571507140761400217240ustar00rootroot00000000000000from __future__ import annotations import enum import typing as t class Sentinel(enum.Enum): """Enum used to define sentinel values. .. seealso:: `PEP 661 - Sentinel Values `_. """ UNSET = object() FLAG_NEEDS_VALUE = object() def __repr__(self) -> str: return f"{self.__class__.__name__}.{self.name}" UNSET = Sentinel.UNSET """Sentinel used to indicate that a value is not set.""" FLAG_NEEDS_VALUE = Sentinel.FLAG_NEEDS_VALUE """Sentinel used to indicate an option was passed as a flag without a value but is not a flag option. ``Option.consume_value`` uses this to prompt or use the ``flag_value``. """ T_UNSET = t.Literal[UNSET] # type: ignore[valid-type] """Type hint for the :data:`UNSET` sentinel value.""" T_FLAG_NEEDS_VALUE = t.Literal[FLAG_NEEDS_VALUE] # type: ignore[valid-type] """Type hint for the :data:`FLAG_NEEDS_VALUE` sentinel value.""" asyncclick-8.3.0.5-async/src/asyncclick/_winconsole.py000066400000000000000000000204211507140761400227320ustar00rootroot00000000000000# This module is based on the excellent work by Adam Bartoš who # provided a lot of what went into the implementation here in # the discussion to issue1602 in the Python bug tracker. # # There are some general differences in regards to how this works # compared to the original patches as we do not need to patch # the entire interpreter but just work in our little world of # echo and prompt. from __future__ import annotations import collections.abc as cabc import io import sys import time import typing as t from ctypes import Array from ctypes import byref from ctypes import c_char from ctypes import c_char_p from ctypes import c_int from ctypes import c_ssize_t from ctypes import c_ulong from ctypes import c_void_p from ctypes import POINTER from ctypes import py_object from ctypes import Structure from ctypes.wintypes import DWORD from ctypes.wintypes import HANDLE from ctypes.wintypes import LPCWSTR from ctypes.wintypes import LPWSTR from ._compat import _NonClosingTextIOWrapper assert sys.platform == "win32" import msvcrt # noqa: E402 from ctypes import windll # noqa: E402 from ctypes import WINFUNCTYPE # noqa: E402 c_ssize_p = POINTER(c_ssize_t) kernel32 = windll.kernel32 GetStdHandle = kernel32.GetStdHandle ReadConsoleW = kernel32.ReadConsoleW WriteConsoleW = kernel32.WriteConsoleW GetConsoleMode = kernel32.GetConsoleMode GetLastError = kernel32.GetLastError GetCommandLineW = WINFUNCTYPE(LPWSTR)(("GetCommandLineW", windll.kernel32)) CommandLineToArgvW = WINFUNCTYPE(POINTER(LPWSTR), LPCWSTR, POINTER(c_int))( ("CommandLineToArgvW", windll.shell32) ) LocalFree = WINFUNCTYPE(c_void_p, c_void_p)(("LocalFree", windll.kernel32)) STDIN_HANDLE = GetStdHandle(-10) STDOUT_HANDLE = GetStdHandle(-11) STDERR_HANDLE = GetStdHandle(-12) PyBUF_SIMPLE = 0 PyBUF_WRITABLE = 1 ERROR_SUCCESS = 0 ERROR_NOT_ENOUGH_MEMORY = 8 ERROR_OPERATION_ABORTED = 995 STDIN_FILENO = 0 STDOUT_FILENO = 1 STDERR_FILENO = 2 EOF = b"\x1a" MAX_BYTES_WRITTEN = 32767 if t.TYPE_CHECKING: try: # Using `typing_extensions.Buffer` instead of `collections.abc` # on Windows for some reason does not have `Sized` implemented. from collections.abc import Buffer # type: ignore except ImportError: from typing_extensions import Buffer try: from ctypes import pythonapi except ImportError: # On PyPy we cannot get buffers so our ability to operate here is # severely limited. get_buffer = None else: class Py_buffer(Structure): _fields_ = [ # noqa: RUF012 ("buf", c_void_p), ("obj", py_object), ("len", c_ssize_t), ("itemsize", c_ssize_t), ("readonly", c_int), ("ndim", c_int), ("format", c_char_p), ("shape", c_ssize_p), ("strides", c_ssize_p), ("suboffsets", c_ssize_p), ("internal", c_void_p), ] PyObject_GetBuffer = pythonapi.PyObject_GetBuffer PyBuffer_Release = pythonapi.PyBuffer_Release def get_buffer(obj: Buffer, writable: bool = False) -> Array[c_char]: buf = Py_buffer() flags: int = PyBUF_WRITABLE if writable else PyBUF_SIMPLE PyObject_GetBuffer(py_object(obj), byref(buf), flags) try: buffer_type = c_char * buf.len out: Array[c_char] = buffer_type.from_address(buf.buf) return out finally: PyBuffer_Release(byref(buf)) class _WindowsConsoleRawIOBase(io.RawIOBase): def __init__(self, handle: int | None) -> None: self.handle = handle def isatty(self) -> t.Literal[True]: super().isatty() return True class _WindowsConsoleReader(_WindowsConsoleRawIOBase): def readable(self) -> t.Literal[True]: return True def readinto(self, b: Buffer) -> int: bytes_to_be_read = len(b) if not bytes_to_be_read: return 0 elif bytes_to_be_read % 2: raise ValueError( "cannot read odd number of bytes from UTF-16-LE encoded console" ) buffer = get_buffer(b, writable=True) code_units_to_be_read = bytes_to_be_read // 2 code_units_read = c_ulong() rv = ReadConsoleW( HANDLE(self.handle), buffer, code_units_to_be_read, byref(code_units_read), None, ) if GetLastError() == ERROR_OPERATION_ABORTED: # wait for KeyboardInterrupt time.sleep(0.1) if not rv: raise OSError(f"Windows error: {GetLastError()}") if buffer[0] == EOF: return 0 return 2 * code_units_read.value class _WindowsConsoleWriter(_WindowsConsoleRawIOBase): def writable(self) -> t.Literal[True]: return True @staticmethod def _get_error_message(errno: int) -> str: if errno == ERROR_SUCCESS: return "ERROR_SUCCESS" elif errno == ERROR_NOT_ENOUGH_MEMORY: return "ERROR_NOT_ENOUGH_MEMORY" return f"Windows error {errno}" def write(self, b: Buffer) -> int: bytes_to_be_written = len(b) buf = get_buffer(b) code_units_to_be_written = min(bytes_to_be_written, MAX_BYTES_WRITTEN) // 2 code_units_written = c_ulong() WriteConsoleW( HANDLE(self.handle), buf, code_units_to_be_written, byref(code_units_written), None, ) bytes_written = 2 * code_units_written.value if bytes_written == 0 and bytes_to_be_written > 0: raise OSError(self._get_error_message(GetLastError())) return bytes_written class ConsoleStream: def __init__(self, text_stream: t.TextIO, byte_stream: t.BinaryIO) -> None: self._text_stream = text_stream self.buffer = byte_stream @property def name(self) -> str: return self.buffer.name def write(self, x: t.AnyStr) -> int: if isinstance(x, str): return self._text_stream.write(x) try: self.flush() except Exception: pass return self.buffer.write(x) def writelines(self, lines: cabc.Iterable[t.AnyStr]) -> None: for line in lines: self.write(line) def __getattr__(self, name: str) -> t.Any: return getattr(self._text_stream, name) def isatty(self) -> bool: return self.buffer.isatty() def __repr__(self) -> str: return f"" def _get_text_stdin(buffer_stream: t.BinaryIO) -> t.TextIO: text_stream = _NonClosingTextIOWrapper( io.BufferedReader(_WindowsConsoleReader(STDIN_HANDLE)), "utf-16-le", "strict", line_buffering=True, ) return t.cast(t.TextIO, ConsoleStream(text_stream, buffer_stream)) def _get_text_stdout(buffer_stream: t.BinaryIO) -> t.TextIO: text_stream = _NonClosingTextIOWrapper( io.BufferedWriter(_WindowsConsoleWriter(STDOUT_HANDLE)), "utf-16-le", "strict", line_buffering=True, ) return t.cast(t.TextIO, ConsoleStream(text_stream, buffer_stream)) def _get_text_stderr(buffer_stream: t.BinaryIO) -> t.TextIO: text_stream = _NonClosingTextIOWrapper( io.BufferedWriter(_WindowsConsoleWriter(STDERR_HANDLE)), "utf-16-le", "strict", line_buffering=True, ) return t.cast(t.TextIO, ConsoleStream(text_stream, buffer_stream)) _stream_factories: cabc.Mapping[int, t.Callable[[t.BinaryIO], t.TextIO]] = { 0: _get_text_stdin, 1: _get_text_stdout, 2: _get_text_stderr, } def _is_console(f: t.TextIO) -> bool: if not hasattr(f, "fileno"): return False try: fileno = f.fileno() except (OSError, io.UnsupportedOperation): return False handle = msvcrt.get_osfhandle(fileno) return bool(GetConsoleMode(handle, byref(DWORD()))) def _get_windows_console_stream( f: t.TextIO, encoding: str | None, errors: str | None ) -> t.TextIO | None: if ( get_buffer is None or encoding not in {"utf-16-le", None} or errors not in {"strict", None} or not _is_console(f) ): return None func = _stream_factories.get(f.fileno()) if func is None: return None b = getattr(f, "buffer", None) if b is None: return None return func(b) asyncclick-8.3.0.5-async/src/asyncclick/core.py000066400000000000000000004033001507140761400213440ustar00rootroot00000000000000from __future__ import annotations import collections.abc as cabc import enum import errno import inspect import os import sys import typing as t from collections import abc from collections import Counter from contextlib import AbstractContextManager from contextlib import asynccontextmanager from contextlib import AsyncExitStack from contextlib import contextmanager from functools import update_wrapper from gettext import gettext as _ from gettext import ngettext from inspect import iscoroutine from itertools import repeat from types import TracebackType from . import types from ._utils import FLAG_NEEDS_VALUE from ._utils import UNSET from .exceptions import Abort from .exceptions import BadParameter from .exceptions import ClickException from .exceptions import Exit from .exceptions import MissingParameter from .exceptions import NoArgsIsHelpError from .exceptions import UsageError from .formatting import HelpFormatter from .formatting import join_options from .globals import pop_context from .globals import push_context from .parser import _OptionParser from .parser import _split_opt from .termui import confirm from .termui import prompt from .termui import style from .utils import _detect_program_name from .utils import _expand_args from .utils import echo from .utils import make_default_short_help from .utils import make_str from .utils import PacifyFlushWrapper if t.TYPE_CHECKING: from collections.abc import Awaitable from typing import Any from .shell_completion import CompletionItem F = t.TypeVar("F", bound="t.Callable[..., t.Any]") V = t.TypeVar("V") def _complete_visible_commands( ctx: Context, incomplete: str ) -> cabc.Iterator[tuple[str, Command]]: """List all the subcommands of a group that start with the incomplete value and aren't hidden. :param ctx: Invocation context for the group. :param incomplete: Value being completed. May be empty. """ multi = t.cast(Group, ctx.command) for name in multi.list_commands(ctx): if name.startswith(incomplete): command = multi.get_command(ctx, name) if command is not None and not command.hidden: yield name, command def _check_nested_chain( base_command: Group, cmd_name: str, cmd: Command, register: bool = False ) -> None: if not base_command.chain or not isinstance(cmd, Group): return if register: message = ( f"It is not possible to add the group {cmd_name!r} to another" f" group {base_command.name!r} that is in chain mode." ) else: message = ( f"Found the group {cmd_name!r} as subcommand to another group " f" {base_command.name!r} that is in chain mode. This is not supported." ) raise RuntimeError(message) def batch(iterable: cabc.Iterable[V], batch_size: int) -> list[tuple[V, ...]]: return list(zip(*repeat(iter(iterable), batch_size), strict=False)) @contextmanager def augment_usage_errors( ctx: Context, param: Parameter | None = None ) -> cabc.Iterator[None]: """Context manager that attaches extra information to exceptions.""" try: yield except BadParameter as e: if e.ctx is None: e.ctx = ctx if param is not None and e.param is None: e.param = param raise except UsageError as e: if e.ctx is None: e.ctx = ctx raise def iter_params_for_processing( invocation_order: cabc.Sequence[Parameter], declaration_order: cabc.Sequence[Parameter], ) -> list[Parameter]: """Returns all declared parameters in the order they should be processed. The declared parameters are re-shuffled depending on the order in which they were invoked, as well as the eagerness of each parameters. The invocation order takes precedence over the declaration order. I.e. the order in which the user provided them to the CLI is respected. This behavior and its effect on callback evaluation is detailed at: https://click.palletsprojects.com/en/stable/advanced/#callback-evaluation-order """ def sort_key(item: Parameter) -> tuple[bool, float]: try: idx: float = invocation_order.index(item) except ValueError: idx = float("inf") return not item.is_eager, idx return sorted(declaration_order, key=sort_key) class ParameterSource(enum.Enum): """This is an :class:`~enum.Enum` that indicates the source of a parameter's value. Use :meth:`click.Context.get_parameter_source` to get the source for a parameter by name. .. versionchanged:: 8.0 Use :class:`~enum.Enum` and drop the ``validate`` method. .. versionchanged:: 8.0 Added the ``PROMPT`` value. """ COMMANDLINE = enum.auto() """The value was provided by the command line args.""" ENVIRONMENT = enum.auto() """The value was provided with an environment variable.""" DEFAULT = enum.auto() """Used the default specified by the parameter.""" DEFAULT_MAP = enum.auto() """Used a default provided by :attr:`Context.default_map`.""" PROMPT = enum.auto() """Used a prompt to confirm a default or provide a value.""" class Context: """The context is a special internal object that holds state relevant for the script execution at every single level. It's normally invisible to commands unless they opt-in to getting access to it. The context is useful as it can pass internal objects around and can control special execution features such as reading data from environment variables. A context can be used as async context manager in which case it will close any managed contexts, and call :meth:`close` on teardown. :param command: the command class for this context. :param parent: the parent context. :param info_name: the info name for this invocation. Generally this is the most descriptive name for the script or command. For the toplevel script it is usually the name of the script, for commands below it it's the name of the script. :param obj: an arbitrary object of user data. :param auto_envvar_prefix: the prefix to use for automatic environment variables. If this is `None` then reading from environment variables is disabled. This does not affect manually set environment variables which are always read. :param default_map: a dictionary (like object) with default values for parameters. :param terminal_width: the width of the terminal. The default is inherit from parent context. If no context defines the terminal width then auto detection will be applied. :param max_content_width: the maximum width for content rendered by Click (this currently only affects help pages). This defaults to 80 characters if not overridden. In other words: even if the terminal is larger than that, Click will not format things wider than 80 characters by default. In addition to that, formatters might add some safety mapping on the right. :param resilient_parsing: if this flag is enabled then Click will parse without any interactivity or callback invocation. Default values will also be ignored. This is useful for implementing things such as completion support. :param allow_extra_args: if this is set to `True` then extra arguments at the end will not raise an error and will be kept on the context. The default is to inherit from the command. :param allow_interspersed_args: if this is set to `False` then options and arguments cannot be mixed. The default is to inherit from the command. :param ignore_unknown_options: instructs click to ignore options it does not know and keeps them for later processing. :param help_option_names: optionally a list of strings that define how the default help parameter is named. The default is ``['--help']``. :param token_normalize_func: an optional function that is used to normalize tokens (options, choices, etc.). This for instance can be used to implement case insensitive behavior. :param color: controls if the terminal supports ANSI colors or not. The default is autodetection. This is only needed if ANSI codes are used in texts that Click prints which is by default not the case. This for instance would affect help output. :param show_default: Show the default value for commands. If this value is not set, it defaults to the value from the parent context. ``Command.show_default`` overrides this default for the specific command. .. versionchanged:: 8.2 The ``protected_args`` attribute is deprecated and will be removed in Click 9.0. ``args`` will contain remaining unparsed tokens. .. versionchanged:: 8.1 The ``show_default`` parameter is overridden by ``Command.show_default``, instead of the other way around. .. versionchanged:: 8.0 The ``show_default`` parameter defaults to the value from the parent context. .. versionchanged:: 7.1 Added the ``show_default`` parameter. .. versionchanged:: 4.0 Added the ``color``, ``ignore_unknown_options``, and ``max_content_width`` parameters. .. versionchanged:: 3.0 Added the ``allow_extra_args`` and ``allow_interspersed_args`` parameters. .. versionchanged:: 2.0 Added the ``resilient_parsing``, ``help_option_names``, and ``token_normalize_func`` parameters. """ #: The formatter class to create with :meth:`make_formatter`. #: #: .. versionadded:: 8.0 formatter_class: type[HelpFormatter] = HelpFormatter def __init__( self, command: Command, parent: Context | None = None, info_name: str | None = None, obj: t.Any | None = None, auto_envvar_prefix: str | None = None, default_map: cabc.MutableMapping[str, t.Any] | None = None, terminal_width: int | None = None, max_content_width: int | None = None, resilient_parsing: bool = False, allow_extra_args: bool | None = None, allow_interspersed_args: bool | None = None, ignore_unknown_options: bool | None = None, help_option_names: list[str] | None = None, token_normalize_func: t.Callable[[str], str] | None = None, color: bool | None = None, show_default: bool | None = None, ) -> None: #: the parent context or `None` if none exists. self.parent = parent #: the :class:`Command` for this context. self.command = command #: the descriptive information name self.info_name = info_name #: Map of parameter names to their parsed values. Parameters #: with ``expose_value=False`` are not stored. self.params: dict[str, t.Any] = {} #: the leftover arguments. self.args: list[str] = [] #: protected arguments. These are arguments that are prepended #: to `args` when certain parsing scenarios are encountered but #: must be never propagated to another arguments. This is used #: to implement nested parsing. self._protected_args: list[str] = [] #: the collected prefixes of the command's options. self._opt_prefixes: set[str] = set(parent._opt_prefixes) if parent else set() if obj is None and parent is not None: obj = parent.obj #: the user object stored. self.obj: t.Any = obj self._meta: dict[str, t.Any] = getattr(parent, "meta", {}) #: A dictionary (-like object) with defaults for parameters. if ( default_map is None and info_name is not None and parent is not None and parent.default_map is not None ): default_map = parent.default_map.get(info_name) self.default_map: cabc.MutableMapping[str, t.Any] | None = default_map #: This flag indicates if a subcommand is going to be executed. A #: group callback can use this information to figure out if it's #: being executed directly or because the execution flow passes #: onwards to a subcommand. By default it's None, but it can be #: the name of the subcommand to execute. #: #: If chaining is enabled this will be set to ``'*'`` in case #: any commands are executed. It is however not possible to #: figure out which ones. If you require this knowledge you #: should use a :func:`result_callback`. self.invoked_subcommand: str | None = None if terminal_width is None and parent is not None: terminal_width = parent.terminal_width #: The width of the terminal (None is autodetection). self.terminal_width: int | None = terminal_width if max_content_width is None and parent is not None: max_content_width = parent.max_content_width #: The maximum width of formatted content (None implies a sensible #: default which is 80 for most things). self.max_content_width: int | None = max_content_width if allow_extra_args is None: allow_extra_args = command.allow_extra_args #: Indicates if the context allows extra args or if it should #: fail on parsing. #: #: .. versionadded:: 3.0 self.allow_extra_args = allow_extra_args if allow_interspersed_args is None: allow_interspersed_args = command.allow_interspersed_args #: Indicates if the context allows mixing of arguments and #: options or not. #: #: .. versionadded:: 3.0 self.allow_interspersed_args: bool = allow_interspersed_args if ignore_unknown_options is None: ignore_unknown_options = command.ignore_unknown_options #: Instructs click to ignore options that a command does not #: understand and will store it on the context for later #: processing. This is primarily useful for situations where you #: want to call into external programs. Generally this pattern is #: strongly discouraged because it's not possibly to losslessly #: forward all arguments. #: #: .. versionadded:: 4.0 self.ignore_unknown_options: bool = ignore_unknown_options if help_option_names is None: if parent is not None: help_option_names = parent.help_option_names else: help_option_names = ["--help"] #: The names for the help options. self.help_option_names: list[str] = help_option_names if token_normalize_func is None and parent is not None: token_normalize_func = parent.token_normalize_func #: An optional normalization function for tokens. This is #: options, choices, commands etc. self.token_normalize_func: t.Callable[[str], str] | None = token_normalize_func #: Indicates if resilient parsing is enabled. In that case Click #: will do its best to not cause any failures and default values #: will be ignored. Useful for completion. self.resilient_parsing: bool = resilient_parsing # If there is no envvar prefix yet, but the parent has one and # the command on this level has a name, we can expand the envvar # prefix automatically. if auto_envvar_prefix is None: if ( parent is not None and parent.auto_envvar_prefix is not None and self.info_name is not None ): auto_envvar_prefix = ( f"{parent.auto_envvar_prefix}_{self.info_name.upper()}" ) else: auto_envvar_prefix = auto_envvar_prefix.upper() if auto_envvar_prefix is not None: auto_envvar_prefix = auto_envvar_prefix.replace("-", "_") self.auto_envvar_prefix: str | None = auto_envvar_prefix if color is None and parent is not None: color = parent.color #: Controls if styling output is wanted or not. self.color: bool | None = color if show_default is None and parent is not None: show_default = parent.show_default #: Show option default values when formatting help text. self.show_default: bool | None = show_default self._close_callbacks: list[t.Callable[[], t.Any]] = [] self._depth = 0 self._parameter_source: dict[str, ParameterSource] = {} self._exit_stack = AsyncExitStack() @property def protected_args(self) -> list[str]: import warnings warnings.warn( "'protected_args' is deprecated and will be removed in Click 9.0." " 'args' will contain remaining unparsed tokens.", DeprecationWarning, stacklevel=2, ) return self._protected_args async def to_info_dict(self) -> dict[str, t.Any]: """Gather information that could be useful for a tool generating user-facing documentation. This traverses the entire CLI structure. .. code-block:: python with Context(cli) as ctx: info = ctx.to_info_dict() .. versionadded:: 8.0 """ return { "command": await self.command.to_info_dict(self), "info_name": self.info_name, "allow_extra_args": self.allow_extra_args, "allow_interspersed_args": self.allow_interspersed_args, "ignore_unknown_options": self.ignore_unknown_options, "auto_envvar_prefix": self.auto_envvar_prefix, } async def __aenter__(self) -> Context: self._depth += 1 push_context(self) return self async def __aexit__( self, exc_type: type[BaseException] | None, exc_value: BaseException | None, tb: TracebackType | None, ) -> bool | None: self._depth -= 1 exit_result: bool | None = None if self._depth == 0: exit_result = await self._aclose_with_exception_info( exc_type, exc_value, tb ) pop_context() return exit_result @asynccontextmanager async def scope(self, cleanup: bool = True) -> t.AsyncIterator[Context]: """This helper method can be used with the context object to promote it to the current thread local (see :func:`get_current_context`). The default behavior of this is to invoke the cleanup functions which can be disabled by setting `cleanup` to `False`. The cleanup functions are typically used for things such as closing file handles. If the cleanup is intended the context object can also be directly used as a context manager. Example usage:: async with ctx.scope(): assert get_current_context() is ctx This is equivalent:: async with ctx: assert get_current_context() is ctx .. versionadded:: 5.0 :param cleanup: controls if the cleanup functions should be run or not. The default is to run these functions. In some situations the context only wants to be temporarily pushed in which case this can be disabled. Nested pushes automatically defer the cleanup. """ if not cleanup: self._depth += 1 try: async with self as rv: yield rv finally: if not cleanup: self._depth -= 1 @property def meta(self) -> dict[str, t.Any]: """This is a dictionary which is shared with all the contexts that are nested. It exists so that click utilities can store some state here if they need to. It is however the responsibility of that code to manage this dictionary well. The keys are supposed to be unique dotted strings. For instance module paths are a good choice for it. What is stored in there is irrelevant for the operation of click. However what is important is that code that places data here adheres to the general semantics of the system. Example usage:: LANG_KEY = f'{__name__}.lang' def set_language(value): ctx = get_current_context() ctx.meta[LANG_KEY] = value def get_language(): return get_current_context().meta.get(LANG_KEY, 'en_US') .. versionadded:: 5.0 """ return self._meta def make_formatter(self) -> HelpFormatter: """Creates the :class:`~click.HelpFormatter` for the help and usage output. To quickly customize the formatter class used without overriding this method, set the :attr:`formatter_class` attribute. .. versionchanged:: 8.0 Added the :attr:`formatter_class` attribute. """ return self.formatter_class( width=self.terminal_width, max_width=self.max_content_width ) def with_resource(self, context_manager: AbstractContextManager[V]) -> V: """Register a resource as if it were used in a ``with`` statement. The resource will be cleaned up when the context is popped. Uses :meth:`contextlib.AsyncExitStack.enter_context`. It calls the resource's ``__enter__()`` method and returns the result. When the context is popped, it closes the stack, which calls the resource's ``__exit__()`` method. To register a cleanup function for something that isn't a context manager, use :meth:`call_on_close`. Or use something from :mod:`contextlib` to turn it into a context manager first. .. code-block:: python @click.group() @click.option("--name") @click.pass_context def cli(ctx): ctx.obj = ctx.with_resource(connect_db(name)) :param context_manager: The context manager to enter. :return: Whatever ``context_manager.__enter__()`` returns. .. versionadded:: 8.0 """ return self._exit_stack.enter_context(context_manager) def with_async_resource( self, context_manager: t.AsyncContextManager[V] ) -> t.Awaitable[V]: """Register a resource as if it were used in an ``async with`` statement. The resource will be cleaned up when the context is popped. Uses :meth:`contextlib.AsyncExitStack.enter_async_context`. It calls the resource's ``__aenter__()`` method and returns the result. When the context is popped, it closes the stack, which calls the resource's ``__aexit__()`` method. To register a cleanup function for something that isn't a context manager, use :meth:`call_on_close`. Or use something from :mod:`contextlib` to turn it into a context manager first. .. code-block:: python @click.group() @click.option("--name") @click.pass_context def cli(ctx): ctx.obj = ctx.with_resource(connect_db(name)) :param context_manager: The context manager to enter. :return: Whatever ``context_manager.__aenter__()`` returns. .. versionadded:: 8.0 """ return self._exit_stack.enter_async_context(context_manager) def call_on_close(self, f: t.Callable[..., t.Any]) -> t.Callable[..., t.Any]: """Register a function to be called when the context tears down. This can be used to close resources opened during the script execution. Resources that support Python's context manager protocol which would be used in a ``with`` statement should be registered with :meth:`with_resource` instead. :param f: The function to execute on teardown. """ async def _f() -> Any: res = f() if iscoroutine(res): res = await res return res return self._exit_stack.push_async_callback(_f) async def aclose(self) -> None: """Invoke all close callbacks registered with :meth:`call_on_close`, and exit all context managers entered with :meth:`with_resource`. """ await self._exit_stack.aclose() await self._aclose_with_exception_info(None, None, None) async def _aclose_with_exception_info( self, exc_type: type[BaseException] | None, exc_value: BaseException | None, tb: TracebackType | None, ) -> bool | None: """Unwind the exit stack by calling its :meth:`__exit__` providing the exception information to allow for exception handling by the various resources registered using :meth;`with_resource` :return: Whatever ``exit_stack.__exit__()`` returns. """ exit_result = await t.cast( t.AsyncContextManager[t.Any], self._exit_stack ).__aexit__(exc_type, exc_value, tb) # In case the context is reused, create a new exit stack. self._exit_stack = AsyncExitStack() return exit_result @property def command_path(self) -> str: """The computed command path. This is used for the ``usage`` information on the help page. It's automatically created by combining the info names of the chain of contexts to the root. """ rv = "" if self.info_name is not None: rv = self.info_name if self.parent is not None: parent_command_path = [self.parent.command_path] if isinstance(self.parent.command, Command): for param in self.parent.command.get_params(self): parent_command_path.extend(param.get_usage_pieces(self)) rv = f"{' '.join(parent_command_path)} {rv}" return rv.lstrip() def find_root(self) -> Context: """Finds the outermost context.""" node = self while node.parent is not None: node = node.parent return node def find_object(self, object_type: type[V]) -> V | None: """Finds the closest object of a given type.""" node: Context | None = self while node is not None: if isinstance(node.obj, object_type): return node.obj node = node.parent return None def ensure_object(self, object_type: type[V]) -> V: """Like :meth:`find_object` but sets the innermost object to a new instance of `object_type` if it does not exist. """ rv = self.find_object(object_type) if rv is None: self.obj = rv = object_type() return rv @t.overload def lookup_default( self, name: str, call: t.Literal[True] = True ) -> t.Any | None: ... @t.overload def lookup_default( self, name: str, call: t.Literal[False] = ... ) -> t.Any | t.Callable[[], t.Any] | None: ... def lookup_default(self, name: str, call: bool = True) -> t.Any | None: """Get the default for a parameter from :attr:`default_map`. :param name: Name of the parameter. :param call: If the default is a callable, call it. Disable to return the callable instead. .. versionchanged:: 8.0 Added the ``call`` parameter. """ if self.default_map is not None: value = self.default_map.get(name, UNSET) if call and callable(value): return value() return value return UNSET def fail(self, message: str) -> t.NoReturn: """Aborts the execution of the program with a specific error message. :param message: the error message to fail with. """ raise UsageError(message, self) def abort(self) -> t.NoReturn: """Aborts the script.""" raise Abort() async def aexit(self, code: int = 0) -> t.NoReturn: """Exits the application with a given exit code. .. versionchanged:: 8.2 Callbacks and context managers registered with :meth:`call_on_close` and :meth:`with_resource` are closed before exiting. """ await self.aclose() raise Exit(code) def get_usage(self) -> str: """Helper method to get formatted usage string for the current context and command. """ return self.command.get_usage(self) def get_help(self) -> str: """Helper method to get formatted help page for the current context and command. """ return self.command.get_help(self) def _make_sub_context(self, command: Command) -> Context: """Create a new context of the same type as this context, but for a new command. :meta private: """ return type(self)(command, info_name=command.name, parent=self) @t.overload async def invoke( self, callback: t.Callable[..., V | Awaitable[V]], /, *args: t.Any, **kwargs: t.Any, ) -> V: ... @t.overload async def invoke( self, callback: Command, /, *args: t.Any, **kwargs: t.Any ) -> t.Any: ... async def invoke( self, callback: Command | t.Callable[..., V | Awaitable[V]], /, *args: t.Any, **kwargs: t.Any, ) -> t.Any | V: """Invokes a command callback in exactly the way it expects. There are two ways to invoke this method: 1. the first argument can be a callback and all other arguments and keyword arguments are forwarded directly to the function. 2. the first argument is a click command object. In that case all arguments are forwarded as well but proper click parameters (options and click arguments) must be keyword arguments and Click will fill in defaults. .. versionchanged:: 8.0 All ``kwargs`` are tracked in :attr:`params` so they will be passed if :meth:`forward` is called at multiple levels. .. versionchanged:: 3.2 A new context is created, and missing arguments use default values. """ if isinstance(callback, Command): other_cmd = callback if other_cmd.callback is None: raise TypeError( "The given command does not have a callback that can be invoked." ) else: callback = t.cast("t.Callable[..., V]", other_cmd.callback) ctx = self._make_sub_context(other_cmd) for param in other_cmd.params: if param.name not in kwargs and param.expose_value: kwargs[param.name] = param.type_cast_value( # type: ignore ctx, param.get_default(ctx) ) # Track all kwargs as params, so that forward() will pass # them on in subsequent calls. ctx.params.update(kwargs) else: ctx = self with augment_usage_errors(self): async with ctx: rv = callback(*args, **kwargs) if iscoroutine(rv): rv = await rv return rv async def forward(self, cmd: Command, /, *args: t.Any, **kwargs: t.Any) -> t.Any: """Similar to :meth:`invoke` but fills in default keyword arguments from the current context if the other command expects it. This cannot invoke callbacks directly, only other commands. .. versionchanged:: 8.0 All ``kwargs`` are tracked in :attr:`params` so they will be passed if ``forward`` is called at multiple levels. """ # Can only forward to other commands, not direct callbacks. if not isinstance(cmd, Command): raise TypeError("Callback is not a command.") for param in self.params: if param not in kwargs: kwargs[param] = self.params[param] return await self.invoke(cmd, *args, **kwargs) def set_parameter_source(self, name: str, source: ParameterSource) -> None: """Set the source of a parameter. This indicates the location from which the value of the parameter was obtained. :param name: The name of the parameter. :param source: A member of :class:`~click.core.ParameterSource`. """ self._parameter_source[name] = source def get_parameter_source(self, name: str) -> ParameterSource | None: """Get the source of a parameter. This indicates the location from which the value of the parameter was obtained. This can be useful for determining when a user specified a value on the command line that is the same as the default value. It will be :attr:`~click.core.ParameterSource.DEFAULT` only if the value was actually taken from the default. :param name: The name of the parameter. :rtype: ParameterSource .. versionchanged:: 8.0 Returns ``None`` if the parameter was not provided from any source. """ return self._parameter_source.get(name) class Command: """Commands are the basic building block of command line interfaces in Click. A basic command handles command line parsing and might dispatch more parsing to commands nested below it. :param name: the name of the command to use unless a group overrides it. :param context_settings: an optional dictionary with defaults that are passed to the context object. :param callback: the callback to invoke. This is optional. :param params: the parameters to register with this command. This can be either :class:`Option` or :class:`Argument` objects. :param help: the help string to use for this command. :param epilog: like the help string but it's printed at the end of the help page after everything else. :param short_help: the short help to use for this command. This is shown on the command listing of the parent command. :param add_help_option: by default each command registers a ``--help`` option. This can be disabled by this parameter. :param no_args_is_help: this controls what happens if no arguments are provided. This option is disabled by default. If enabled this will add ``--help`` as argument if no arguments are passed :param hidden: hide this command from help outputs. :param deprecated: If ``True`` or non-empty string, issues a message indicating that the command is deprecated and highlights its deprecation in --help. The message can be customized by using a string as the value. .. versionchanged:: 8.2 This is the base class for all commands, not ``BaseCommand``. ``deprecated`` can be set to a string as well to customize the deprecation message. .. versionchanged:: 8.1 ``help``, ``epilog``, and ``short_help`` are stored unprocessed, all formatting is done when outputting help text, not at init, and is done even if not using the ``@command`` decorator. .. versionchanged:: 8.0 Added a ``repr`` showing the command name. .. versionchanged:: 7.1 Added the ``no_args_is_help`` parameter. .. versionchanged:: 2.0 Added the ``context_settings`` parameter. """ #: The context class to create with :meth:`make_context`. #: #: .. versionadded:: 8.0 context_class: type[Context] = Context #: the default for the :attr:`Context.allow_extra_args` flag. allow_extra_args = False #: the default for the :attr:`Context.allow_interspersed_args` flag. allow_interspersed_args = True #: the default for the :attr:`Context.ignore_unknown_options` flag. ignore_unknown_options = False def __init__( self, name: str | None, context_settings: cabc.MutableMapping[str, t.Any] | None = None, callback: t.Callable[..., t.Any] | None = None, params: list[Parameter] | None = None, help: str | None = None, epilog: str | None = None, short_help: str | None = None, options_metavar: str | None = "[OPTIONS]", add_help_option: bool = True, no_args_is_help: bool = False, hidden: bool = False, deprecated: bool | str = False, ) -> None: #: the name the command thinks it has. Upon registering a command #: on a :class:`Group` the group will default the command name #: with this information. You should instead use the #: :class:`Context`\'s :attr:`~Context.info_name` attribute. self.name = name if context_settings is None: context_settings = {} #: an optional dictionary with defaults passed to the context. self.context_settings: cabc.MutableMapping[str, t.Any] = context_settings #: the callback to execute when the command fires. This might be #: `None` in which case nothing happens. self.callback = callback #: the list of parameters for this command in the order they #: should show up in the help page and execute. Eager parameters #: will automatically be handled before non eager ones. self.params: list[Parameter] = params or [] self.help = help self.epilog = epilog self.options_metavar = options_metavar self.short_help = short_help self.add_help_option = add_help_option self._help_option = None self.no_args_is_help = no_args_is_help self.hidden = hidden self.deprecated = deprecated async def to_info_dict(self, ctx: Context) -> dict[str, t.Any]: return { "name": self.name, "params": [await param.to_info_dict() for param in self.get_params(ctx)], "help": self.help, "epilog": self.epilog, "short_help": self.short_help, "hidden": self.hidden, "deprecated": self.deprecated, } def __repr__(self) -> str: return f"<{self.__class__.__name__} {self.name}>" def get_usage(self, ctx: Context) -> str: """Formats the usage line into a string and returns it. Calls :meth:`format_usage` internally. """ formatter = ctx.make_formatter() self.format_usage(ctx, formatter) return formatter.getvalue().rstrip("\n") def get_params(self, ctx: Context) -> list[Parameter]: params = self.params help_option = self.get_help_option(ctx) if help_option is not None: params = [*params, help_option] if __debug__: import warnings opts = [opt for param in params for opt in param.opts] opts_counter = Counter(opts) duplicate_opts = (opt for opt, count in opts_counter.items() if count > 1) for duplicate_opt in duplicate_opts: warnings.warn( ( f"The parameter {duplicate_opt} is used more than once. " "Remove its duplicate as parameters should be unique." ), stacklevel=3, ) return params def format_usage(self, ctx: Context, formatter: HelpFormatter) -> None: """Writes the usage line into the formatter. This is a low-level method called by :meth:`get_usage`. """ pieces = self.collect_usage_pieces(ctx) formatter.write_usage(ctx.command_path, " ".join(pieces)) def collect_usage_pieces(self, ctx: Context) -> list[str]: """Returns all the pieces that go into the usage line and returns it as a list of strings. """ rv = [self.options_metavar] if self.options_metavar else [] for param in self.get_params(ctx): rv.extend(param.get_usage_pieces(ctx)) return rv def get_help_option_names(self, ctx: Context) -> list[str]: """Returns the names for the help option.""" all_names = set(ctx.help_option_names) for param in self.params: all_names.difference_update(param.opts) all_names.difference_update(param.secondary_opts) return list(all_names) def get_help_option(self, ctx: Context) -> Option | None: """Returns the help option object. Skipped if :attr:`add_help_option` is ``False``. .. versionchanged:: 8.1.8 The help option is now cached to avoid creating it multiple times. """ help_option_names = self.get_help_option_names(ctx) if not help_option_names or not self.add_help_option: return None # Cache the help option object in private _help_option attribute to # avoid creating it multiple times. Not doing this will break the # callback odering by iter_params_for_processing(), which relies on # object comparison. if self._help_option is None: # Avoid circular import. from .decorators import help_option # Apply help_option decorator and pop resulting option help_option(*help_option_names)(self) self._help_option = self.params.pop() # type: ignore[assignment] return self._help_option def make_parser(self, ctx: Context) -> _OptionParser: """Creates the underlying option parser for this command.""" parser = _OptionParser(ctx) for param in self.get_params(ctx): param.add_to_parser(parser, ctx) return parser def get_help(self, ctx: Context) -> str: """Formats the help into a string and returns it. Calls :meth:`format_help` internally. """ formatter = ctx.make_formatter() self.format_help(ctx, formatter) return formatter.getvalue().rstrip("\n") def get_short_help_str(self, limit: int = 45) -> str: """Gets short help for the command or makes it by shortening the long help string. """ if self.short_help: text = inspect.cleandoc(self.short_help) elif self.help: text = make_default_short_help(self.help, limit) else: text = "" if self.deprecated: deprecated_message = ( f"(DEPRECATED: {self.deprecated})" if isinstance(self.deprecated, str) else "(DEPRECATED)" ) text = _("{text} {deprecated_message}").format( text=text, deprecated_message=deprecated_message ) return text.strip() def format_help(self, ctx: Context, formatter: HelpFormatter) -> None: """Writes the help into the formatter if it exists. This is a low-level method called by :meth:`get_help`. This calls the following methods: - :meth:`format_usage` - :meth:`format_help_text` - :meth:`format_options` - :meth:`format_epilog` """ self.format_usage(ctx, formatter) self.format_help_text(ctx, formatter) self.format_options(ctx, formatter) self.format_epilog(ctx, formatter) def format_help_text(self, ctx: Context, formatter: HelpFormatter) -> None: """Writes the help text to the formatter if it exists.""" if self.help is not None: # truncate the help text to the first form feed text = inspect.cleandoc(self.help).partition("\f")[0] else: text = "" if self.deprecated: deprecated_message = ( f"(DEPRECATED: {self.deprecated})" if isinstance(self.deprecated, str) else "(DEPRECATED)" ) text = _("{text} {deprecated_message}").format( text=text, deprecated_message=deprecated_message ) if text: formatter.write_paragraph() with formatter.indentation(): formatter.write_text(text) def format_options(self, ctx: Context, formatter: HelpFormatter) -> None: """Writes all the options into the formatter if they exist.""" opts = [] for param in self.get_params(ctx): rv = param.get_help_record(ctx) if rv is not None: opts.append(rv) if opts: with formatter.section(_("Options")): formatter.write_dl(opts) def format_epilog(self, ctx: Context, formatter: HelpFormatter) -> None: """Writes the epilog into the formatter if it exists.""" if self.epilog: epilog = inspect.cleandoc(self.epilog) formatter.write_paragraph() with formatter.indentation(): formatter.write_text(epilog) async def make_context( self, info_name: str | None, args: list[str], parent: Context | None = None, **extra: t.Any, ) -> Context: """This function when given an info name and arguments will kick off the parsing and create a new :class:`Context`. It does not invoke the actual command callback though. To quickly customize the context class used without overriding this method, set the :attr:`context_class` attribute. :param info_name: the info name for this invocation. Generally this is the most descriptive name for the script or command. For the toplevel script it's usually the name of the script, for commands below it's the name of the command. :param args: the arguments to parse as list of strings. :param parent: the parent context if available. :param extra: extra keyword arguments forwarded to the context constructor. .. versionchanged:: 8.0 Added the :attr:`context_class` attribute. """ for key, value in self.context_settings.items(): if key not in extra: extra[key] = value ctx = self.context_class(self, info_name=info_name, parent=parent, **extra) async with ctx.scope(cleanup=False): await self.parse_args(ctx, args) return ctx async def parse_args(self, ctx: Context, args: list[str]) -> list[str]: if not args and self.no_args_is_help and not ctx.resilient_parsing: raise NoArgsIsHelpError(ctx) parser = self.make_parser(ctx) opts, args, param_order = await parser.parse_args(args=args) for param in iter_params_for_processing(param_order, self.get_params(ctx)): _, args = await param.handle_parse_result(ctx, opts, args) if args and not ctx.allow_extra_args and not ctx.resilient_parsing: ctx.fail( ngettext( "Got unexpected extra argument ({args})", "Got unexpected extra arguments ({args})", len(args), ).format(args=" ".join(map(str, args))) ) ctx.args = args ctx._opt_prefixes.update(parser._opt_prefixes) return args async def invoke(self, ctx: Context) -> t.Any: """Given a context, this invokes the attached callback (if it exists) in the right way. """ if self.deprecated: extra_message = ( f" {self.deprecated}" if isinstance(self.deprecated, str) else "" ) message = _( "DeprecationWarning: The command {name!r} is deprecated.{extra_message}" ).format(name=self.name, extra_message=extra_message) echo(style(message, fg="red"), err=True) if self.callback is not None: return await ctx.invoke(self.callback, **ctx.params) def shell_complete(self, ctx: Context, incomplete: str) -> list[CompletionItem]: """Return a list of completions for the incomplete value. Looks at the names of options and chained multi-commands. Any command could be part of a chained multi-command, so sibling commands are valid at any point during command completion. :param ctx: Invocation context for this command. :param incomplete: Value being completed. May be empty. .. versionadded:: 8.0 """ from .shell_completion import CompletionItem results: list[CompletionItem] = [] if incomplete and not incomplete[0].isalnum(): for param in self.get_params(ctx): if ( not isinstance(param, Option) or param.hidden or ( not param.multiple and ctx.get_parameter_source(param.name) # type: ignore is ParameterSource.COMMANDLINE ) ): continue results.extend( CompletionItem(name, help=param.help) for name in [*param.opts, *param.secondary_opts] if name.startswith(incomplete) ) while ctx.parent is not None: ctx = ctx.parent if isinstance(ctx.command, Group) and ctx.command.chain: results.extend( CompletionItem(name, help=command.get_short_help_str()) for name, command in _complete_visible_commands(ctx, incomplete) if name not in ctx._protected_args ) return results @t.overload async def main( self, args: cabc.Sequence[str] | None = None, prog_name: str | None = None, complete_var: str | None = None, standalone_mode: t.Literal[True] = True, **extra: t.Any, ) -> t.NoReturn: ... @t.overload async def main( self, args: cabc.Sequence[str] | None = None, prog_name: str | None = None, complete_var: str | None = None, standalone_mode: bool = ..., **extra: t.Any, ) -> t.Any: ... async def main( self, args: cabc.Sequence[str] | None = None, prog_name: str | None = None, complete_var: str | None = None, standalone_mode: bool = True, windows_expand_args: bool = True, **extra: t.Any, ) -> t.Any: """This is the way to invoke a script with all the bells and whistles as a command line application. This will always terminate the application after a call. If this is not wanted, ``SystemExit`` needs to be caught. This method is also available by directly calling the instance of a :class:`Command`. :param args: the arguments that should be used for parsing. If not provided, ``sys.argv[1:]`` is used. :param prog_name: the program name that should be used. By default the program name is constructed by taking the file name from ``sys.argv[0]``. :param complete_var: the environment variable that controls the bash completion support. The default is ``"__COMPLETE"`` with prog_name in uppercase. :param standalone_mode: the default behavior is to invoke the script in standalone mode. Click will then handle exceptions and convert them into error messages and the function will never return but shut down the interpreter. If this is set to `False` they will be propagated to the caller and the return value of this function is the return value of :meth:`invoke`. :param windows_expand_args: Expand glob patterns, user dir, and env vars in command line args on Windows. :param extra: extra keyword arguments are forwarded to the context constructor. See :class:`Context` for more information. .. versionchanged:: 8.0.1 Added the ``windows_expand_args`` parameter to allow disabling command line arg expansion on Windows. .. versionchanged:: 8.0 When taking arguments from ``sys.argv`` on Windows, glob patterns, user dir, and env vars are expanded. .. versionchanged:: 3.0 Added the ``standalone_mode`` parameter. """ if args is None: args = sys.argv[1:] if os.name == "nt" and windows_expand_args: args = _expand_args(args) else: args = list(args) if prog_name is None: prog_name = _detect_program_name() # Process shell completion requests and exit early. await self._main_shell_completion(extra, prog_name, complete_var) try: try: async with await self.make_context(prog_name, args, **extra) as ctx: rv = await self.invoke(ctx) if not standalone_mode: return rv # it's not safe to `ctx.aexit(rv)` here! # note that `rv` may actually contain data like "1" which # has obvious effects # more subtle case: `rv=[None, None]` can come out of # chained commands which all returned `None` -- so it's not # even always obvious that `rv` indicates success/failure # by its truthiness/falsiness await ctx.aexit() except (EOFError, KeyboardInterrupt) as e: echo(file=sys.stderr) raise Abort() from e except ClickException as e: if not standalone_mode: raise e.show() sys.exit(e.exit_code) except OSError as e: if e.errno == errno.EPIPE: sys.stdout = t.cast(t.TextIO, PacifyFlushWrapper(sys.stdout)) sys.stderr = t.cast(t.TextIO, PacifyFlushWrapper(sys.stderr)) sys.exit(1) else: raise except Exit as e: if standalone_mode: sys.exit(e.exit_code) else: # in non-standalone mode, return the exit code # note that this is only reached if `self.invoke` above raises # an Exit explicitly -- thus bypassing the check there which # would return its result # the results of non-standalone execution may therefore be # somewhat ambiguous: if there are codepaths which lead to # `ctx.aexit(1)` and to `return 1`, the caller won't be able to # tell the difference between the two return e.exit_code except Abort: if not standalone_mode: raise echo(_("Aborted!"), file=sys.stderr) sys.exit(1) async def _main_shell_completion( self, ctx_args: cabc.MutableMapping[str, t.Any], prog_name: str, complete_var: str | None = None, ) -> None: """Check if the shell is asking for tab completion, process that, then exit early. Called from :meth:`main` before the program is invoked. :param prog_name: Name of the executable in the shell. :param complete_var: Name of the environment variable that holds the completion instruction. Defaults to ``_{PROG_NAME}_COMPLETE``. .. versionchanged:: 8.2.0 Dots (``.``) in ``prog_name`` are replaced with underscores (``_``). """ if complete_var is None: complete_name = prog_name.replace("-", "_").replace(".", "_") complete_var = f"_{complete_name}_COMPLETE".upper() instruction = os.environ.get(complete_var) if not instruction: return from .shell_completion import shell_complete rv = await shell_complete(self, ctx_args, prog_name, complete_var, instruction) sys.exit(rv) def __call__( self, *args: t.Any, _anyio_backend: str | None = None, _anyio_backend_options: dict[str, t.Any] | None = None, **kwargs: t.Any, ) -> t.Any: """Calling the command directly runs it in a new :mod:`anyio` event loop. If you are already inside an async event loop, call ``await`` :meth:`main` instead. :param _anyio_backend: The backend to use for the event loop. :param _anyio_backend_options: Any options to pass to the backend. The parameters are used as the ``backend`` and ``backend_options`` arguments to :func:`anyio.run`, respectively. """ main = self.main opts: dict[str, t.Any] = {} try: import anyio except ImportError: pass else: if _anyio_backend: opts["backend"] = _anyio_backend if _anyio_backend_options: opts["backend_options"] = _anyio_backend_options return anyio.run(self._main, main, args, kwargs, **opts) if _anyio_backend == "trio": import trio return trio.run(self._main, main, args, kwargs) if _anyio_backend == "asyncio": import asyncio return asyncio.run(self._main(main, args, kwargs)) raise RuntimeError(f"Backend {_anyio_backend!r} unknown") async def _main( self, main: t.Callable[..., t.Awaitable[t.Any]], args: t.Sequence[t.Any], kwargs: dict[str, t.Any], ) -> t.Any: return await main(*args, **kwargs) class _FakeSubclassCheck(type): def __subclasscheck__(cls, subclass: type) -> bool: return issubclass(subclass, cls.__bases__[0]) def __instancecheck__(cls, instance: t.Any) -> bool: return isinstance(instance, cls.__bases__[0]) class _BaseCommand(Command, metaclass=_FakeSubclassCheck): """ .. deprecated:: 8.2 Will be removed in Click 9.0. Use ``Command`` instead. """ class Group(Command): """A group is a command that nests other commands (or more groups). :param name: The name of the group command. :param commands: Map names to :class:`Command` objects. Can be a list, which will use :attr:`Command.name` as the keys. :param invoke_without_command: Invoke the group's callback even if a subcommand is not given. :param no_args_is_help: If no arguments are given, show the group's help and exit. Defaults to the opposite of ``invoke_without_command``. :param subcommand_metavar: How to represent the subcommand argument in help. The default will represent whether ``chain`` is set or not. :param chain: Allow passing more than one subcommand argument. After parsing a command's arguments, if any arguments remain another command will be matched, and so on. :param result_callback: A function to call after the group's and subcommand's callbacks. The value returned by the subcommand is passed. If ``chain`` is enabled, the value will be a list of values returned by all the commands. If ``invoke_without_command`` is enabled, the value will be the value returned by the group's callback, or an empty list if ``chain`` is enabled. :param kwargs: Other arguments passed to :class:`Command`. .. versionchanged:: 8.0 The ``commands`` argument can be a list of command objects. .. versionchanged:: 8.2 Merged with and replaces the ``MultiCommand`` base class. """ allow_extra_args = True allow_interspersed_args = False #: If set, this is used by the group's :meth:`command` decorator #: as the default :class:`Command` class. This is useful to make all #: subcommands use a custom command class. #: #: .. versionadded:: 8.0 command_class: type[Command] | None = None #: If set, this is used by the group's :meth:`group` decorator #: as the default :class:`Group` class. This is useful to make all #: subgroups use a custom group class. #: #: If set to the special value :class:`type` (literally #: ``group_class = type``), this group's class will be used as the #: default class. This makes a custom group class continue to make #: custom groups. #: #: .. versionadded:: 8.0 group_class: type[Group] | type[type] | None = None # Literal[type] isn't valid, so use Type[type] def __init__( self, name: str | None = None, commands: cabc.MutableMapping[str, Command] | cabc.Sequence[Command] | None = None, invoke_without_command: bool = False, no_args_is_help: bool | None = None, subcommand_metavar: str | None = None, chain: bool = False, result_callback: t.Callable[..., t.Any] | None = None, **kwargs: t.Any, ) -> None: super().__init__(name, **kwargs) if commands is None: commands = {} elif isinstance(commands, abc.Sequence): commands = {c.name: c for c in commands if c.name is not None} #: The registered subcommands by their exported names. self.commands: cabc.MutableMapping[str, Command] = commands if no_args_is_help is None: no_args_is_help = not invoke_without_command self.no_args_is_help = no_args_is_help self.invoke_without_command = invoke_without_command if subcommand_metavar is None: if chain: subcommand_metavar = "COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]..." else: subcommand_metavar = "COMMAND [ARGS]..." self.subcommand_metavar = subcommand_metavar self.chain = chain # The result callback that is stored. This can be set or # overridden with the :func:`result_callback` decorator. self._result_callback = result_callback if self.chain: for param in self.params: if isinstance(param, Argument) and not param.required: raise RuntimeError( "A group in chain mode cannot have optional arguments." ) async def to_info_dict(self, ctx: Context) -> dict[str, t.Any]: info_dict = await super().to_info_dict(ctx) commands = {} for name in self.list_commands(ctx): command = self.get_command(ctx, name) if command is None: continue sub_ctx = ctx._make_sub_context(command) async with sub_ctx.scope(cleanup=False): commands[name] = await command.to_info_dict(sub_ctx) info_dict.update(commands=commands, chain=self.chain) return info_dict def add_command(self, cmd: Command, name: str | None = None) -> None: """Registers another :class:`Command` with this group. If the name is not provided, the name of the command is used. """ name = name or cmd.name if name is None: raise TypeError("Command has no name.") _check_nested_chain(self, name, cmd, register=True) self.commands[name] = cmd @t.overload def command(self, __func: t.Callable[..., t.Any]) -> Command: ... @t.overload def command( self, *args: t.Any, **kwargs: t.Any ) -> t.Callable[[t.Callable[..., t.Any]], Command]: ... def command( self, *args: t.Any, **kwargs: t.Any ) -> t.Callable[[t.Callable[..., t.Any]], Command] | Command: """A shortcut decorator for declaring and attaching a command to the group. This takes the same arguments as :func:`command` and immediately registers the created command with this group by calling :meth:`add_command`. To customize the command class used, set the :attr:`command_class` attribute. .. versionchanged:: 8.1 This decorator can be applied without parentheses. .. versionchanged:: 8.0 Added the :attr:`command_class` attribute. """ from .decorators import command func: t.Callable[..., t.Any] | None = None if args and callable(args[0]): assert len(args) == 1 and not kwargs, ( "Use 'command(**kwargs)(callable)' to provide arguments." ) (func,) = args args = () if self.command_class and kwargs.get("cls") is None: kwargs["cls"] = self.command_class def decorator(f: t.Callable[..., t.Any]) -> Command: cmd: Command = command(*args, **kwargs)(f) self.add_command(cmd) return cmd if func is not None: return decorator(func) return decorator @t.overload def group(self, __func: t.Callable[..., t.Any]) -> Group: ... @t.overload def group( self, *args: t.Any, **kwargs: t.Any ) -> t.Callable[[t.Callable[..., t.Any]], Group]: ... def group( self, *args: t.Any, **kwargs: t.Any ) -> t.Callable[[t.Callable[..., t.Any]], Group] | Group: """A shortcut decorator for declaring and attaching a group to the group. This takes the same arguments as :func:`group` and immediately registers the created group with this group by calling :meth:`add_command`. To customize the group class used, set the :attr:`group_class` attribute. .. versionchanged:: 8.1 This decorator can be applied without parentheses. .. versionchanged:: 8.0 Added the :attr:`group_class` attribute. """ from .decorators import group func: t.Callable[..., t.Any] | None = None if args and callable(args[0]): assert len(args) == 1 and not kwargs, ( "Use 'group(**kwargs)(callable)' to provide arguments." ) (func,) = args args = () if self.group_class is not None and kwargs.get("cls") is None: if self.group_class is type: kwargs["cls"] = type(self) else: kwargs["cls"] = self.group_class def decorator(f: t.Callable[..., t.Any]) -> Group: cmd: Group = group(*args, **kwargs)(f) self.add_command(cmd) return cmd if func is not None: return decorator(func) return decorator def result_callback(self, replace: bool = False) -> t.Callable[[F], F]: """Adds a result callback to the command. By default if a result callback is already registered this will chain them but this can be disabled with the `replace` parameter. The result callback is invoked with the return value of the subcommand (or the list of return values from all subcommands if chaining is enabled) as well as the parameters as they would be passed to the main callback. Example:: @click.group() @click.option('-i', '--input', default=23) def cli(input): return 42 @cli.result_callback() def process_result(result, input): return result + input :param replace: if set to `True` an already existing result callback will be removed. .. versionchanged:: 8.0 Renamed from ``resultcallback``. .. versionadded:: 3.0 """ def decorator(f: F) -> F: old_callback = self._result_callback if old_callback is None or replace: self._result_callback = f return f def function(value: t.Any, /, *args: t.Any, **kwargs: t.Any) -> t.Any: inner = old_callback(value, *args, **kwargs) return f(inner, *args, **kwargs) self._result_callback = rv = update_wrapper(t.cast(F, function), f) return rv # type: ignore[return-value] return decorator def get_command(self, ctx: Context, cmd_name: str) -> Command | None: """Given a context and a command name, this returns a :class:`Command` object if it exists or returns ``None``. """ return self.commands.get(cmd_name) def list_commands(self, ctx: Context) -> list[str]: """Returns a list of subcommand names in the order they should appear.""" return sorted(self.commands) def collect_usage_pieces(self, ctx: Context) -> list[str]: rv = super().collect_usage_pieces(ctx) rv.append(self.subcommand_metavar) return rv def format_options(self, ctx: Context, formatter: HelpFormatter) -> None: super().format_options(ctx, formatter) self.format_commands(ctx, formatter) def format_commands(self, ctx: Context, formatter: HelpFormatter) -> None: """Extra format methods for multi methods that adds all the commands after the options. """ commands = [] for subcommand in self.list_commands(ctx): cmd = self.get_command(ctx, subcommand) # What is this, the tool lied about a command. Ignore it if cmd is None: continue if cmd.hidden: continue commands.append((subcommand, cmd)) # allow for 3 times the default spacing if len(commands): limit = formatter.width - 6 - max(len(cmd[0]) for cmd in commands) rows = [] for subcommand, cmd in commands: help = cmd.get_short_help_str(limit) rows.append((subcommand, help)) if rows: with formatter.section(_("Commands")): formatter.write_dl(rows) async def parse_args(self, ctx: Context, args: list[str]) -> list[str]: if not args and self.no_args_is_help and not ctx.resilient_parsing: raise NoArgsIsHelpError(ctx) rest = await super().parse_args(ctx, args) if self.chain: ctx._protected_args = rest ctx.args = [] elif rest: ctx._protected_args, ctx.args = rest[:1], rest[1:] return ctx.args async def invoke(self, ctx: Context) -> t.Any: async def _process_result(value: t.Any) -> t.Any: if self._result_callback is not None: value = await ctx.invoke(self._result_callback, value, **ctx.params) return value if not ctx._protected_args: if self.invoke_without_command: # No subcommand was invoked, so the result callback is # invoked with the group return value for regular # groups, or an empty list for chained groups. async with ctx: rv = await super().invoke(ctx) return await _process_result([] if self.chain else rv) ctx.fail(_("Missing command.")) # Fetch args back out args = [*ctx._protected_args, *ctx.args] ctx.args = [] ctx._protected_args = [] # If we're not in chain mode, we only allow the invocation of a # single command but we also inform the current context about the # name of the command to invoke. if not self.chain: # Make sure the context is entered so we do not clean up # resources until the result processor has worked. async with ctx: cmd_name, cmd, args = await self.resolve_command(ctx, args) assert cmd is not None ctx.invoked_subcommand = cmd_name await super().invoke(ctx) sub_ctx = await cmd.make_context(cmd_name, args, parent=ctx) async with sub_ctx: return await _process_result(await sub_ctx.command.invoke(sub_ctx)) # In chain mode we create the contexts step by step, but after the # base command has been invoked. Because at that point we do not # know the subcommands yet, the invoked subcommand attribute is # set to ``*`` to inform the command that subcommands are executed # but nothing else. async with ctx: ctx.invoked_subcommand = "*" if args else None await super().invoke(ctx) # Otherwise we make every single context and invoke them in a # chain. In that case the return value to the result processor # is the list of all invoked subcommand's results. contexts = [] while args: cmd_name, cmd, args = await self.resolve_command(ctx, args) assert cmd is not None sub_ctx = await cmd.make_context( cmd_name, args, parent=ctx, allow_extra_args=True, allow_interspersed_args=False, ) contexts.append(sub_ctx) args, sub_ctx.args = sub_ctx.args, [] rv = [] for sub_ctx in contexts: async with sub_ctx: rv.append(await sub_ctx.command.invoke(sub_ctx)) return await _process_result(rv) async def resolve_command( self, ctx: Context, args: list[str] ) -> tuple[str | None, Command | None, list[str]]: cmd_name = make_str(args[0]) original_cmd_name = cmd_name # Get the command cmd = self.get_command(ctx, cmd_name) # If we can't find the command but there is a normalization # function available, we try with that one. if cmd is None and ctx.token_normalize_func is not None: cmd_name = ctx.token_normalize_func(cmd_name) cmd = self.get_command(ctx, cmd_name) # If we don't find the command we want to show an error message # to the user that it was not provided. However, there is # something else we should do: if the first argument looks like # an option we want to kick off parsing again for arguments to # resolve things like --help which now should go to the main # place. if cmd is None and not ctx.resilient_parsing: if _split_opt(cmd_name)[0]: await self.parse_args(ctx, args) ctx.fail(_("No such command {name!r}.").format(name=original_cmd_name)) return cmd_name if cmd else None, cmd, args[1:] def shell_complete(self, ctx: Context, incomplete: str) -> list[CompletionItem]: """Return a list of completions for the incomplete value. Looks at the names of options, subcommands, and chained multi-commands. :param ctx: Invocation context for this command. :param incomplete: Value being completed. May be empty. .. versionadded:: 8.0 """ from .shell_completion import CompletionItem results = [ CompletionItem(name, help=command.get_short_help_str()) for name, command in _complete_visible_commands(ctx, incomplete) ] results.extend(super().shell_complete(ctx, incomplete)) return results class _MultiCommand(Group, metaclass=_FakeSubclassCheck): """ .. deprecated:: 8.2 Will be removed in Click 9.0. Use ``Group`` instead. """ class CommandCollection(Group): """A :class:`Group` that looks up subcommands on other groups. If a command is not found on this group, each registered source is checked in order. Parameters on a source are not added to this group, and a source's callback is not invoked when invoking its commands. In other words, this "flattens" commands in many groups into this one group. :param name: The name of the group command. :param sources: A list of :class:`Group` objects to look up commands from. :param kwargs: Other arguments passed to :class:`Group`. .. versionchanged:: 8.2 This is a subclass of ``Group``. Commands are looked up first on this group, then each of its sources. """ def __init__( self, name: str | None = None, sources: list[Group] | None = None, **kwargs: t.Any, ) -> None: super().__init__(name, **kwargs) #: The list of registered groups. self.sources: list[Group] = sources or [] def add_source(self, group: Group) -> None: """Add a group as a source of commands.""" self.sources.append(group) def get_command(self, ctx: Context, cmd_name: str) -> Command | None: rv = super().get_command(ctx, cmd_name) if rv is not None: return rv for source in self.sources: rv = source.get_command(ctx, cmd_name) if rv is not None: if self.chain: _check_nested_chain(self, cmd_name, rv) return rv return None def list_commands(self, ctx: Context) -> list[str]: rv: set[str] = set(super().list_commands(ctx)) for source in self.sources: rv.update(source.list_commands(ctx)) return sorted(rv) def _check_iter(value: t.Any) -> cabc.Iterator[t.Any]: """Check if the value is iterable but not a string. Raises a type error, or return an iterator over the value. """ if isinstance(value, str): raise TypeError return iter(value) class Parameter: r"""A parameter to a command comes in two versions: they are either :class:`Option`\s or :class:`Argument`\s. Other subclasses are currently not supported by design as some of the internals for parsing are intentionally not finalized. Some settings are supported by both options and arguments. :param param_decls: the parameter declarations for this option or argument. This is a list of flags or argument names. :param type: the type that should be used. Either a :class:`ParamType` or a Python type. The latter is converted into the former automatically if supported. :param required: controls if this is optional or not. :param default: the default value if omitted. This can also be a callable, in which case it's invoked when the default is needed without any arguments. :param callback: A function to further process or validate the value after type conversion. It is called as ``f(ctx, param, value)`` and must return the value. It is called for all sources, including prompts. :param nargs: the number of arguments to match. If not ``1`` the return value is a tuple instead of single value. The default for nargs is ``1`` (except if the type is a tuple, then it's the arity of the tuple). If ``nargs=-1``, all remaining parameters are collected. :param metavar: how the value is represented in the help page. :param expose_value: if this is `True` then the value is passed onwards to the command callback and stored on the context, otherwise it's skipped. :param is_eager: eager values are processed before non eager ones. This should not be set for arguments or it will inverse the order of processing. :param envvar: environment variable(s) that are used to provide a default value for this parameter. This can be a string or a sequence of strings. If a sequence is given, only the first non-empty environment variable is used for the parameter. :param shell_complete: A function that returns custom shell completions. Used instead of the param's type completion if given. Takes ``ctx, param, incomplete`` and must return a list of :class:`~click.shell_completion.CompletionItem` or a list of strings. :param deprecated: If ``True`` or non-empty string, issues a message indicating that the argument is deprecated and highlights its deprecation in --help. The message can be customized by using a string as the value. A deprecated parameter cannot be required, a ValueError will be raised otherwise. .. versionchanged:: 8.2.0 Introduction of ``deprecated``. .. versionchanged:: 8.2 Adding duplicate parameter names to a :class:`~click.core.Command` will result in a ``UserWarning`` being shown. .. versionchanged:: 8.2 Adding duplicate parameter names to a :class:`~click.core.Command` will result in a ``UserWarning`` being shown. .. versionchanged:: 8.0 ``process_value`` validates required parameters and bounded ``nargs``, and invokes the parameter callback before returning the value. This allows the callback to validate prompts. ``full_process_value`` is removed. .. versionchanged:: 8.0 ``autocompletion`` is renamed to ``shell_complete`` and has new semantics described above. The old name is deprecated and will be removed in 8.1, until then it will be wrapped to match the new requirements. .. versionchanged:: 8.0 For ``multiple=True, nargs>1``, the default must be a list of tuples. .. versionchanged:: 8.0 Setting a default is no longer required for ``nargs>1``, it will default to ``None``. ``multiple=True`` or ``nargs=-1`` will default to ``()``. .. versionchanged:: 7.1 Empty environment variables are ignored rather than taking the empty string value. This makes it possible for scripts to clear variables if they can't unset them. .. versionchanged:: 2.0 Changed signature for parameter callback to also be passed the parameter. The old callback format will still work, but it will raise a warning to give you a chance to migrate the code easier. """ param_type_name = "parameter" def __init__( self, param_decls: cabc.Sequence[str] | None = None, type: types.ParamType | t.Any | None = None, required: bool = False, # XXX The default historically embed two concepts: # - the declaration of a Parameter object carrying the default (handy to # arbitrage the default value of coupled Parameters sharing the same # self.name, like flag options), # - and the actual value of the default. # It is confusing and is the source of many issues discussed in: # https://github.com/pallets/click/pull/3030 # In the future, we might think of splitting it in two, not unlike # Option.is_flag and Option.flag_value: we could have something like # Parameter.is_default and Parameter.default_value. default: t.Any | t.Callable[[], t.Any] | None = UNSET, callback: t.Callable[[Context, Parameter, t.Any], t.Any] | None = None, nargs: int | None = None, multiple: bool = False, metavar: str | None = None, expose_value: bool = True, is_eager: bool = False, envvar: str | cabc.Sequence[str] | None = None, shell_complete: t.Callable[ [Context, Parameter, str], list[CompletionItem] | list[str] ] | None = None, deprecated: bool | str = False, ) -> None: self.name: str | None self.opts: list[str] self.secondary_opts: list[str] self.name, self.opts, self.secondary_opts = self._parse_decls( param_decls or (), expose_value ) self.type: types.ParamType = types.convert_type(type, default) # Default nargs to what the type tells us if we have that # information available. if nargs is None: if self.type.is_composite: nargs = self.type.arity else: nargs = 1 self.required = required self.callback = callback self.nargs = nargs self.multiple = multiple self.expose_value = expose_value self.default = default self.is_eager = is_eager self.metavar = metavar self.envvar = envvar self._custom_shell_complete = shell_complete self.deprecated = deprecated if __debug__: if self.type.is_composite and nargs != self.type.arity: raise ValueError( f"'nargs' must be {self.type.arity} (or None) for" f" type {self.type!r}, but it was {nargs}." ) if required and deprecated: raise ValueError( f"The {self.param_type_name} '{self.human_readable_name}' " "is deprecated and still required. A deprecated " f"{self.param_type_name} cannot be required." ) async def to_info_dict(self) -> dict[str, t.Any]: """Gather information that could be useful for a tool generating user-facing documentation. Use :meth:`click.Context.to_info_dict` to traverse the entire CLI structure. .. versionchanged:: 8.3.0 Returns ``None`` for the :attr:`default` if it was not set. .. versionadded:: 8.0 """ return { "name": self.name, "param_type_name": self.param_type_name, "opts": self.opts, "secondary_opts": self.secondary_opts, "type": await self.type.to_info_dict(), "required": self.required, "nargs": self.nargs, "multiple": self.multiple, # We explicitly hide the :attr:`UNSET` value to the user, as we choose to # make it an implementation detail. And because ``to_info_dict`` has been # designed for documentation purposes, we return ``None`` instead. "default": self.default if self.default is not UNSET else None, "envvar": self.envvar, } def __repr__(self) -> str: return f"<{self.__class__.__name__} {self.name}>" def _parse_decls( self, decls: cabc.Sequence[str], expose_value: bool ) -> tuple[str | None, list[str], list[str]]: raise NotImplementedError() @property def human_readable_name(self) -> str: """Returns the human readable name of this parameter. This is the same as the name for options, but the metavar for arguments. """ return self.name # type: ignore def make_metavar(self, ctx: Context) -> str: if self.metavar is not None: return self.metavar metavar = self.type.get_metavar(param=self, ctx=ctx) if metavar is None: metavar = self.type.name.upper() if self.nargs != 1: metavar += "..." return metavar @t.overload def get_default( self, ctx: Context, call: t.Literal[True] = True ) -> t.Any | None: ... @t.overload def get_default( self, ctx: Context, call: bool = ... ) -> t.Any | t.Callable[[], t.Any] | None: ... def get_default( self, ctx: Context, call: bool = True ) -> t.Any | t.Callable[[], t.Any] | None: """Get the default for the parameter. Tries :meth:`Context.lookup_default` first, then the local default. :param ctx: Current context. :param call: If the default is a callable, call it. Disable to return the callable instead. .. versionchanged:: 8.0.2 Type casting is no longer performed when getting a default. .. versionchanged:: 8.0.1 Type casting can fail in resilient parsing mode. Invalid defaults will not prevent showing help text. .. versionchanged:: 8.0 Looks at ``ctx.default_map`` first. .. versionchanged:: 8.0 Added the ``call`` parameter. """ value = ctx.lookup_default(self.name, call=False) # type: ignore if value is UNSET: value = self.default if call and callable(value): value = value() return value def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None: raise NotImplementedError() async def consume_value( self, ctx: Context, opts: cabc.Mapping[str, t.Any] ) -> tuple[t.Any, ParameterSource]: """Returns the parameter value produced by the parser. If the parser did not produce a value from user input, the value is either sourced from the environment variable, the default map, or the parameter's default value. In that order of precedence. If no value is found, an internal sentinel value is returned. :meta private: """ # Collect from the parse the value passed by the user to the CLI. value = opts.get(self.name, UNSET) # type: ignore # If the value is set, it means it was sourced from the command line by the # parser, otherwise it left unset by default. source = ( ParameterSource.COMMANDLINE if value is not UNSET else ParameterSource.DEFAULT ) if value is UNSET: envvar_value = self.value_from_envvar(ctx) if envvar_value is not None: value = envvar_value source = ParameterSource.ENVIRONMENT if value is UNSET: default_map_value = ctx.lookup_default(self.name) # type: ignore if default_map_value is not UNSET: value = default_map_value source = ParameterSource.DEFAULT_MAP if value is UNSET: default_value = self.get_default(ctx) if default_value is not UNSET: value = default_value source = ParameterSource.DEFAULT return value, source def type_cast_value(self, ctx: Context, value: t.Any) -> t.Any: """Convert and validate a value against the parameter's :attr:`type`, :attr:`multiple`, and :attr:`nargs`. """ if value in (None, UNSET): if self.multiple or self.nargs == -1: return () else: return value def check_iter(value: t.Any) -> cabc.Iterator[t.Any]: try: return _check_iter(value) except TypeError: # This should only happen when passing in args manually, # the parser should construct an iterable when parsing # the command line. raise BadParameter( _("Value must be an iterable."), ctx=ctx, param=self ) from None # Define the conversion function based on nargs and type. if self.nargs == 1 or self.type.is_composite: def convert(value: t.Any) -> t.Any: return self.type(value, param=self, ctx=ctx) elif self.nargs == -1: def convert(value: t.Any) -> t.Any: # tuple[t.Any, ...] return tuple(self.type(x, self, ctx) for x in check_iter(value)) else: # nargs > 1 def convert(value: t.Any) -> t.Any: # tuple[t.Any, ...] value = tuple(check_iter(value)) if len(value) != self.nargs: raise BadParameter( ngettext( "Takes {nargs} values but 1 was given.", "Takes {nargs} values but {len} were given.", len(value), ).format(nargs=self.nargs, len=len(value)), ctx=ctx, param=self, ) return tuple(self.type(x, self, ctx) for x in value) if self.multiple: return tuple(convert(x) for x in check_iter(value)) return convert(value) def value_is_missing(self, value: t.Any) -> bool: """A value is considered missing if: - it is :attr:`UNSET`, - or if it is an empty sequence while the parameter is suppose to have non-single value (i.e. :attr:`nargs` is not ``1`` or :attr:`multiple` is set). :meta private: """ if value is UNSET: return True if (self.nargs != 1 or self.multiple) and value == (): return True return False async def process_value(self, ctx: Context, value: t.Any) -> t.Any: """Process the value of this parameter: 1. Type cast the value using :meth:`type_cast_value`. 2. Check if the value is missing (see: :meth:`value_is_missing`), and raise :exc:`MissingParameter` if it is required. 3. If a :attr:`callback` is set, call it to have the value replaced by the result of the callback. If the value was not set, the callback receive ``None``. This keep the legacy behavior as it was before the introduction of the :attr:`UNSET` sentinel. :meta private: """ value = self.type_cast_value(ctx, value) if self.required and self.value_is_missing(value): raise MissingParameter(ctx=ctx, param=self) if self.callback is not None: # Legacy case: UNSET is not exposed directly to the callback, but converted # to None. if value is UNSET: value = None value = self.callback(ctx, self, value) if iscoroutine(value): value = await value return value def resolve_envvar_value(self, ctx: Context) -> str | None: """Returns the value found in the environment variable(s) attached to this parameter. Environment variables values are `always returned as strings `_. This method returns ``None`` if: - the :attr:`envvar` property is not set on the :class:`Parameter`, - the environment variable is not found in the environment, - the variable is found in the environment but its value is empty (i.e. the environment variable is present but has an empty string). If :attr:`envvar` is setup with multiple environment variables, then only the first non-empty value is returned. .. caution:: The raw value extracted from the environment is not normalized and is returned as-is. Any normalization or reconciliation is performed later by the :class:`Parameter`'s :attr:`type`. :meta private: """ if not self.envvar: return None if isinstance(self.envvar, str): rv = os.environ.get(self.envvar) if rv: return rv else: for envvar in self.envvar: rv = os.environ.get(envvar) # Return the first non-empty value of the list of environment variables. if rv: return rv # Else, absence of value is interpreted as an environment variable that # is not set, so proceed to the next one. return None def value_from_envvar(self, ctx: Context) -> str | cabc.Sequence[str] | None: """Process the raw environment variable string for this parameter. Returns the string as-is or splits it into a sequence of strings if the parameter is expecting multiple values (i.e. its :attr:`nargs` property is set to a value other than ``1``). :meta private: """ rv = self.resolve_envvar_value(ctx) if rv is not None and self.nargs != 1: return self.type.split_envvar_value(rv) return rv async def handle_parse_result( self, ctx: Context, opts: cabc.Mapping[str, t.Any], args: list[str] ) -> tuple[t.Any, list[str]]: """Process the value produced by the parser from user input. Always process the value through the Parameter's :attr:`type`, wherever it comes from. If the parameter is deprecated, this method warn the user about it. But only if the value has been explicitly set by the user (and as such, is not coming from a default). :meta private: """ with augment_usage_errors(ctx, param=self): value, source = await self.consume_value(ctx, opts) ctx.set_parameter_source(self.name, source) # type: ignore # Display a deprecation warning if necessary. if ( self.deprecated and value is not UNSET and source not in (ParameterSource.DEFAULT, ParameterSource.DEFAULT_MAP) ): extra_message = ( f" {self.deprecated}" if isinstance(self.deprecated, str) else "" ) message = _( "DeprecationWarning: The {param_type} {name!r} is deprecated." "{extra_message}" ).format( param_type=self.param_type_name, name=self.human_readable_name, extra_message=extra_message, ) echo(style(message, fg="red"), err=True) # Process the value through the parameter's type. try: value = await self.process_value(ctx, value) except Exception: if not ctx.resilient_parsing: raise # In resilient parsing mode, we do not want to fail the command if the # value is incompatible with the parameter type, so we reset the value # to UNSET, which will be interpreted as a missing value. value = UNSET # Add parameter's value to the context. if ( self.expose_value # We skip adding the value if it was previously set by another parameter # targeting the same variable name. This prevents parameters competing for # the same name to override each other. and self.name not in ctx.params ): # Click is logically enforcing that the name is None if the parameter is # not to be exposed. We still assert it here to please the type checker. assert self.name is not None, ( f"{self!r} parameter's name should not be None when exposing value." ) # Normalize UNSET values to None, as we're about to pass them to the # command function and move them to the pure-Python realm of user-written # code. ctx.params[self.name] = value if value is not UNSET else None return value, args def get_help_record(self, ctx: Context) -> tuple[str, str] | None: pass def get_usage_pieces(self, ctx: Context) -> list[str]: return [] def get_error_hint(self, ctx: Context) -> str: """Get a stringified version of the param for use in error messages to indicate which param caused the error. """ hint_list = self.opts or [self.human_readable_name] return " / ".join(f"'{x}'" for x in hint_list) def shell_complete(self, ctx: Context, incomplete: str) -> list[CompletionItem]: """Return a list of completions for the incomplete value. If a ``shell_complete`` function was given during init, it is used. Otherwise, the :attr:`type` :meth:`~click.types.ParamType.shell_complete` function is used. :param ctx: Invocation context for this command. :param incomplete: Value being completed. May be empty. .. versionadded:: 8.0 """ if self._custom_shell_complete is not None: results = self._custom_shell_complete(ctx, self, incomplete) if results and isinstance(results[0], str): from .shell_completion import CompletionItem results = [CompletionItem(c) for c in results] return t.cast("list[CompletionItem]", results) return self.type.shell_complete(ctx, self, incomplete) class Option(Parameter): """Options are usually optional values on the command line and have some extra features that arguments don't have. All other parameters are passed onwards to the parameter constructor. :param show_default: Show the default value for this option in its help text. Values are not shown by default, unless :attr:`Context.show_default` is ``True``. If this value is a string, it shows that string in parentheses instead of the actual value. This is particularly useful for dynamic options. For single option boolean flags, the default remains hidden if its value is ``False``. :param show_envvar: Controls if an environment variable should be shown on the help page and error messages. Normally, environment variables are not shown. :param prompt: If set to ``True`` or a non empty string then the user will be prompted for input. If set to ``True`` the prompt will be the option name capitalized. A deprecated option cannot be prompted. :param confirmation_prompt: Prompt a second time to confirm the value if it was prompted for. Can be set to a string instead of ``True`` to customize the message. :param prompt_required: If set to ``False``, the user will be prompted for input only when the option was specified as a flag without a value. :param hide_input: If this is ``True`` then the input on the prompt will be hidden from the user. This is useful for password input. :param is_flag: forces this option to act as a flag. The default is auto detection. :param flag_value: which value should be used for this flag if it's enabled. This is set to a boolean automatically if the option string contains a slash to mark two options. :param multiple: if this is set to `True` then the argument is accepted multiple times and recorded. This is similar to ``nargs`` in how it works but supports arbitrary number of arguments. :param count: this flag makes an option increment an integer. :param allow_from_autoenv: if this is enabled then the value of this parameter will be pulled from an environment variable in case a prefix is defined on the context. :param help: the help string. :param hidden: hide this option from help outputs. :param attrs: Other command arguments described in :class:`Parameter`. .. versionchanged:: 8.2 ``envvar`` used with ``flag_value`` will always use the ``flag_value``, previously it would use the value of the environment variable. .. versionchanged:: 8.1 Help text indentation is cleaned here instead of only in the ``@option`` decorator. .. versionchanged:: 8.1 The ``show_default`` parameter overrides ``Context.show_default``. .. versionchanged:: 8.1 The default of a single option boolean flag is not shown if the default value is ``False``. .. versionchanged:: 8.0.1 ``type`` is detected from ``flag_value`` if given. """ param_type_name = "option" def __init__( self, param_decls: cabc.Sequence[str] | None = None, show_default: bool | str | None = None, prompt: bool | str = False, confirmation_prompt: bool | str = False, prompt_required: bool = True, hide_input: bool = False, is_flag: bool | None = None, flag_value: t.Any = UNSET, multiple: bool = False, count: bool = False, allow_from_autoenv: bool = True, type: types.ParamType | t.Any | None = None, help: str | None = None, hidden: bool = False, show_choices: bool = True, show_envvar: bool = False, deprecated: bool | str = False, **attrs: t.Any, ) -> None: if help: help = inspect.cleandoc(help) super().__init__( param_decls, type=type, multiple=multiple, deprecated=deprecated, **attrs ) if prompt is True: if self.name is None: raise TypeError("'name' is required with 'prompt=True'.") prompt_text: str | None = self.name.replace("_", " ").capitalize() elif prompt is False: prompt_text = None else: prompt_text = prompt if deprecated: deprecated_message = ( f"(DEPRECATED: {deprecated})" if isinstance(deprecated, str) else "(DEPRECATED)" ) help = help + deprecated_message if help is not None else deprecated_message self.prompt = prompt_text self.confirmation_prompt = confirmation_prompt self.prompt_required = prompt_required self.hide_input = hide_input self.hidden = hidden # The _flag_needs_value property tells the parser that this option is a flag # that cannot be used standalone and needs a value. With this information, the # parser can determine whether to consider the next user-provided argument in # the CLI as a value for this flag or as a new option. # If prompt is enabled but not required, then it opens the possibility for the # option to gets its value from the user. self._flag_needs_value = self.prompt is not None and not self.prompt_required # Auto-detect if this is a flag or not. if is_flag is None: # Implicitly a flag because flag_value was set. if flag_value is not UNSET: is_flag = True # Not a flag, but when used as a flag it shows a prompt. elif self._flag_needs_value: is_flag = False # Implicitly a flag because secondary options names were given. elif self.secondary_opts: is_flag = True # The option is explicitly not a flag. But we do not know yet if it needs a # value or not. So we look at the default value to determine it. elif is_flag is False and not self._flag_needs_value: self._flag_needs_value = self.default is UNSET if is_flag: # Set missing default for flags if not explicitly required or prompted. if self.default is UNSET and not self.required and not self.prompt: if multiple: self.default = () # Auto-detect the type of the flag based on the flag_value. if type is None: # A flag without a flag_value is a boolean flag. if flag_value is UNSET: self.type = types.BoolParamType() # If the flag value is a boolean, use BoolParamType. elif isinstance(flag_value, bool): self.type = types.BoolParamType() # Otherwise, guess the type from the flag value. else: self.type = types.convert_type(None, flag_value) self.is_flag: bool = bool(is_flag) self.is_bool_flag: bool = bool( is_flag and isinstance(self.type, types.BoolParamType) ) self.flag_value: t.Any = flag_value # Set boolean flag default to False if unset and not required. if self.is_bool_flag: if self.default is UNSET and not self.required: self.default = False # Support the special case of aligning the default value with the flag_value # for flags whose default is explicitly set to True. Note that as long as we # have this condition, there is no way a flag can have a default set to True, # and a flag_value set to something else. Refs: # https://github.com/pallets/click/issues/3024#issuecomment-3146199461 # https://github.com/pallets/click/pull/3030/commits/06847da if self.default is True and self.flag_value is not UNSET: self.default = self.flag_value # Set the default flag_value if it is not set. if self.flag_value is UNSET: if self.is_flag: self.flag_value = True else: self.flag_value = None # Counting. self.count = count if count: if type is None: self.type = types.IntRange(min=0) if self.default is UNSET: self.default = 0 self.allow_from_autoenv = allow_from_autoenv self.help = help self.show_default = show_default self.show_choices = show_choices self.show_envvar = show_envvar if __debug__: if deprecated and prompt: raise ValueError("`deprecated` options cannot use `prompt`.") if self.nargs == -1: raise TypeError("nargs=-1 is not supported for options.") if not self.is_bool_flag and self.secondary_opts: raise TypeError("Secondary flag is not valid for non-boolean flag.") if self.is_bool_flag and self.hide_input and self.prompt is not None: raise TypeError( "'prompt' with 'hide_input' is not valid for boolean flag." ) if self.count: if self.multiple: raise TypeError("'count' is not valid with 'multiple'.") if self.is_flag: raise TypeError("'count' is not valid with 'is_flag'.") async def to_info_dict(self) -> dict[str, t.Any]: """ .. versionchanged:: 8.3.0 Returns ``None`` for the :attr:`flag_value` if it was not set. """ info_dict = await super().to_info_dict() info_dict.update( help=self.help, prompt=self.prompt, is_flag=self.is_flag, # We explicitly hide the :attr:`UNSET` value to the user, as we choose to # make it an implementation detail. And because ``to_info_dict`` has been # designed for documentation purposes, we return ``None`` instead. flag_value=self.flag_value if self.flag_value is not UNSET else None, count=self.count, hidden=self.hidden, ) return info_dict def get_error_hint(self, ctx: Context) -> str: result = super().get_error_hint(ctx) if self.show_envvar and self.envvar is not None: result += f" (env var: '{self.envvar}')" return result def _parse_decls( self, decls: cabc.Sequence[str], expose_value: bool ) -> tuple[str | None, list[str], list[str]]: opts = [] secondary_opts = [] name = None possible_names = [] for decl in decls: if decl.isidentifier(): if name is not None: raise TypeError(f"Name '{name}' defined twice") name = decl else: split_char = ";" if decl[:1] == "/" else "/" if split_char in decl: first, second = decl.split(split_char, 1) first = first.rstrip() if first: possible_names.append(_split_opt(first)) opts.append(first) second = second.lstrip() if second: secondary_opts.append(second.lstrip()) if first == second: raise ValueError( f"Boolean option {decl!r} cannot use the" " same flag for true/false." ) else: possible_names.append(_split_opt(decl)) opts.append(decl) if name is None and possible_names: possible_names.sort(key=lambda x: -len(x[0])) # group long options first name = possible_names[0][1].replace("-", "_").lower() if not name.isidentifier(): name = None if name is None: if not expose_value: return None, opts, secondary_opts raise TypeError( f"Could not determine name for option with declarations {decls!r}" ) if not opts and not secondary_opts: raise TypeError( f"No options defined but a name was passed ({name})." " Did you mean to declare an argument instead? Did" f" you mean to pass '--{name}'?" ) return name, opts, secondary_opts def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None: if self.multiple: action = "append" elif self.count: action = "count" else: action = "store" if self.is_flag: action = f"{action}_const" if self.is_bool_flag and self.secondary_opts: parser.add_option( obj=self, opts=self.opts, dest=self.name, action=action, const=True ) parser.add_option( obj=self, opts=self.secondary_opts, dest=self.name, action=action, const=False, ) else: parser.add_option( obj=self, opts=self.opts, dest=self.name, action=action, const=self.flag_value, ) else: parser.add_option( obj=self, opts=self.opts, dest=self.name, action=action, nargs=self.nargs, ) def get_help_record(self, ctx: Context) -> tuple[str, str] | None: if self.hidden: return None any_prefix_is_slash = False def _write_opts(opts: cabc.Sequence[str]) -> str: nonlocal any_prefix_is_slash rv, any_slashes = join_options(opts) if any_slashes: any_prefix_is_slash = True if not self.is_flag and not self.count: rv += f" {self.make_metavar(ctx=ctx)}" return rv rv = [_write_opts(self.opts)] if self.secondary_opts: rv.append(_write_opts(self.secondary_opts)) help = self.help or "" extra = self.get_help_extra(ctx) extra_items = [] if "envvars" in extra: extra_items.append( _("env var: {var}").format(var=", ".join(extra["envvars"])) ) if "default" in extra: extra_items.append(_("default: {default}").format(default=extra["default"])) if "range" in extra: extra_items.append(extra["range"]) if "required" in extra: extra_items.append(_(extra["required"])) if extra_items: extra_str = "; ".join(extra_items) help = f"{help} [{extra_str}]" if help else f"[{extra_str}]" return ("; " if any_prefix_is_slash else " / ").join(rv), help def get_help_extra(self, ctx: Context) -> types.OptionHelpExtra: extra: types.OptionHelpExtra = {} if self.show_envvar: envvar = self.envvar if envvar is None: if ( self.allow_from_autoenv and ctx.auto_envvar_prefix is not None and self.name is not None ): envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}" if envvar is not None: if isinstance(envvar, str): extra["envvars"] = (envvar,) else: extra["envvars"] = tuple(str(d) for d in envvar) # Temporarily enable resilient parsing to avoid type casting # failing for the default. Might be possible to extend this to # help formatting in general. resilient = ctx.resilient_parsing ctx.resilient_parsing = True try: default_value = self.get_default(ctx, call=False) finally: ctx.resilient_parsing = resilient show_default = False show_default_is_str = False if self.show_default is not None: if isinstance(self.show_default, str): show_default_is_str = show_default = True else: show_default = self.show_default elif ctx.show_default is not None: show_default = ctx.show_default if show_default_is_str or ( show_default and (default_value not in (None, UNSET)) ): if show_default_is_str: default_string = f"({self.show_default})" elif isinstance(default_value, (list, tuple)): default_string = ", ".join(str(d) for d in default_value) elif isinstance(default_value, enum.Enum): default_string = default_value.name elif inspect.isfunction(default_value): default_string = _("(dynamic)") elif self.is_bool_flag and self.secondary_opts: # For boolean flags that have distinct True/False opts, # use the opt without prefix instead of the value. default_string = _split_opt( (self.opts if default_value else self.secondary_opts)[0] )[1] elif self.is_bool_flag and not self.secondary_opts and not default_value: default_string = "" elif default_value == "": default_string = '""' else: default_string = str(default_value) if default_string: extra["default"] = default_string if ( isinstance(self.type, types._NumberRangeBase) # skip count with default range type and not (self.count and self.type.min == 0 and self.type.max is None) ): range_str = self.type._describe_range() if range_str: extra["range"] = range_str if self.required: extra["required"] = "required" return extra async def prompt_for_value(self, ctx: Context) -> t.Any: """This is an alternative flow that can be activated in the full value processing if a value does not exist. It will prompt the user until a valid value exists and then returns the processed value as result. """ assert self.prompt is not None # Calculate the default before prompting anything to lock in the value before # attempting any user interaction. default = self.get_default(ctx) # A boolean flag can use a simplified [y/n] confirmation prompt. if self.is_bool_flag: # If we have no boolean default, we force the user to explicitly provide # one. if default in (UNSET, None): default = None # Nothing prevent you to declare an option that is simultaneously: # 1) auto-detected as a boolean flag, # 2) allowed to prompt, and # 3) still declare a non-boolean default. # This forced casting into a boolean is necessary to align any non-boolean # default to the prompt, which is going to be a [y/n]-style confirmation # because the option is still a boolean flag. That way, instead of [y/n], # we get [Y/n] or [y/N] depending on the truthy value of the default. # Refs: https://github.com/pallets/click/pull/3030#discussion_r2289180249 else: default = bool(default) return confirm(self.prompt, default) # If show_default is set to True/False, provide this to `prompt` as well. For # non-bool values of `show_default`, we use `prompt`'s default behavior prompt_kwargs: t.Any = {} if isinstance(self.show_default, bool): prompt_kwargs["show_default"] = self.show_default return await prompt( self.prompt, # Use ``None`` to inform the prompt() function to reiterate until a valid # value is provided by the user if we have no default. default=None if default is UNSET else default, type=self.type, hide_input=self.hide_input, show_choices=self.show_choices, confirmation_prompt=self.confirmation_prompt, value_proc=lambda x: self.process_value(ctx, x), **prompt_kwargs, ) def resolve_envvar_value(self, ctx: Context) -> str | None: """:class:`Option` resolves its environment variable the same way as :func:`Parameter.resolve_envvar_value`, but it also supports :attr:`Context.auto_envvar_prefix`. If we could not find an environment from the :attr:`envvar` property, we fallback on :attr:`Context.auto_envvar_prefix` to build dynamiccaly the environment variable name using the :python:`{ctx.auto_envvar_prefix}_{self.name.upper()}` template. :meta private: """ rv = super().resolve_envvar_value(ctx) if rv is not None: return rv if ( self.allow_from_autoenv and ctx.auto_envvar_prefix is not None and self.name is not None ): envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}" rv = os.environ.get(envvar) if rv: return rv return None def value_from_envvar(self, ctx: Context) -> t.Any: """For :class:`Option`, this method processes the raw environment variable string the same way as :func:`Parameter.value_from_envvar` does. But in the case of non-boolean flags, the value is analyzed to determine if the flag is activated or not, and returns a boolean of its activation, or the :attr:`flag_value` if the latter is set. This method also takes care of repeated options (i.e. options with :attr:`multiple` set to ``True``). :meta private: """ rv = self.resolve_envvar_value(ctx) # Absent environment variable or an empty string is interpreted as unset. if rv is None: return None # Non-boolean flags are more liberal in what they accept. But a flag being a # flag, its envvar value still needs to be analyzed to determine if the flag is # activated or not. if self.is_flag and not self.is_bool_flag: # If the flag_value is set and match the envvar value, return it # directly. if self.flag_value is not UNSET and rv == self.flag_value: return self.flag_value # Analyze the envvar value as a boolean to know if the flag is # activated or not. return types.BoolParamType.str_to_bool(rv) # Split the envvar value if it is allowed to be repeated. value_depth = (self.nargs != 1) + bool(self.multiple) if value_depth > 0: multi_rv = self.type.split_envvar_value(rv) if self.multiple and self.nargs != 1: multi_rv = batch(multi_rv, self.nargs) # type: ignore[assignment] return multi_rv return rv async def consume_value( self, ctx: Context, opts: cabc.Mapping[str, Parameter] ) -> tuple[t.Any, ParameterSource]: """For :class:`Option`, the value can be collected from an interactive prompt if the option is a flag that needs a value (and the :attr:`prompt` property is set). Additionally, this method handles flag option that are activated without a value, in which case the :attr:`flag_value` is returned. :meta private: """ value, source = await super().consume_value(ctx, opts) # The parser will emit a sentinel value if the option is allowed to as a flag # without a value. if value is FLAG_NEEDS_VALUE: # If the option allows for a prompt, we start an interaction with the user. if self.prompt is not None and not ctx.resilient_parsing: value = await self.prompt_for_value(ctx) source = ParameterSource.PROMPT # Else the flag takes its flag_value as value. else: value = self.flag_value source = ParameterSource.COMMANDLINE # A flag which is activated always returns the flag value, unless the value # comes from the explicitly sets default. elif ( self.is_flag and value is True and not self.is_bool_flag and source not in (ParameterSource.DEFAULT, ParameterSource.DEFAULT_MAP) ): value = self.flag_value # Re-interpret a multiple option which has been sent as-is by the parser. # Here we replace each occurrence of value-less flags (marked by the # FLAG_NEEDS_VALUE sentinel) with the flag_value. elif ( self.multiple and value is not UNSET and source not in (ParameterSource.DEFAULT, ParameterSource.DEFAULT_MAP) and any(v is FLAG_NEEDS_VALUE for v in value) ): value = [self.flag_value if v is FLAG_NEEDS_VALUE else v for v in value] source = ParameterSource.COMMANDLINE # The value wasn't set, or used the param's default, prompt for one to the user # if prompting is enabled. elif ( ( value is UNSET or source in (ParameterSource.DEFAULT, ParameterSource.DEFAULT_MAP) ) and self.prompt is not None and (self.required or self.prompt_required) and not ctx.resilient_parsing ): value = await self.prompt_for_value(ctx) source = ParameterSource.PROMPT return value, source def type_cast_value(self, ctx: Context, value: t.Any) -> t.Any: if self.is_flag and not self.required: if value is UNSET: if self.is_bool_flag: # If the flag is a boolean flag, we return False if it is not set. value = False return super().type_cast_value(ctx, value) class Argument(Parameter): """Arguments are positional parameters to a command. They generally provide fewer features than options but can have infinite ``nargs`` and are required by default. All parameters are passed onwards to the constructor of :class:`Parameter`. """ param_type_name = "argument" def __init__( self, param_decls: cabc.Sequence[str], required: bool | None = None, **attrs: t.Any, ) -> None: # Auto-detect the requirement status of the argument if not explicitly set. if required is None: # The argument gets automatically required if it has no explicit default # value set and is setup to match at least one value. if attrs.get("default", UNSET) is UNSET: required = attrs.get("nargs", 1) > 0 # If the argument has a default value, it is not required. else: required = False if "multiple" in attrs: raise TypeError("__init__() got an unexpected keyword argument 'multiple'.") super().__init__(param_decls, required=required, **attrs) @property def human_readable_name(self) -> str: if self.metavar is not None: return self.metavar return self.name.upper() # type: ignore def make_metavar(self, ctx: Context) -> str: if self.metavar is not None: return self.metavar var = self.type.get_metavar(param=self, ctx=ctx) if not var: var = self.name.upper() # type: ignore if self.deprecated: var += "!" if not self.required: var = f"[{var}]" if self.nargs != 1: var += "..." return var def _parse_decls( self, decls: cabc.Sequence[str], expose_value: bool ) -> tuple[str | None, list[str], list[str]]: if not decls: if not expose_value: return None, [], [] raise TypeError("Argument is marked as exposed, but does not have a name.") if len(decls) == 1: name = arg = decls[0] name = name.replace("-", "_").lower() else: raise TypeError( "Arguments take exactly one parameter declaration, got" f" {len(decls)}: {decls}." ) return name, [arg], [] def get_usage_pieces(self, ctx: Context) -> list[str]: return [self.make_metavar(ctx)] def get_error_hint(self, ctx: Context) -> str: return f"'{self.make_metavar(ctx)}'" def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None: parser.add_argument(dest=self.name, nargs=self.nargs, obj=self) def __getattr__(name: str) -> object: import warnings if name == "BaseCommand": warnings.warn( "'BaseCommand' is deprecated and will be removed in Click 9.0. Use" " 'Command' instead.", DeprecationWarning, stacklevel=2, ) return _BaseCommand if name == "MultiCommand": warnings.warn( "'MultiCommand' is deprecated and will be removed in Click 9.0. Use" " 'Group' instead.", DeprecationWarning, stacklevel=2, ) return _MultiCommand raise AttributeError(name) asyncclick-8.3.0.5-async/src/asyncclick/decorators.py000066400000000000000000000444031507140761400225660ustar00rootroot00000000000000from __future__ import annotations import inspect import typing as t from functools import update_wrapper from gettext import gettext as _ from .core import Argument from .core import Command from .core import Context from .core import Group from .core import Option from .core import Parameter from .globals import get_current_context from .utils import echo if t.TYPE_CHECKING: import typing_extensions as te P = te.ParamSpec("P") R = t.TypeVar("R") T = t.TypeVar("T") _AnyCallable = t.Callable[..., t.Any] FC = t.TypeVar("FC", bound="_AnyCallable | Command") def pass_context(f: t.Callable[te.Concatenate[Context, P], R]) -> t.Callable[P, R]: """Marks a callback as wanting to receive the current context object as first argument. """ def new_func(*args: P.args, **kwargs: P.kwargs) -> R: return f(get_current_context(), *args, **kwargs) return update_wrapper(new_func, f) def pass_obj(f: t.Callable[te.Concatenate[T, P], R]) -> t.Callable[P, R]: """Similar to :func:`pass_context`, but only pass the object on the context onwards (:attr:`Context.obj`). This is useful if that object represents the state of a nested system. """ def new_func(*args: P.args, **kwargs: P.kwargs) -> R: return f(get_current_context().obj, *args, **kwargs) return update_wrapper(new_func, f) def make_pass_decorator( object_type: type[T], ensure: bool = False ) -> t.Callable[ [t.Callable[te.Concatenate[T, P], R]], t.Callable[P, t.Coroutine[t.Any, t.Any, R]] ]: """Given an object type this creates a decorator that will work similar to :func:`pass_obj` but instead of passing the object of the current context, it will find the innermost context of type :func:`object_type`. This generates a decorator that works roughly like this:: from functools import update_wrapper def decorator(f): @pass_context def new_func(ctx, *args, **kwargs): obj = ctx.find_object(object_type) return ctx.invoke(f, obj, *args, **kwargs) return update_wrapper(new_func, f) return decorator :param object_type: the type of the object to pass. :param ensure: if set to `True`, a new object will be created and remembered on the context if it's not there yet. """ def decorator( f: t.Callable[te.Concatenate[T, P], R], ) -> t.Callable[P, t.Coroutine[t.Any, t.Any, R]]: def new_func(*args: P.args, **kwargs: P.kwargs) -> t.Coroutine[t.Any, t.Any, R]: ctx = get_current_context() obj: T | None if ensure: obj = ctx.ensure_object(object_type) else: obj = ctx.find_object(object_type) if obj is None: raise RuntimeError( "Managed to invoke callback without a context" f" object of type {object_type.__name__!r}" " existing." ) return ctx.invoke(f, obj, *args, **kwargs) return update_wrapper(new_func, f) return decorator def pass_meta_key( key: str, *, doc_description: str | None = None ) -> t.Callable[ [t.Callable[te.Concatenate[T, P], R]], t.Callable[P, t.Coroutine[t.Any, t.Any, R]] ]: """Create a decorator that passes a key from :attr:`click.Context.meta` as the first argument to the decorated function. :param key: Key in ``Context.meta`` to pass. :param doc_description: Description of the object being passed, inserted into the decorator's docstring. Defaults to "the 'key' key from Context.meta". .. versionadded:: 8.0 """ def decorator( f: t.Callable[te.Concatenate[T, P], R], ) -> t.Callable[P, t.Coroutine[t.Any, t.Any, R]]: def new_func(*args: P.args, **kwargs: P.kwargs) -> t.Coroutine[t.Any, t.Any, R]: ctx = get_current_context() obj = ctx.meta[key] return ctx.invoke(f, obj, *args, **kwargs) return update_wrapper(new_func, f) if doc_description is None: doc_description = f"the {key!r} key from :attr:`click.Context.meta`" decorator.__doc__ = ( f"Decorator that passes {doc_description} as the first argument" " to the decorated function." ) return decorator CmdType = t.TypeVar("CmdType", bound=Command) # variant: no call, directly as decorator for a function. @t.overload def command(name: _AnyCallable) -> Command: ... # variant: with positional name and with positional or keyword cls argument: # @command(namearg, CommandCls, ...) or @command(namearg, cls=CommandCls, ...) @t.overload def command( name: str | None, cls: type[CmdType], **attrs: t.Any, ) -> t.Callable[[_AnyCallable], CmdType]: ... # variant: name omitted, cls _must_ be a keyword argument, @command(cls=CommandCls, ...) @t.overload def command( name: None = None, *, cls: type[CmdType], **attrs: t.Any, ) -> t.Callable[[_AnyCallable], CmdType]: ... # variant: with optional string name, no cls argument provided. @t.overload def command( name: str | None = ..., cls: None = None, **attrs: t.Any ) -> t.Callable[[_AnyCallable], Command]: ... def command( name: str | _AnyCallable | None = None, cls: type[CmdType] | None = None, **attrs: t.Any, ) -> Command | t.Callable[[_AnyCallable], Command | CmdType]: r"""Creates a new :class:`Command` and uses the decorated function as callback. This will also automatically attach all decorated :func:`option`\s and :func:`argument`\s as parameters to the command. The name of the command defaults to the name of the function, converted to lowercase, with underscores ``_`` replaced by dashes ``-``, and the suffixes ``_command``, ``_cmd``, ``_group``, and ``_grp`` are removed. For example, ``init_data_command`` becomes ``init-data``. All keyword arguments are forwarded to the underlying command class. For the ``params`` argument, any decorated params are appended to the end of the list. Once decorated the function turns into a :class:`Command` instance that can be invoked as a command line utility or be attached to a command :class:`Group`. :param name: The name of the command. Defaults to modifying the function's name as described above. :param cls: The command class to create. Defaults to :class:`Command`. .. versionchanged:: 8.2 The suffixes ``_command``, ``_cmd``, ``_group``, and ``_grp`` are removed when generating the name. .. versionchanged:: 8.1 This decorator can be applied without parentheses. .. versionchanged:: 8.1 The ``params`` argument can be used. Decorated params are appended to the end of the list. """ func: t.Callable[[_AnyCallable], t.Any] | None = None if callable(name): func = name name = None assert cls is None, "Use 'command(cls=cls)(callable)' to specify a class." assert not attrs, "Use 'command(**kwargs)(callable)' to provide arguments." if cls is None: cls = t.cast("type[CmdType]", Command) def decorator(f: _AnyCallable) -> CmdType: if isinstance(f, Command): raise TypeError("Attempted to convert a callback into a command twice.") attr_params = attrs.pop("params", None) params = attr_params if attr_params is not None else [] try: decorator_params = f.__click_params__ # type: ignore except AttributeError: pass else: del f.__click_params__ # type: ignore params.extend(reversed(decorator_params)) if attrs.get("help") is None: attrs["help"] = f.__doc__ if t.TYPE_CHECKING: assert cls is not None assert not callable(name) if name is not None: cmd_name = name else: cmd_name = f.__name__.lower().replace("_", "-") cmd_left, sep, suffix = cmd_name.rpartition("-") if sep and suffix in {"command", "cmd", "group", "grp"}: cmd_name = cmd_left cmd = cls(name=cmd_name, callback=f, params=params, **attrs) cmd.__doc__ = f.__doc__ return cmd if func is not None: return decorator(func) return decorator GrpType = t.TypeVar("GrpType", bound=Group) # variant: no call, directly as decorator for a function. @t.overload def group(name: _AnyCallable) -> Group: ... # variant: with positional name and with positional or keyword cls argument: # @group(namearg, GroupCls, ...) or @group(namearg, cls=GroupCls, ...) @t.overload def group( name: str | None, cls: type[GrpType], **attrs: t.Any, ) -> t.Callable[[_AnyCallable], GrpType]: ... # variant: name omitted, cls _must_ be a keyword argument, @group(cmd=GroupCls, ...) @t.overload def group( name: None = None, *, cls: type[GrpType], **attrs: t.Any, ) -> t.Callable[[_AnyCallable], GrpType]: ... # variant: with optional string name, no cls argument provided. @t.overload def group( name: str | None = ..., cls: None = None, **attrs: t.Any ) -> t.Callable[[_AnyCallable], Group]: ... def group( name: str | _AnyCallable | None = None, cls: type[GrpType] | None = None, **attrs: t.Any, ) -> Group | t.Callable[[_AnyCallable], Group | GrpType]: """Creates a new :class:`Group` with a function as callback. This works otherwise the same as :func:`command` just that the `cls` parameter is set to :class:`Group`. .. versionchanged:: 8.1 This decorator can be applied without parentheses. """ if cls is None: cls = t.cast("type[GrpType]", Group) if callable(name): return command(cls=cls, **attrs)(name) return command(name, cls, **attrs) def _param_memo(f: t.Callable[..., t.Any], param: Parameter) -> None: if isinstance(f, Command): f.params.append(param) else: if not hasattr(f, "__click_params__"): f.__click_params__ = [] # type: ignore f.__click_params__.append(param) # type: ignore def argument( *param_decls: str, cls: type[Argument] | None = None, **attrs: t.Any ) -> t.Callable[[FC], FC]: """Attaches an argument to the command. All positional arguments are passed as parameter declarations to :class:`Argument`; all keyword arguments are forwarded unchanged (except ``cls``). This is equivalent to creating an :class:`Argument` instance manually and attaching it to the :attr:`Command.params` list. For the default argument class, refer to :class:`Argument` and :class:`Parameter` for descriptions of parameters. :param cls: the argument class to instantiate. This defaults to :class:`Argument`. :param param_decls: Passed as positional arguments to the constructor of ``cls``. :param attrs: Passed as keyword arguments to the constructor of ``cls``. """ if cls is None: cls = Argument def decorator(f: FC) -> FC: _param_memo(f, cls(param_decls, **attrs)) return f return decorator def option( *param_decls: str, cls: type[Option] | None = None, **attrs: t.Any ) -> t.Callable[[FC], FC]: """Attaches an option to the command. All positional arguments are passed as parameter declarations to :class:`Option`; all keyword arguments are forwarded unchanged (except ``cls``). This is equivalent to creating an :class:`Option` instance manually and attaching it to the :attr:`Command.params` list. For the default option class, refer to :class:`Option` and :class:`Parameter` for descriptions of parameters. :param cls: the option class to instantiate. This defaults to :class:`Option`. :param param_decls: Passed as positional arguments to the constructor of ``cls``. :param attrs: Passed as keyword arguments to the constructor of ``cls``. """ if cls is None: cls = Option def decorator(f: FC) -> FC: _param_memo(f, cls(param_decls, **attrs)) return f return decorator def confirmation_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]: """Add a ``--yes`` option which shows a prompt before continuing if not passed. If the prompt is declined, the program will exit. :param param_decls: One or more option names. Defaults to the single value ``"--yes"``. :param kwargs: Extra arguments are passed to :func:`option`. """ def callback(ctx: Context, param: Parameter, value: bool) -> None: if not value: ctx.abort() if not param_decls: param_decls = ("--yes",) kwargs.setdefault("is_flag", True) kwargs.setdefault("callback", callback) kwargs.setdefault("expose_value", False) kwargs.setdefault("prompt", "Do you want to continue?") kwargs.setdefault("help", "Confirm the action without prompting.") return option(*param_decls, **kwargs) def password_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]: """Add a ``--password`` option which prompts for a password, hiding input and asking to enter the value again for confirmation. :param param_decls: One or more option names. Defaults to the single value ``"--password"``. :param kwargs: Extra arguments are passed to :func:`option`. """ if not param_decls: param_decls = ("--password",) kwargs.setdefault("prompt", True) kwargs.setdefault("confirmation_prompt", True) kwargs.setdefault("hide_input", True) return option(*param_decls, **kwargs) def version_option( version: str | None = None, *param_decls: str, package_name: str | None = None, prog_name: str | None = None, message: str | None = None, **kwargs: t.Any, ) -> t.Callable[[FC], FC]: """Add a ``--version`` option which immediately prints the version number and exits the program. If ``version`` is not provided, Click will try to detect it using :func:`importlib.metadata.version` to get the version for the ``package_name``. If ``package_name`` is not provided, Click will try to detect it by inspecting the stack frames. This will be used to detect the version, so it must match the name of the installed package. :param version: The version number to show. If not provided, Click will try to detect it. :param param_decls: One or more option names. Defaults to the single value ``"--version"``. :param package_name: The package name to detect the version from. If not provided, Click will try to detect it. :param prog_name: The name of the CLI to show in the message. If not provided, it will be detected from the command. :param message: The message to show. The values ``%(prog)s``, ``%(package)s``, and ``%(version)s`` are available. Defaults to ``"%(prog)s, version %(version)s"``. :param kwargs: Extra arguments are passed to :func:`option`. :raise RuntimeError: ``version`` could not be detected. .. versionchanged:: 8.0 Add the ``package_name`` parameter, and the ``%(package)s`` value for messages. .. versionchanged:: 8.0 Use :mod:`importlib.metadata` instead of ``pkg_resources``. The version is detected based on the package name, not the entry point name. The Python package name must match the installed package name, or be passed with ``package_name=``. """ if message is None: message = _("%(prog)s, version %(version)s") if version is None and package_name is None: frame = inspect.currentframe() f_back = frame.f_back if frame is not None else None f_globals = f_back.f_globals if f_back is not None else None # break reference cycle # https://docs.python.org/3/library/inspect.html#the-interpreter-stack del frame if f_globals is not None: package_name = f_globals.get("__name__") if package_name == "__main__": package_name = f_globals.get("__package__") if package_name: package_name = package_name.partition(".")[0] async def callback(ctx: Context, param: Parameter, value: bool) -> None: if not value or ctx.resilient_parsing: return nonlocal prog_name nonlocal version if prog_name is None: prog_name = ctx.find_root().info_name if version is None and package_name is not None: import importlib.metadata try: version = importlib.metadata.version(package_name) except importlib.metadata.PackageNotFoundError: raise RuntimeError( f"{package_name!r} is not installed. Try passing" " 'package_name' instead." ) from None if version is None: raise RuntimeError( f"Could not determine the version for {package_name!r} automatically." ) echo( message % {"prog": prog_name, "package": package_name, "version": version}, color=ctx.color, ) await ctx.aexit() if not param_decls: param_decls = ("--version",) kwargs.setdefault("is_flag", True) kwargs.setdefault("expose_value", False) kwargs.setdefault("is_eager", True) kwargs.setdefault("help", _("Show the version and exit.")) kwargs["callback"] = callback return option(*param_decls, **kwargs) def help_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]: """Pre-configured ``--help`` option which immediately prints the help page and exits the program. :param param_decls: One or more option names. Defaults to the single value ``"--help"``. :param kwargs: Extra arguments are passed to :func:`option`. """ async def show_help(ctx: Context, param: Parameter, value: bool) -> None: """Callback that print the help page on ```` and exits.""" if value and not ctx.resilient_parsing: echo(ctx.get_help(), color=ctx.color) await ctx.aexit() if not param_decls: param_decls = ("--help",) kwargs.setdefault("is_flag", True) kwargs.setdefault("expose_value", False) kwargs.setdefault("is_eager", True) kwargs.setdefault("help", _("Show this message and exit.")) kwargs.setdefault("callback", show_help) return option(*param_decls, **kwargs) asyncclick-8.3.0.5-async/src/asyncclick/exceptions.py000066400000000000000000000233421507140761400226010ustar00rootroot00000000000000from __future__ import annotations import collections.abc as cabc import typing as t from gettext import gettext as _ from gettext import ngettext from ._compat import get_text_stderr from .globals import resolve_color_default from .utils import echo from .utils import format_filename if t.TYPE_CHECKING: from .core import Command from .core import Context from .core import Parameter def _join_param_hints(param_hint: cabc.Sequence[str] | str | None) -> str | None: if param_hint is not None and not isinstance(param_hint, str): return " / ".join(repr(x) for x in param_hint) return param_hint class ClickException(Exception): """An exception that Click can handle and show to the user.""" #: The exit code for this exception. exit_code = 1 def __init__(self, message: str) -> None: super().__init__(message) # The context will be removed by the time we print the message, so cache # the color settings here to be used later on (in `show`) self.show_color: bool | None = resolve_color_default() self.message = message def format_message(self) -> str: return self.message def __str__(self) -> str: return self.message def show(self, file: t.IO[t.Any] | None = None) -> None: if file is None: file = get_text_stderr() echo( _("Error: {message}").format(message=self.format_message()), file=file, color=self.show_color, ) class UsageError(ClickException): """An internal exception that signals a usage error. This typically aborts any further handling. :param message: the error message to display. :param ctx: optionally the context that caused this error. Click will fill in the context automatically in some situations. """ exit_code = 2 def __init__(self, message: str, ctx: Context | None = None) -> None: super().__init__(message) self.ctx = ctx self.cmd: Command | None = self.ctx.command if self.ctx else None def show(self, file: t.IO[t.Any] | None = None) -> None: if file is None: file = get_text_stderr() color = None hint = "" if ( self.ctx is not None and self.ctx.command.get_help_option(self.ctx) is not None ): hint = _("Try '{command} {option}' for help.").format( command=self.ctx.command_path, option=self.ctx.help_option_names[0] ) hint = f"{hint}\n" if self.ctx is not None: color = self.ctx.color echo(f"{self.ctx.get_usage()}\n{hint}", file=file, color=color) echo( _("Error: {message}").format(message=self.format_message()), file=file, color=color, ) class BadParameter(UsageError): """An exception that formats out a standardized error message for a bad parameter. This is useful when thrown from a callback or type as Click will attach contextual information to it (for instance, which parameter it is). .. versionadded:: 2.0 :param param: the parameter object that caused this error. This can be left out, and Click will attach this info itself if possible. :param param_hint: a string that shows up as parameter name. This can be used as alternative to `param` in cases where custom validation should happen. If it is a string it's used as such, if it's a list then each item is quoted and separated. """ def __init__( self, message: str, ctx: Context | None = None, param: Parameter | None = None, param_hint: cabc.Sequence[str] | str | None = None, ) -> None: super().__init__(message, ctx) self.param = param self.param_hint = param_hint def format_message(self) -> str: if self.param_hint is not None: param_hint = self.param_hint elif self.param is not None: param_hint = self.param.get_error_hint(self.ctx) # type: ignore else: return _("Invalid value: {message}").format(message=self.message) return _("Invalid value for {param_hint}: {message}").format( param_hint=_join_param_hints(param_hint), message=self.message ) class MissingParameter(BadParameter): """Raised if click required an option or argument but it was not provided when invoking the script. .. versionadded:: 4.0 :param param_type: a string that indicates the type of the parameter. The default is to inherit the parameter type from the given `param`. Valid values are ``'parameter'``, ``'option'`` or ``'argument'``. """ def __init__( self, message: str | None = None, ctx: Context | None = None, param: Parameter | None = None, param_hint: cabc.Sequence[str] | str | None = None, param_type: str | None = None, ) -> None: super().__init__(message or "", ctx, param, param_hint) self.param_type = param_type def format_message(self) -> str: if self.param_hint is not None: param_hint: cabc.Sequence[str] | str | None = self.param_hint elif self.param is not None: param_hint = self.param.get_error_hint(self.ctx) # type: ignore else: param_hint = None param_hint = _join_param_hints(param_hint) param_hint = f" {param_hint}" if param_hint else "" param_type = self.param_type if param_type is None and self.param is not None: param_type = self.param.param_type_name msg = self.message if self.param is not None: msg_extra = self.param.type.get_missing_message( param=self.param, ctx=self.ctx ) if msg_extra: if msg: msg += f". {msg_extra}" else: msg = msg_extra msg = f" {msg}" if msg else "" # Translate param_type for known types. if param_type == "argument": missing = _("Missing argument") elif param_type == "option": missing = _("Missing option") elif param_type == "parameter": missing = _("Missing parameter") else: missing = _("Missing {param_type}").format(param_type=param_type) return f"{missing}{param_hint}.{msg}" def __str__(self) -> str: if not self.message: param_name = self.param.name if self.param else None return _("Missing parameter: {param_name}").format(param_name=param_name) else: return self.message class NoSuchOption(UsageError): """Raised if click attempted to handle an option that does not exist. .. versionadded:: 4.0 """ def __init__( self, option_name: str, message: str | None = None, possibilities: cabc.Sequence[str] | None = None, ctx: Context | None = None, ) -> None: if message is None: message = _("No such option: {name}").format(name=option_name) super().__init__(message, ctx) self.option_name = option_name self.possibilities = possibilities def format_message(self) -> str: if not self.possibilities: return self.message possibility_str = ", ".join(sorted(self.possibilities)) suggest = ngettext( "Did you mean {possibility}?", "(Possible options: {possibilities})", len(self.possibilities), ).format(possibility=possibility_str, possibilities=possibility_str) return f"{self.message} {suggest}" class BadOptionUsage(UsageError): """Raised if an option is generally supplied but the use of the option was incorrect. This is for instance raised if the number of arguments for an option is not correct. .. versionadded:: 4.0 :param option_name: the name of the option being used incorrectly. """ def __init__( self, option_name: str, message: str, ctx: Context | None = None ) -> None: super().__init__(message, ctx) self.option_name = option_name class BadArgumentUsage(UsageError): """Raised if an argument is generally supplied but the use of the argument was incorrect. This is for instance raised if the number of values for an argument is not correct. .. versionadded:: 6.0 """ class NoArgsIsHelpError(UsageError): def __init__(self, ctx: Context) -> None: self.ctx: Context super().__init__(ctx.get_help(), ctx=ctx) def show(self, file: t.IO[t.Any] | None = None) -> None: echo(self.format_message(), file=file, err=True, color=self.ctx.color) class FileError(ClickException): """Raised if a file cannot be opened.""" def __init__(self, filename: str, hint: str | None = None) -> None: if hint is None: hint = _("unknown error") super().__init__(hint) self.ui_filename: str = format_filename(filename) self.filename = filename def format_message(self) -> str: return _("Could not open file {filename!r}: {message}").format( filename=self.ui_filename, message=self.message ) class Abort(RuntimeError): """An internal signalling exception that signals Click to abort.""" class Exit(RuntimeError): """An exception that indicates that the application should exit with some status code. :param code: the status code to exit with. """ __slots__ = ("exit_code",) def __init__(self, code: int = 0) -> None: self.exit_code: int = code asyncclick-8.3.0.5-async/src/asyncclick/formatting.py000066400000000000000000000230021507140761400225630ustar00rootroot00000000000000from __future__ import annotations import collections.abc as cabc from contextlib import contextmanager from gettext import gettext as _ from ._compat import term_len from .parser import _split_opt # Can force a width. This is used by the test system FORCED_WIDTH: int | None = None def measure_table(rows: cabc.Iterable[tuple[str, str]]) -> tuple[int, ...]: widths: dict[int, int] = {} for row in rows: for idx, col in enumerate(row): widths[idx] = max(widths.get(idx, 0), term_len(col)) return tuple(y for x, y in sorted(widths.items())) def iter_rows( rows: cabc.Iterable[tuple[str, str]], col_count: int ) -> cabc.Iterator[tuple[str, ...]]: for row in rows: yield row + ("",) * (col_count - len(row)) def wrap_text( text: str, width: int = 78, initial_indent: str = "", subsequent_indent: str = "", preserve_paragraphs: bool = False, ) -> str: """A helper function that intelligently wraps text. By default, it assumes that it operates on a single paragraph of text but if the `preserve_paragraphs` parameter is provided it will intelligently handle paragraphs (defined by two empty lines). If paragraphs are handled, a paragraph can be prefixed with an empty line containing the ``\\b`` character (``\\x08``) to indicate that no rewrapping should happen in that block. :param text: the text that should be rewrapped. :param width: the maximum width for the text. :param initial_indent: the initial indent that should be placed on the first line as a string. :param subsequent_indent: the indent string that should be placed on each consecutive line. :param preserve_paragraphs: if this flag is set then the wrapping will intelligently handle paragraphs. """ from ._textwrap import TextWrapper text = text.expandtabs() wrapper = TextWrapper( width, initial_indent=initial_indent, subsequent_indent=subsequent_indent, replace_whitespace=False, ) if not preserve_paragraphs: return wrapper.fill(text) p: list[tuple[int, bool, str]] = [] buf: list[str] = [] indent = None def _flush_par() -> None: if not buf: return if buf[0].strip() == "\b": p.append((indent or 0, True, "\n".join(buf[1:]))) else: p.append((indent or 0, False, " ".join(buf))) del buf[:] for line in text.splitlines(): if not line: _flush_par() indent = None else: if indent is None: orig_len = term_len(line) line = line.lstrip() indent = orig_len - term_len(line) buf.append(line) _flush_par() rv = [] for indent, raw, text in p: with wrapper.extra_indent(" " * indent): if raw: rv.append(wrapper.indent_only(text)) else: rv.append(wrapper.fill(text)) return "\n\n".join(rv) class HelpFormatter: """This class helps with formatting text-based help pages. It's usually just needed for very special internal cases, but it's also exposed so that developers can write their own fancy outputs. At present, it always writes into memory. :param indent_increment: the additional increment for each level. :param width: the width for the text. This defaults to the terminal width clamped to a maximum of 78. """ def __init__( self, indent_increment: int = 2, width: int | None = None, max_width: int | None = None, ) -> None: self.indent_increment = indent_increment if max_width is None: max_width = 80 if width is None: import shutil width = FORCED_WIDTH if width is None: width = max(min(shutil.get_terminal_size().columns, max_width) - 2, 50) self.width = width self.current_indent: int = 0 self.buffer: list[str] = [] def write(self, string: str) -> None: """Writes a unicode string into the internal buffer.""" self.buffer.append(string) def indent(self) -> None: """Increases the indentation.""" self.current_indent += self.indent_increment def dedent(self) -> None: """Decreases the indentation.""" self.current_indent -= self.indent_increment def write_usage(self, prog: str, args: str = "", prefix: str | None = None) -> None: """Writes a usage line into the buffer. :param prog: the program name. :param args: whitespace separated list of arguments. :param prefix: The prefix for the first line. Defaults to ``"Usage: "``. """ if prefix is None: prefix = f"{_('Usage:')} " usage_prefix = f"{prefix:>{self.current_indent}}{prog} " text_width = self.width - self.current_indent if text_width >= (term_len(usage_prefix) + 20): # The arguments will fit to the right of the prefix. indent = " " * term_len(usage_prefix) self.write( wrap_text( args, text_width, initial_indent=usage_prefix, subsequent_indent=indent, ) ) else: # The prefix is too long, put the arguments on the next line. self.write(usage_prefix) self.write("\n") indent = " " * (max(self.current_indent, term_len(prefix)) + 4) self.write( wrap_text( args, text_width, initial_indent=indent, subsequent_indent=indent ) ) self.write("\n") def write_heading(self, heading: str) -> None: """Writes a heading into the buffer.""" self.write(f"{'':>{self.current_indent}}{heading}:\n") def write_paragraph(self) -> None: """Writes a paragraph into the buffer.""" if self.buffer: self.write("\n") def write_text(self, text: str) -> None: """Writes re-indented text into the buffer. This rewraps and preserves paragraphs. """ indent = " " * self.current_indent self.write( wrap_text( text, self.width, initial_indent=indent, subsequent_indent=indent, preserve_paragraphs=True, ) ) self.write("\n") def write_dl( self, rows: cabc.Sequence[tuple[str, str]], col_max: int = 30, col_spacing: int = 2, ) -> None: """Writes a definition list into the buffer. This is how options and commands are usually formatted. :param rows: a list of two item tuples for the terms and values. :param col_max: the maximum width of the first column. :param col_spacing: the number of spaces between the first and second column. """ rows = list(rows) widths = measure_table(rows) if len(widths) != 2: raise TypeError("Expected two columns for definition list") first_col = min(widths[0], col_max) + col_spacing for first, second in iter_rows(rows, len(widths)): self.write(f"{'':>{self.current_indent}}{first}") if not second: self.write("\n") continue if term_len(first) <= first_col - col_spacing: self.write(" " * (first_col - term_len(first))) else: self.write("\n") self.write(" " * (first_col + self.current_indent)) text_width = max(self.width - first_col - 2, 10) wrapped_text = wrap_text(second, text_width, preserve_paragraphs=True) lines = wrapped_text.splitlines() if lines: self.write(f"{lines[0]}\n") for line in lines[1:]: self.write(f"{'':>{first_col + self.current_indent}}{line}\n") else: self.write("\n") @contextmanager def section(self, name: str) -> cabc.Iterator[None]: """Helpful context manager that writes a paragraph, a heading, and the indents. :param name: the section name that is written as heading. """ self.write_paragraph() self.write_heading(name) self.indent() try: yield finally: self.dedent() @contextmanager def indentation(self) -> cabc.Iterator[None]: """A context manager that increases the indentation.""" self.indent() try: yield finally: self.dedent() def getvalue(self) -> str: """Returns the buffer contents.""" return "".join(self.buffer) def join_options(options: cabc.Sequence[str]) -> tuple[str, bool]: """Given a list of option strings this joins them in the most appropriate way and returns them in the form ``(formatted_string, any_prefix_is_slash)`` where the second item in the tuple is a flag that indicates if any of the option prefixes was a slash. """ rv = [] any_prefix_is_slash = False for opt in options: prefix = _split_opt(opt)[0] if prefix == "/": any_prefix_is_slash = True rv.append((len(prefix), opt)) rv.sort(key=lambda x: x[0]) return ", ".join(x[1] for x in rv), any_prefix_is_slash asyncclick-8.3.0.5-async/src/asyncclick/globals.py000066400000000000000000000036031507140761400220410ustar00rootroot00000000000000from __future__ import annotations import typing as t from threading import local if t.TYPE_CHECKING: from .core import Context _local = local() @t.overload def get_current_context(silent: t.Literal[False] = False) -> Context: ... @t.overload def get_current_context(silent: bool = ...) -> Context | None: ... def get_current_context(silent: bool = False) -> Context | None: """Returns the current click context. This can be used as a way to access the current context object from anywhere. This is a more implicit alternative to the :func:`pass_context` decorator. This function is primarily useful for helpers such as :func:`echo` which might be interested in changing its behavior based on the current context. To push the current context, :meth:`Context.scope` can be used. .. versionadded:: 5.0 :param silent: if set to `True` the return value is `None` if no context is available. The default behavior is to raise a :exc:`RuntimeError`. """ try: return t.cast("Context", _local.stack[-1]) except (AttributeError, IndexError) as e: if not silent: raise RuntimeError("There is no active click context.") from e return None def push_context(ctx: Context) -> None: """Pushes a new context to the current stack.""" _local.__dict__.setdefault("stack", []).append(ctx) def pop_context() -> None: """Removes the top level from the stack.""" _local.stack.pop() def resolve_color_default(color: bool | None = None) -> bool | None: """Internal helper to get the default value of the color flag. If a value is passed it's returned unchanged, otherwise it's looked up from the current context. """ if color is not None: return color ctx = get_current_context(silent=True) if ctx is not None: return ctx.color return None asyncclick-8.3.0.5-async/src/asyncclick/parser.py000066400000000000000000000451701507140761400217170ustar00rootroot00000000000000""" This module started out as largely a copy paste from the stdlib's optparse module with the features removed that we do not need from optparse because we implement them in Click on a higher level (for instance type handling, help formatting and a lot more). The plan is to remove more and more from here over time. The reason this is a different module and not optparse from the stdlib is that there are differences in 2.x and 3.x about the error messages generated and optparse in the stdlib uses gettext for no good reason and might cause us issues. Click uses parts of optparse written by Gregory P. Ward and maintained by the Python Software Foundation. This is limited to code in parser.py. Copyright 2001-2006 Gregory P. Ward. All rights reserved. Copyright 2002-2006 Python Software Foundation. All rights reserved. """ # This code uses parts of optparse written by Gregory P. Ward and # maintained by the Python Software Foundation. # Copyright 2001-2006 Gregory P. Ward # Copyright 2002-2006 Python Software Foundation from __future__ import annotations import collections.abc as cabc import typing as t from collections import deque from gettext import gettext as _ from gettext import ngettext from ._utils import FLAG_NEEDS_VALUE from ._utils import UNSET from .exceptions import BadArgumentUsage from .exceptions import BadOptionUsage from .exceptions import NoSuchOption from .exceptions import UsageError if t.TYPE_CHECKING: from ._utils import T_FLAG_NEEDS_VALUE from ._utils import T_UNSET from .core import Argument as CoreArgument from .core import Context from .core import Option as CoreOption from .core import Parameter as CoreParameter V = t.TypeVar("V") def _unpack_args( args: cabc.Sequence[str], nargs_spec: cabc.Sequence[int] ) -> tuple[cabc.Sequence[str | cabc.Sequence[str | None] | None], list[str]]: """Given an iterable of arguments and an iterable of nargs specifications, it returns a tuple with all the unpacked arguments at the first index and all remaining arguments as the second. The nargs specification is the number of arguments that should be consumed or `-1` to indicate that this position should eat up all the remainders. Missing items are filled with ``UNSET``. """ args = deque(args) nargs_spec = deque(nargs_spec) rv: list[str | tuple[str | T_UNSET, ...] | T_UNSET] = [] spos: int | None = None def _fetch(c: deque[V]) -> V | T_UNSET: try: if spos is None: return c.popleft() else: return c.pop() except IndexError: return UNSET while nargs_spec: nargs = _fetch(nargs_spec) if nargs is None: continue if nargs == 1: rv.append(_fetch(args)) # type: ignore[arg-type] elif nargs > 1: x = [_fetch(args) for _ in range(nargs)] # If we're reversed, we're pulling in the arguments in reverse, # so we need to turn them around. if spos is not None: x.reverse() rv.append(tuple(x)) elif nargs < 0: if spos is not None: raise TypeError("Cannot have two nargs < 0") spos = len(rv) rv.append(UNSET) # spos is the position of the wildcard (star). If it's not `None`, # we fill it with the remainder. if spos is not None: rv[spos] = tuple(args) args = [] rv[spos + 1 :] = reversed(rv[spos + 1 :]) return tuple(rv), list(args) def _split_opt(opt: str) -> tuple[str, str]: first = opt[:1] if first.isalnum(): return "", opt if opt[1:2] == first: return opt[:2], opt[2:] return first, opt[1:] def _normalize_opt(opt: str, ctx: Context | None) -> str: if ctx is None or ctx.token_normalize_func is None: return opt prefix, opt = _split_opt(opt) return f"{prefix}{ctx.token_normalize_func(opt)}" class _Option: def __init__( self, obj: CoreOption, opts: cabc.Sequence[str], dest: str | None, action: str | None = None, nargs: int = 1, const: t.Any | None = None, ): self._short_opts = [] self._long_opts = [] self.prefixes: set[str] = set() for opt in opts: prefix, value = _split_opt(opt) if not prefix: raise ValueError(f"Invalid start character for option ({opt})") self.prefixes.add(prefix[0]) if len(prefix) == 1 and len(value) == 1: self._short_opts.append(opt) else: self._long_opts.append(opt) self.prefixes.add(prefix) if action is None: action = "store" self.dest = dest self.action = action self.nargs = nargs self.const = const self.obj = obj @property def takes_value(self) -> bool: return self.action in ("store", "append") def process(self, value: t.Any, state: _ParsingState) -> None: if self.action == "store": state.opts[self.dest] = value # type: ignore elif self.action == "store_const": state.opts[self.dest] = self.const # type: ignore elif self.action == "append": state.opts.setdefault(self.dest, []).append(value) # type: ignore elif self.action == "append_const": state.opts.setdefault(self.dest, []).append(self.const) # type: ignore elif self.action == "count": state.opts[self.dest] = state.opts.get(self.dest, 0) + 1 # type: ignore else: raise ValueError(f"unknown action '{self.action}'") state.order.append(self.obj) class _Argument: def __init__(self, obj: CoreArgument, dest: str | None, nargs: int = 1): self.dest = dest self.nargs = nargs self.obj = obj def process( self, value: str | cabc.Sequence[str | None] | None | T_UNSET, state: _ParsingState, ) -> None: if self.nargs > 1: assert isinstance(value, cabc.Sequence) holes = sum(1 for x in value if x is UNSET) if holes == len(value): value = UNSET elif holes != 0: raise BadArgumentUsage( _("Argument {name!r} takes {nargs} values.").format( name=self.dest, nargs=self.nargs ) ) # We failed to collect any argument value so we consider the argument as unset. if value == (): value = UNSET state.opts[self.dest] = value # type: ignore state.order.append(self.obj) class _ParsingState: def __init__(self, rargs: list[str]) -> None: self.opts: dict[str, t.Any] = {} self.largs: list[str] = [] self.rargs = rargs self.order: list[CoreParameter] = [] class _OptionParser: """The option parser is an internal class that is ultimately used to parse options and arguments. It's modelled after optparse and brings a similar but vastly simplified API. It should generally not be used directly as the high level Click classes wrap it for you. It's not nearly as extensible as optparse or argparse as it does not implement features that are implemented on a higher level (such as types or defaults). :param ctx: optionally the :class:`~click.Context` where this parser should go with. .. deprecated:: 8.2 Will be removed in Click 9.0. """ def __init__(self, ctx: Context | None = None) -> None: #: The :class:`~click.Context` for this parser. This might be #: `None` for some advanced use cases. self.ctx = ctx #: This controls how the parser deals with interspersed arguments. #: If this is set to `False`, the parser will stop on the first #: non-option. Click uses this to implement nested subcommands #: safely. self.allow_interspersed_args: bool = True #: This tells the parser how to deal with unknown options. By #: default it will error out (which is sensible), but there is a #: second mode where it will ignore it and continue processing #: after shifting all the unknown options into the resulting args. self.ignore_unknown_options: bool = False if ctx is not None: self.allow_interspersed_args = ctx.allow_interspersed_args self.ignore_unknown_options = ctx.ignore_unknown_options self._short_opt: dict[str, _Option] = {} self._long_opt: dict[str, _Option] = {} self._opt_prefixes = {"-", "--"} self._args: list[_Argument] = [] def add_option( self, obj: CoreOption, opts: cabc.Sequence[str], dest: str | None, action: str | None = None, nargs: int = 1, const: t.Any | None = None, ) -> None: """Adds a new option named `dest` to the parser. The destination is not inferred (unlike with optparse) and needs to be explicitly provided. Action can be any of ``store``, ``store_const``, ``append``, ``append_const`` or ``count``. The `obj` can be used to identify the option in the order list that is returned from the parser. """ opts = [_normalize_opt(opt, self.ctx) for opt in opts] option = _Option(obj, opts, dest, action=action, nargs=nargs, const=const) self._opt_prefixes.update(option.prefixes) for opt in option._short_opts: self._short_opt[opt] = option for opt in option._long_opts: self._long_opt[opt] = option def add_argument(self, obj: CoreArgument, dest: str | None, nargs: int = 1) -> None: """Adds a positional argument named `dest` to the parser. The `obj` can be used to identify the option in the order list that is returned from the parser. """ self._args.append(_Argument(obj, dest=dest, nargs=nargs)) async def parse_args( self, args: list[str] ) -> tuple[dict[str, t.Any], list[str], list[CoreParameter]]: """Parses positional arguments and returns ``(values, args, order)`` for the parsed options and arguments as well as the leftover arguments if there are any. The order is a list of objects as they appear on the command line. If arguments appear multiple times they will be memorized multiple times as well. """ state = _ParsingState(args) try: await self._process_args_for_options(state) self._process_args_for_args(state) except UsageError: if self.ctx is None or not self.ctx.resilient_parsing: raise return state.opts, state.largs, state.order def _process_args_for_args(self, state: _ParsingState) -> None: pargs, args = _unpack_args( state.largs + state.rargs, [x.nargs for x in self._args] ) for idx, arg in enumerate(self._args): arg.process(pargs[idx], state) state.largs = args state.rargs = [] async def _process_args_for_options(self, state: _ParsingState) -> None: while state.rargs: arg = state.rargs.pop(0) arglen = len(arg) # Double dashes always handled explicitly regardless of what # prefixes are valid. if arg == "--": return elif arg[:1] in self._opt_prefixes and arglen > 1: await self._process_opts(arg, state) elif self.allow_interspersed_args: state.largs.append(arg) else: state.rargs.insert(0, arg) return # Say this is the original argument list: # [arg0, arg1, ..., arg(i-1), arg(i), arg(i+1), ..., arg(N-1)] # ^ # (we are about to process arg(i)). # # Then rargs is [arg(i), ..., arg(N-1)] and largs is a *subset* of # [arg0, ..., arg(i-1)] (any options and their arguments will have # been removed from largs). # # The while loop will usually consume 1 or more arguments per pass. # If it consumes 1 (eg. arg is an option that takes no arguments), # then after _process_arg() is done the situation is: # # largs = subset of [arg0, ..., arg(i)] # rargs = [arg(i+1), ..., arg(N-1)] # # If allow_interspersed_args is false, largs will always be # *empty* -- still a subset of [arg0, ..., arg(i-1)], but # not a very interesting subset! async def _match_long_opt( self, opt: str, explicit_value: str | None, state: _ParsingState ) -> None: if opt not in self._long_opt: from difflib import get_close_matches possibilities = get_close_matches(opt, self._long_opt) raise NoSuchOption(opt, possibilities=possibilities, ctx=self.ctx) option = self._long_opt[opt] if option.takes_value: # At this point it's safe to modify rargs by injecting the # explicit value, because no exception is raised in this # branch. This means that the inserted value will be fully # consumed. if explicit_value is not None: state.rargs.insert(0, explicit_value) value = self._get_value_from_state(opt, option, state) elif explicit_value is not None: raise BadOptionUsage( opt, _("Option {name!r} does not take a value.").format(name=opt) ) else: value = UNSET option.process(value, state) async def _match_short_opt(self, arg: str, state: _ParsingState) -> None: stop = False i = 1 prefix = arg[0] unknown_options = [] for ch in arg[1:]: opt = _normalize_opt(f"{prefix}{ch}", self.ctx) option = self._short_opt.get(opt) i += 1 if not option: if self.ignore_unknown_options: unknown_options.append(ch) continue raise NoSuchOption(opt, ctx=self.ctx) if option.takes_value: # Any characters left in arg? Pretend they're the # next arg, and stop consuming characters of arg. if i < len(arg): state.rargs.insert(0, arg[i:]) stop = True value = self._get_value_from_state(opt, option, state) else: value = UNSET option.process(value, state) if stop: break # If we got any unknown options we recombine the string of the # remaining options and re-attach the prefix, then report that # to the state as new larg. This way there is basic combinatorics # that can be achieved while still ignoring unknown arguments. if self.ignore_unknown_options and unknown_options: state.largs.append(f"{prefix}{''.join(unknown_options)}") def _get_value_from_state( self, option_name: str, option: _Option, state: _ParsingState ) -> str | cabc.Sequence[str] | T_FLAG_NEEDS_VALUE: nargs = option.nargs value: str | cabc.Sequence[str] | T_FLAG_NEEDS_VALUE if len(state.rargs) < nargs: if option.obj._flag_needs_value: # Option allows omitting the value. value = FLAG_NEEDS_VALUE else: raise BadOptionUsage( option_name, ngettext( "Option {name!r} requires an argument.", "Option {name!r} requires {nargs} arguments.", nargs, ).format(name=option_name, nargs=nargs), ) elif nargs == 1: next_rarg = state.rargs[0] if ( option.obj._flag_needs_value and isinstance(next_rarg, str) and next_rarg[:1] in self._opt_prefixes and len(next_rarg) > 1 ): # The next arg looks like the start of an option, don't # use it as the value if omitting the value is allowed. value = FLAG_NEEDS_VALUE else: value = state.rargs.pop(0) else: value = tuple(state.rargs[:nargs]) del state.rargs[:nargs] return value async def _process_opts(self, arg: str, state: _ParsingState) -> None: explicit_value = None # Long option handling happens in two parts. The first part is # supporting explicitly attached values. In any case, we will try # to long match the option first. if "=" in arg: long_opt, explicit_value = arg.split("=", 1) else: long_opt = arg norm_long_opt = _normalize_opt(long_opt, self.ctx) # At this point we will match the (assumed) long option through # the long option matching code. Note that this allows options # like "-foo" to be matched as long options. try: await self._match_long_opt(norm_long_opt, explicit_value, state) except NoSuchOption: # At this point the long option matching failed, and we need # to try with short options. However there is a special rule # which says, that if we have a two character options prefix # (applies to "--foo" for instance), we do not dispatch to the # short option code and will instead raise the no option # error. if arg[:2] not in self._opt_prefixes: await self._match_short_opt(arg, state) return if not self.ignore_unknown_options: raise state.largs.append(arg) def __getattr__(name: str) -> object: import warnings if name in { "OptionParser", "Argument", "Option", "split_opt", "normalize_opt", "ParsingState", }: warnings.warn( f"'parser.{name}' is deprecated and will be removed in Click 9.0." " The old parser is available in 'optparse'.", DeprecationWarning, stacklevel=2, ) return globals()[f"_{name}"] if name == "split_arg_string": from .shell_completion import split_arg_string warnings.warn( "Importing 'parser.split_arg_string' is deprecated, it will only be" " available in 'shell_completion' in Click 9.0.", DeprecationWarning, stacklevel=2, ) return split_arg_string raise AttributeError(name) asyncclick-8.3.0.5-async/src/asyncclick/py.typed000066400000000000000000000000001507140761400215270ustar00rootroot00000000000000asyncclick-8.3.0.5-async/src/asyncclick/shell_completion.py000066400000000000000000000511521507140761400237600ustar00rootroot00000000000000from __future__ import annotations import collections.abc as cabc import os import re import typing as t from gettext import gettext as _ from .core import Argument from .core import Command from .core import Context from .core import Group from .core import Option from .core import Parameter from .core import ParameterSource from .utils import echo async def shell_complete( cli: Command, ctx_args: cabc.MutableMapping[str, t.Any], prog_name: str, complete_var: str, instruction: str, ) -> int: """Perform shell completion for the given CLI program. :param cli: Command being called. :param ctx_args: Extra arguments to pass to ``cli.make_context``. :param prog_name: Name of the executable in the shell. :param complete_var: Name of the environment variable that holds the completion instruction. :param instruction: Value of ``complete_var`` with the completion instruction and shell, in the form ``instruction_shell``. :return: Status code to exit with. """ shell, _, instruction = instruction.partition("_") comp_cls = get_completion_class(shell) if comp_cls is None: return 1 comp = comp_cls(cli, ctx_args, prog_name, complete_var) if instruction == "source": echo(comp.source()) return 0 if instruction == "complete": echo(await comp.complete()) return 0 return 1 class CompletionItem: """Represents a completion value and metadata about the value. The default metadata is ``type`` to indicate special shell handling, and ``help`` if a shell supports showing a help string next to the value. Arbitrary parameters can be passed when creating the object, and accessed using ``item.attr``. If an attribute wasn't passed, accessing it returns ``None``. :param value: The completion suggestion. :param type: Tells the shell script to provide special completion support for the type. Click uses ``"dir"`` and ``"file"``. :param help: String shown next to the value if supported. :param kwargs: Arbitrary metadata. The built-in implementations don't use this, but custom type completions paired with custom shell support could use it. """ __slots__ = ("value", "type", "help", "_info") def __init__( self, value: t.Any, type: str = "plain", help: str | None = None, **kwargs: t.Any, ) -> None: self.value: t.Any = value self.type: str = type self.help: str | None = help self._info = kwargs def __getattr__(self, name: str) -> t.Any: return self._info.get(name) # Only Bash >= 4.4 has the nosort option. _SOURCE_BASH = """\ %(complete_func)s() { local IFS=$'\\n' local response response=$(env COMP_WORDS="${COMP_WORDS[*]}" COMP_CWORD=$COMP_CWORD \ %(complete_var)s=bash_complete $1) for completion in $response; do IFS=',' read type value <<< "$completion" if [[ $type == 'dir' ]]; then COMPREPLY=() compopt -o dirnames elif [[ $type == 'file' ]]; then COMPREPLY=() compopt -o default elif [[ $type == 'plain' ]]; then COMPREPLY+=($value) fi done return 0 } %(complete_func)s_setup() { complete -o nosort -F %(complete_func)s %(prog_name)s } %(complete_func)s_setup; """ # See ZshComplete.format_completion below, and issue #2703, before # changing this script. # # (TL;DR: _describe is picky about the format, but this Zsh script snippet # is already widely deployed. So freeze this script, and use clever-ish # handling of colons in ZshComplet.format_completion.) _SOURCE_ZSH = """\ #compdef %(prog_name)s %(complete_func)s() { local -a completions local -a completions_with_descriptions local -a response (( ! $+commands[%(prog_name)s] )) && return 1 response=("${(@f)$(env COMP_WORDS="${words[*]}" COMP_CWORD=$((CURRENT-1)) \ %(complete_var)s=zsh_complete %(prog_name)s)}") for type key descr in ${response}; do if [[ "$type" == "plain" ]]; then if [[ "$descr" == "_" ]]; then completions+=("$key") else completions_with_descriptions+=("$key":"$descr") fi elif [[ "$type" == "dir" ]]; then _path_files -/ elif [[ "$type" == "file" ]]; then _path_files -f fi done if [ -n "$completions_with_descriptions" ]; then _describe -V unsorted completions_with_descriptions -U fi if [ -n "$completions" ]; then compadd -U -V unsorted -a completions fi } if [[ $zsh_eval_context[-1] == loadautofunc ]]; then # autoload from fpath, call function directly %(complete_func)s "$@" else # eval/source/. command, register function for later compdef %(complete_func)s %(prog_name)s fi """ _SOURCE_FISH = """\ function %(complete_func)s; set -l response (env %(complete_var)s=fish_complete COMP_WORDS=(commandline -cp) \ COMP_CWORD=(commandline -t) %(prog_name)s); for completion in $response; set -l metadata (string split "," $completion); if test $metadata[1] = "dir"; __fish_complete_directories $metadata[2]; else if test $metadata[1] = "file"; __fish_complete_path $metadata[2]; else if test $metadata[1] = "plain"; echo $metadata[2]; end; end; end; complete --no-files --command %(prog_name)s --arguments \ "(%(complete_func)s)"; """ class ShellComplete: """Base class for providing shell completion support. A subclass for a given shell will override attributes and methods to implement the completion instructions (``source`` and ``complete``). :param cli: Command being called. :param prog_name: Name of the executable in the shell. :param complete_var: Name of the environment variable that holds the completion instruction. .. versionadded:: 8.0 """ name: t.ClassVar[str] """Name to register the shell as with :func:`add_completion_class`. This is used in completion instructions (``{name}_source`` and ``{name}_complete``). """ source_template: t.ClassVar[str] """Completion script template formatted by :meth:`source`. This must be provided by subclasses. """ def __init__( self, cli: Command, ctx_args: cabc.MutableMapping[str, t.Any], prog_name: str, complete_var: str, ) -> None: self.cli = cli self.ctx_args = ctx_args self.prog_name = prog_name self.complete_var = complete_var @property def func_name(self) -> str: """The name of the shell function defined by the completion script. """ safe_name = re.sub(r"\W*", "", self.prog_name.replace("-", "_"), flags=re.ASCII) return f"_{safe_name}_completion" def source_vars(self) -> dict[str, t.Any]: """Vars for formatting :attr:`source_template`. By default this provides ``complete_func``, ``complete_var``, and ``prog_name``. """ return { "complete_func": self.func_name, "complete_var": self.complete_var, "prog_name": self.prog_name, } def source(self) -> str: """Produce the shell script that defines the completion function. By default this ``%``-style formats :attr:`source_template` with the dict returned by :meth:`source_vars`. """ return self.source_template % self.source_vars() def get_completion_args(self) -> tuple[list[str], str]: """Use the env vars defined by the shell script to return a tuple of ``args, incomplete``. This must be implemented by subclasses. """ raise NotImplementedError async def get_completions( self, args: list[str], incomplete: str ) -> list[CompletionItem]: """Determine the context and last complete command or parameter from the complete args. Call that object's ``shell_complete`` method to get the completions for the incomplete value. :param args: List of complete args before the incomplete value. :param incomplete: Value being completed. May be empty. """ ctx = await _resolve_context(self.cli, self.ctx_args, self.prog_name, args) obj, incomplete = _resolve_incomplete(ctx, args, incomplete) return obj.shell_complete(ctx, incomplete) def format_completion(self, item: CompletionItem) -> str: """Format a completion item into the form recognized by the shell script. This must be implemented by subclasses. :param item: Completion item to format. """ raise NotImplementedError async def complete(self) -> str: """Produce the completion data to send back to the shell. By default this calls :meth:`get_completion_args`, gets the completions, then calls :meth:`format_completion` for each completion. """ args, incomplete = self.get_completion_args() completions = await self.get_completions(args, incomplete) out = [self.format_completion(item) for item in completions] return "\n".join(out) class BashComplete(ShellComplete): """Shell completion for Bash.""" name = "bash" source_template = _SOURCE_BASH @staticmethod def _check_version() -> None: import shutil import subprocess bash_exe = shutil.which("bash") if bash_exe is None: match = None else: output = subprocess.run( [bash_exe, "--norc", "-c", 'echo "${BASH_VERSION}"'], stdout=subprocess.PIPE, ) match = re.search(r"^(\d+)\.(\d+)\.\d+", output.stdout.decode()) if match is not None: major, minor = match.groups() if major < "4" or major == "4" and minor < "4": echo( _( "Shell completion is not supported for Bash" " versions older than 4.4." ), err=True, ) else: echo( _("Couldn't detect Bash version, shell completion is not supported."), err=True, ) def source(self) -> str: self._check_version() return super().source() def get_completion_args(self) -> tuple[list[str], str]: cwords = split_arg_string(os.environ["COMP_WORDS"]) cword = int(os.environ["COMP_CWORD"]) args = cwords[1:cword] try: incomplete = cwords[cword] except IndexError: incomplete = "" return args, incomplete def format_completion(self, item: CompletionItem) -> str: return f"{item.type},{item.value}" class ZshComplete(ShellComplete): """Shell completion for Zsh.""" name = "zsh" source_template = _SOURCE_ZSH def get_completion_args(self) -> tuple[list[str], str]: cwords = split_arg_string(os.environ["COMP_WORDS"]) cword = int(os.environ["COMP_CWORD"]) args = cwords[1:cword] try: incomplete = cwords[cword] except IndexError: incomplete = "" return args, incomplete def format_completion(self, item: CompletionItem) -> str: help_ = item.help or "_" # The zsh completion script uses `_describe` on items with help # texts (which splits the item help from the item value at the # first unescaped colon) and `compadd` on items without help # text (which uses the item value as-is and does not support # colon escaping). So escape colons in the item value if and # only if the item help is not the sentinel "_" value, as used # by the completion script. # # (The zsh completion script is potentially widely deployed, and # thus harder to fix than this method.) # # See issue #1812 and issue #2703 for further context. value = item.value.replace(":", r"\:") if help_ != "_" else item.value return f"{item.type}\n{value}\n{help_}" class FishComplete(ShellComplete): """Shell completion for Fish.""" name = "fish" source_template = _SOURCE_FISH def get_completion_args(self) -> tuple[list[str], str]: cwords = split_arg_string(os.environ["COMP_WORDS"]) incomplete = os.environ["COMP_CWORD"] if incomplete: incomplete = split_arg_string(incomplete)[0] args = cwords[1:] # Fish stores the partial word in both COMP_WORDS and # COMP_CWORD, remove it from complete args. if incomplete and args and args[-1] == incomplete: args.pop() return args, incomplete def format_completion(self, item: CompletionItem) -> str: if item.help: return f"{item.type},{item.value}\t{item.help}" return f"{item.type},{item.value}" ShellCompleteType = t.TypeVar("ShellCompleteType", bound="type[ShellComplete]") _available_shells: dict[str, type[ShellComplete]] = { "bash": BashComplete, "fish": FishComplete, "zsh": ZshComplete, } def add_completion_class( cls: ShellCompleteType, name: str | None = None ) -> ShellCompleteType: """Register a :class:`ShellComplete` subclass under the given name. The name will be provided by the completion instruction environment variable during completion. :param cls: The completion class that will handle completion for the shell. :param name: Name to register the class under. Defaults to the class's ``name`` attribute. """ if name is None: name = cls.name _available_shells[name] = cls return cls def get_completion_class(shell: str) -> type[ShellComplete] | None: """Look up a registered :class:`ShellComplete` subclass by the name provided by the completion instruction environment variable. If the name isn't registered, returns ``None``. :param shell: Name the class is registered under. """ return _available_shells.get(shell) def split_arg_string(string: str) -> list[str]: """Split an argument string as with :func:`shlex.split`, but don't fail if the string is incomplete. Ignores a missing closing quote or incomplete escape sequence and uses the partial token as-is. .. code-block:: python split_arg_string("example 'my file") ["example", "my file"] split_arg_string("example my\\") ["example", "my"] :param string: String to split. .. versionchanged:: 8.2 Moved to ``shell_completion`` from ``parser``. """ import shlex lex = shlex.shlex(string, posix=True) lex.whitespace_split = True lex.commenters = "" out = [] try: for token in lex: out.append(token) except ValueError: # Raised when end-of-string is reached in an invalid state. Use # the partial token as-is. The quote or escape character is in # lex.state, not lex.token. out.append(lex.token) return out def _is_incomplete_argument(ctx: Context, param: Parameter) -> bool: """Determine if the given parameter is an argument that can still accept values. :param ctx: Invocation context for the command represented by the parsed complete args. :param param: Argument object being checked. """ if not isinstance(param, Argument): return False assert param.name is not None # Will be None if expose_value is False. value = ctx.params.get(param.name) return ( param.nargs == -1 or ctx.get_parameter_source(param.name) is not ParameterSource.COMMANDLINE or ( param.nargs > 1 and isinstance(value, (tuple, list)) and len(value) < param.nargs ) ) def _start_of_option(ctx: Context, value: str) -> bool: """Check if the value looks like the start of an option.""" if not value: return False c = value[0] return c in ctx._opt_prefixes def _is_incomplete_option(ctx: Context, args: list[str], param: Parameter) -> bool: """Determine if the given parameter is an option that needs a value. :param args: List of complete args before the incomplete value. :param param: Option object being checked. """ if not isinstance(param, Option): return False if param.is_flag or param.count: return False last_option = None for index, arg in enumerate(reversed(args)): if index + 1 > param.nargs: break if _start_of_option(ctx, arg): last_option = arg break return last_option is not None and last_option in param.opts async def _resolve_context( cli: Command, ctx_args: cabc.MutableMapping[str, t.Any], prog_name: str, args: list[str], ) -> Context: """Produce the context hierarchy starting with the command and traversing the complete arguments. This only follows the commands, it doesn't trigger input prompts or callbacks. :param cli: Command being called. :param prog_name: Name of the executable in the shell. :param args: List of complete args before the incomplete value. """ ctx_args["resilient_parsing"] = True async with await cli.make_context(prog_name, args.copy(), **ctx_args) as ctx: args = ctx._protected_args + ctx.args while args: command = ctx.command if isinstance(command, Group): if not command.chain: name, cmd, args = await command.resolve_command(ctx, args) if cmd is None: return ctx async with await cmd.make_context( name, args, parent=ctx, resilient_parsing=True ) as sub_ctx: ctx = sub_ctx args = ctx._protected_args + ctx.args else: sub_ctx = ctx while args: name, cmd, args = await command.resolve_command(ctx, args) if cmd is None: return ctx async with await cmd.make_context( name, args, parent=ctx, allow_extra_args=True, allow_interspersed_args=False, resilient_parsing=True, ) as sub_sub_ctx: sub_ctx = sub_sub_ctx args = sub_ctx.args ctx = sub_ctx args = [*sub_ctx._protected_args, *sub_ctx.args] else: break return ctx def _resolve_incomplete( ctx: Context, args: list[str], incomplete: str ) -> tuple[Command | Parameter, str]: """Find the Click object that will handle the completion of the incomplete value. Return the object and the incomplete value. :param ctx: Invocation context for the command represented by the parsed complete args. :param args: List of complete args before the incomplete value. :param incomplete: Value being completed. May be empty. """ # Different shells treat an "=" between a long option name and # value differently. Might keep the value joined, return the "=" # as a separate item, or return the split name and value. Always # split and discard the "=" to make completion easier. if incomplete == "=": incomplete = "" elif "=" in incomplete and _start_of_option(ctx, incomplete): name, _, incomplete = incomplete.partition("=") args.append(name) # The "--" marker tells Click to stop treating values as options # even if they start with the option character. If it hasn't been # given and the incomplete arg looks like an option, the current # command will provide option name completions. if "--" not in args and _start_of_option(ctx, incomplete): return ctx.command, incomplete params = ctx.command.get_params(ctx) # If the last complete arg is an option name with an incomplete # value, the option will provide value completions. for param in params: if _is_incomplete_option(ctx, args, param): return param, incomplete # It's not an option name or value. The first argument without a # parsed value will provide value completions. for param in params: if _is_incomplete_argument(ctx, param): return param, incomplete # There were no unparsed arguments, the command may be a group that # will provide command name completions. return ctx.command, incomplete asyncclick-8.3.0.5-async/src/asyncclick/termui.py000066400000000000000000000776201507140761400217350ustar00rootroot00000000000000from __future__ import annotations import collections.abc as cabc import inspect import io import itertools import sys import typing as t from contextlib import AbstractContextManager from gettext import gettext as _ from inspect import iscoroutine from ._compat import isatty from ._compat import strip_ansi from .exceptions import Abort from .exceptions import UsageError from .globals import resolve_color_default from .types import Choice from .types import convert_type from .types import ParamType from .utils import echo from .utils import LazyFile if t.TYPE_CHECKING: from ._termui_impl import ProgressBar V = t.TypeVar("V") # The prompt functions to use. The doc tools currently override these # functions to customize how they work. visible_prompt_func: t.Callable[[str], str] = input _ansi_colors = { "black": 30, "red": 31, "green": 32, "yellow": 33, "blue": 34, "magenta": 35, "cyan": 36, "white": 37, "reset": 39, "bright_black": 90, "bright_red": 91, "bright_green": 92, "bright_yellow": 93, "bright_blue": 94, "bright_magenta": 95, "bright_cyan": 96, "bright_white": 97, } _ansi_reset_all = "\033[0m" def hidden_prompt_func(prompt: str) -> str: import getpass return getpass.getpass(prompt) def _build_prompt( text: str, suffix: str, show_default: bool = False, default: t.Any | None = None, show_choices: bool = True, type: ParamType | None = None, ) -> str: prompt = text if type is not None and show_choices and isinstance(type, Choice): prompt += f" ({', '.join(map(str, type.choices))})" if default is not None and show_default: prompt = f"{prompt} [{_format_default(default)}]" return f"{prompt}{suffix}" def _format_default(default: t.Any) -> t.Any: if isinstance(default, (io.IOBase, LazyFile)) and hasattr(default, "name"): return default.name return default async def prompt( text: str, default: t.Any | None = None, hide_input: bool = False, confirmation_prompt: bool | str = False, type: ParamType | t.Any | None = None, value_proc: t.Callable[[str], t.Any] | None = None, prompt_suffix: str = ": ", show_default: bool = True, err: bool = False, show_choices: bool = True, blocking: bool = True, ) -> t.Any: """Prompts a user for input. This is a convenience function that can be used to prompt a user for input later. If the user aborts the input by sending an interrupt signal, this function will catch it and raise a :exc:`Abort` exception. :param text: the text to show for the prompt. :param default: the default value to use if no input happens. If this is not given it will prompt until it's aborted. :param hide_input: if this is set to true then the input value will be hidden. :param confirmation_prompt: Prompt a second time to confirm the value. Can be set to a string instead of ``True`` to customize the message. :param type: the type to use to check the value against. :param value_proc: if this parameter is provided it's a function that is invoked instead of the type conversion to convert a value. :param prompt_suffix: a suffix that should be added to the prompt. :param show_default: shows or hides the default value in the prompt. :param err: if set to true the file defaults to ``stderr`` instead of ``stdout``, the same as with echo. :param show_choices: Show or hide choices if the passed type is a Choice. For example if type is a Choice of either day or week, show_choices is true and text is "Group by" then the prompt will be "Group by (day, week): ". :param blocking: if `False`, uses a thread to interact with the terminal. This keeps the event loop running but may cause interesting effects when interrupted with Control-C. The default is `True`, but don't depend on it. Warning: The user interaction is run inside a separate thread, because otherwise the call would block the async loop. As a result, behavior when interrupted may be sub-optimal. .. versionadded:: 8.3 (AsyncClick) ``prompt`` is now async; ``blocking`` parameter added. .. versionadded:: 8.0 ``confirmation_prompt`` can be a custom string. .. versionadded:: 7.0 Added the ``show_choices`` parameter. .. versionadded:: 6.0 Added unicode support for cmd.exe on Windows. .. versionadded:: 4.0 Added the `err` parameter. """ def prompt_func(text: str) -> str: f = hidden_prompt_func if hide_input else visible_prompt_func try: # Write the prompt separately so that we get nice # coloring through colorama on Windows echo(text.rstrip(" "), nl=False, err=err) # Echo a space to stdout to work around an issue where # readline causes backspace to clear the whole line. return f(" ") except (KeyboardInterrupt, EOFError): # getpass doesn't print a newline if the user aborts input with ^C. # Allegedly this behavior is inherited from getpass(3). # A doc bug has been filed at https://bugs.python.org/issue24711 if hide_input: echo(None, err=err) raise Abort() from None run_prompt_func: t.Callable[[str], t.Awaitable[str]] if blocking: async def run_prompt_func(text: str) -> str: return prompt_func(text) else: # Not having a hard dependency on any async runtime is harder than it looks. try: import anyio except ImportError: try: import sniffio # type: ignore except ImportError: backend = "asyncio" else: backend = sniffio.current_async_library() if backend == "trio": import trio def run_prompt_func(text: str) -> t.Awaitable[str]: return trio.to_thread.run_sync(prompt_func, text) else: import asyncio def run_prompt_func(text: str) -> t.Awaitable[str]: return asyncio.to_thread(prompt_func, text) else: def run_prompt_func(text: str) -> t.Awaitable[str]: return anyio.to_thread.run_sync(prompt_func, text) if value_proc is None: value_proc = convert_type(type, default) prompt = _build_prompt( text, prompt_suffix, show_default, default, show_choices, type ) if confirmation_prompt: if confirmation_prompt is True: confirmation_prompt = _("Repeat for confirmation") confirmation_prompt = _build_prompt(confirmation_prompt, prompt_suffix) while True: while True: value = await run_prompt_func(prompt) if value: break elif default is not None: value = default break try: result = value_proc(value) if iscoroutine(result): result = await result except UsageError as e: if hide_input: echo(_("Error: The value you entered was invalid."), err=err) else: echo(_("Error: {e.message}").format(e=e), err=err) continue if not confirmation_prompt: return result while True: value2 = await run_prompt_func(confirmation_prompt) is_empty = not value and not value2 if value2 or is_empty: break if value == value2: return result echo(_("Error: The two entered values do not match."), err=err) def confirm( text: str, default: bool | None = False, abort: bool = False, prompt_suffix: str = ": ", show_default: bool = True, err: bool = False, ) -> bool: """Prompts for confirmation (yes/no question). If the user aborts the input by sending a interrupt signal this function will catch it and raise a :exc:`Abort` exception. :param text: the question to ask. :param default: The default value to use when no input is given. If ``None``, repeat until input is given. :param abort: if this is set to `True` a negative answer aborts the exception by raising :exc:`Abort`. :param prompt_suffix: a suffix that should be added to the prompt. :param show_default: shows or hides the default value in the prompt. :param err: if set to true the file defaults to ``stderr`` instead of ``stdout``, the same as with echo. .. versionchanged:: 8.0 Repeat until input is given if ``default`` is ``None``. .. versionadded:: 4.0 Added the ``err`` parameter. """ prompt = _build_prompt( text, prompt_suffix, show_default, "y/n" if default is None else ("Y/n" if default else "y/N"), ) while True: try: # Write the prompt separately so that we get nice # coloring through colorama on Windows echo(prompt.rstrip(" "), nl=False, err=err) # Echo a space to stdout to work around an issue where # readline causes backspace to clear the whole line. value = visible_prompt_func(" ").lower().strip() except (KeyboardInterrupt, EOFError): raise Abort() from None if value in ("y", "yes"): rv = True elif value in ("n", "no"): rv = False elif default is not None and value == "": rv = default else: echo(_("Error: invalid input"), err=err) continue break if abort and not rv: raise Abort() return rv def echo_via_pager( text_or_generator: cabc.Iterable[str] | t.Callable[[], cabc.Iterable[str]] | str, color: bool | None = None, ) -> None: """This function takes a text and shows it via an environment specific pager on stdout. .. versionchanged:: 3.0 Added the `color` flag. :param text_or_generator: the text to page, or alternatively, a generator emitting the text to page. :param color: controls if the pager supports ANSI colors or not. The default is autodetection. """ color = resolve_color_default(color) if inspect.isgeneratorfunction(text_or_generator): i = t.cast("t.Callable[[], cabc.Iterable[str]]", text_or_generator)() elif isinstance(text_or_generator, str): i = [text_or_generator] else: i = iter(t.cast("cabc.Iterable[str]", text_or_generator)) # convert every element of i to a text type if necessary text_generator = (el if isinstance(el, str) else str(el) for el in i) from ._termui_impl import pager return pager(itertools.chain(text_generator, "\n"), color) @t.overload def progressbar( *, length: int, label: str | None = None, hidden: bool = False, show_eta: bool = True, show_percent: bool | None = None, show_pos: bool = False, fill_char: str = "#", empty_char: str = "-", bar_template: str = "%(label)s [%(bar)s] %(info)s", info_sep: str = " ", width: int = 36, file: t.TextIO | None = None, color: bool | None = None, update_min_steps: int = 1, ) -> ProgressBar[int]: ... @t.overload def progressbar( iterable: cabc.Iterable[V] | None = None, length: int | None = None, label: str | None = None, hidden: bool = False, show_eta: bool = True, show_percent: bool | None = None, show_pos: bool = False, item_show_func: t.Callable[[V | None], str | None] | None = None, fill_char: str = "#", empty_char: str = "-", bar_template: str = "%(label)s [%(bar)s] %(info)s", info_sep: str = " ", width: int = 36, file: t.TextIO | None = None, color: bool | None = None, update_min_steps: int = 1, ) -> ProgressBar[V]: ... def progressbar( iterable: cabc.Iterable[V] | None = None, length: int | None = None, label: str | None = None, hidden: bool = False, show_eta: bool = True, show_percent: bool | None = None, show_pos: bool = False, item_show_func: t.Callable[[V | None], str | None] | None = None, fill_char: str = "#", empty_char: str = "-", bar_template: str = "%(label)s [%(bar)s] %(info)s", info_sep: str = " ", width: int = 36, file: t.TextIO | None = None, color: bool | None = None, update_min_steps: int = 1, ) -> ProgressBar[V]: """This function creates an iterable context manager that can be used to iterate over something while showing a progress bar. It will either iterate over the `iterable` or `length` items (that are counted up). While iteration happens, this function will print a rendered progress bar to the given `file` (defaults to stdout) and will attempt to calculate remaining time and more. By default, this progress bar will not be rendered if the file is not a terminal. The context manager creates the progress bar. When the context manager is entered the progress bar is already created. With every iteration over the progress bar, the iterable passed to the bar is advanced and the bar is updated. When the context manager exits, a newline is printed and the progress bar is finalized on screen. Note: The progress bar is currently designed for use cases where the total progress can be expected to take at least several seconds. Because of this, the ProgressBar class object won't display progress that is considered too fast, and progress where the time between steps is less than a second. No printing must happen or the progress bar will be unintentionally destroyed. Example usage:: with progressbar(items) as bar: for item in bar: do_something_with(item) Alternatively, if no iterable is specified, one can manually update the progress bar through the `update()` method instead of directly iterating over the progress bar. The update method accepts the number of steps to increment the bar with:: with progressbar(length=chunks.total_bytes) as bar: for chunk in chunks: process_chunk(chunk) bar.update(chunks.bytes) The ``update()`` method also takes an optional value specifying the ``current_item`` at the new position. This is useful when used together with ``item_show_func`` to customize the output for each manual step:: with click.progressbar( length=total_size, label='Unzipping archive', item_show_func=lambda a: a.filename ) as bar: for archive in zip_file: archive.extract() bar.update(archive.size, archive) :param iterable: an iterable to iterate over. If not provided the length is required. :param length: the number of items to iterate over. By default the progressbar will attempt to ask the iterator about its length, which might or might not work. If an iterable is also provided this parameter can be used to override the length. If an iterable is not provided the progress bar will iterate over a range of that length. :param label: the label to show next to the progress bar. :param hidden: hide the progressbar. Defaults to ``False``. When no tty is detected, it will only print the progressbar label. Setting this to ``False`` also disables that. :param show_eta: enables or disables the estimated time display. This is automatically disabled if the length cannot be determined. :param show_percent: enables or disables the percentage display. The default is `True` if the iterable has a length or `False` if not. :param show_pos: enables or disables the absolute position display. The default is `False`. :param item_show_func: A function called with the current item which can return a string to show next to the progress bar. If the function returns ``None`` nothing is shown. The current item can be ``None``, such as when entering and exiting the bar. :param fill_char: the character to use to show the filled part of the progress bar. :param empty_char: the character to use to show the non-filled part of the progress bar. :param bar_template: the format string to use as template for the bar. The parameters in it are ``label`` for the label, ``bar`` for the progress bar and ``info`` for the info section. :param info_sep: the separator between multiple info items (eta etc.) :param width: the width of the progress bar in characters, 0 means full terminal width :param file: The file to write to. If this is not a terminal then only the label is printed. :param color: controls if the terminal supports ANSI colors or not. The default is autodetection. This is only needed if ANSI codes are included anywhere in the progress bar output which is not the case by default. :param update_min_steps: Render only when this many updates have completed. This allows tuning for very fast iterators. .. versionadded:: 8.2 The ``hidden`` argument. .. versionchanged:: 8.0 Output is shown even if execution time is less than 0.5 seconds. .. versionchanged:: 8.0 ``item_show_func`` shows the current item, not the previous one. .. versionchanged:: 8.0 Labels are echoed if the output is not a TTY. Reverts a change in 7.0 that removed all output. .. versionadded:: 8.0 The ``update_min_steps`` parameter. .. versionadded:: 4.0 The ``color`` parameter and ``update`` method. .. versionadded:: 2.0 """ from ._termui_impl import ProgressBar color = resolve_color_default(color) return ProgressBar( iterable=iterable, length=length, hidden=hidden, show_eta=show_eta, show_percent=show_percent, show_pos=show_pos, item_show_func=item_show_func, fill_char=fill_char, empty_char=empty_char, bar_template=bar_template, info_sep=info_sep, file=file, label=label, width=width, color=color, update_min_steps=update_min_steps, ) def clear() -> None: """Clears the terminal screen. This will have the effect of clearing the whole visible space of the terminal and moving the cursor to the top left. This does not do anything if not connected to a terminal. .. versionadded:: 2.0 """ if not isatty(sys.stdout): return # ANSI escape \033[2J clears the screen, \033[1;1H moves the cursor echo("\033[2J\033[1;1H", nl=False) def _interpret_color(color: int | tuple[int, int, int] | str, offset: int = 0) -> str: if isinstance(color, int): return f"{38 + offset};5;{color:d}" if isinstance(color, (tuple, list)): r, g, b = color return f"{38 + offset};2;{r:d};{g:d};{b:d}" return str(_ansi_colors[color] + offset) def style( text: t.Any, fg: int | tuple[int, int, int] | str | None = None, bg: int | tuple[int, int, int] | str | None = None, bold: bool | None = None, dim: bool | None = None, underline: bool | None = None, overline: bool | None = None, italic: bool | None = None, blink: bool | None = None, reverse: bool | None = None, strikethrough: bool | None = None, reset: bool = True, ) -> str: """Styles a text with ANSI styles and returns the new string. By default the styling is self contained which means that at the end of the string a reset code is issued. This can be prevented by passing ``reset=False``. Examples:: click.echo(click.style('Hello World!', fg='green')) click.echo(click.style('ATTENTION!', blink=True)) click.echo(click.style('Some things', reverse=True, fg='cyan')) click.echo(click.style('More colors', fg=(255, 12, 128), bg=117)) Supported color names: * ``black`` (might be a gray) * ``red`` * ``green`` * ``yellow`` (might be an orange) * ``blue`` * ``magenta`` * ``cyan`` * ``white`` (might be light gray) * ``bright_black`` * ``bright_red`` * ``bright_green`` * ``bright_yellow`` * ``bright_blue`` * ``bright_magenta`` * ``bright_cyan`` * ``bright_white`` * ``reset`` (reset the color code only) If the terminal supports it, color may also be specified as: - An integer in the interval [0, 255]. The terminal must support 8-bit/256-color mode. - An RGB tuple of three integers in [0, 255]. The terminal must support 24-bit/true-color mode. See https://en.wikipedia.org/wiki/ANSI_color and https://gist.github.com/XVilka/8346728 for more information. :param text: the string to style with ansi codes. :param fg: if provided this will become the foreground color. :param bg: if provided this will become the background color. :param bold: if provided this will enable or disable bold mode. :param dim: if provided this will enable or disable dim mode. This is badly supported. :param underline: if provided this will enable or disable underline. :param overline: if provided this will enable or disable overline. :param italic: if provided this will enable or disable italic. :param blink: if provided this will enable or disable blinking. :param reverse: if provided this will enable or disable inverse rendering (foreground becomes background and the other way round). :param strikethrough: if provided this will enable or disable striking through text. :param reset: by default a reset-all code is added at the end of the string which means that styles do not carry over. This can be disabled to compose styles. .. versionchanged:: 8.0 A non-string ``message`` is converted to a string. .. versionchanged:: 8.0 Added support for 256 and RGB color codes. .. versionchanged:: 8.0 Added the ``strikethrough``, ``italic``, and ``overline`` parameters. .. versionchanged:: 7.0 Added support for bright colors. .. versionadded:: 2.0 """ if not isinstance(text, str): text = str(text) bits = [] if fg: try: bits.append(f"\033[{_interpret_color(fg)}m") except KeyError: raise TypeError(f"Unknown color {fg!r}") from None if bg: try: bits.append(f"\033[{_interpret_color(bg, 10)}m") except KeyError: raise TypeError(f"Unknown color {bg!r}") from None if bold is not None: bits.append(f"\033[{1 if bold else 22}m") if dim is not None: bits.append(f"\033[{2 if dim else 22}m") if underline is not None: bits.append(f"\033[{4 if underline else 24}m") if overline is not None: bits.append(f"\033[{53 if overline else 55}m") if italic is not None: bits.append(f"\033[{3 if italic else 23}m") if blink is not None: bits.append(f"\033[{5 if blink else 25}m") if reverse is not None: bits.append(f"\033[{7 if reverse else 27}m") if strikethrough is not None: bits.append(f"\033[{9 if strikethrough else 29}m") bits.append(text) if reset: bits.append(_ansi_reset_all) return "".join(bits) def unstyle(text: str) -> str: """Removes ANSI styling information from a string. Usually it's not necessary to use this function as Click's echo function will automatically remove styling if necessary. .. versionadded:: 2.0 :param text: the text to remove style information from. """ return strip_ansi(text) def secho( message: t.Any | None = None, file: t.IO[t.AnyStr] | None = None, nl: bool = True, err: bool = False, color: bool | None = None, **styles: t.Any, ) -> None: """This function combines :func:`echo` and :func:`style` into one call. As such the following two calls are the same:: click.secho('Hello World!', fg='green') click.echo(click.style('Hello World!', fg='green')) All keyword arguments are forwarded to the underlying functions depending on which one they go with. Non-string types will be converted to :class:`str`. However, :class:`bytes` are passed directly to :meth:`echo` without applying style. If you want to style bytes that represent text, call :meth:`bytes.decode` first. .. versionchanged:: 8.0 A non-string ``message`` is converted to a string. Bytes are passed through without style applied. .. versionadded:: 2.0 """ if message is not None and not isinstance(message, (bytes, bytearray)): message = style(message, **styles) return echo(message, file=file, nl=nl, err=err, color=color) @t.overload def edit( text: bytes | bytearray, editor: str | None = None, env: cabc.Mapping[str, str] | None = None, require_save: bool = False, extension: str = ".txt", ) -> bytes | None: ... @t.overload def edit( text: str, editor: str | None = None, env: cabc.Mapping[str, str] | None = None, require_save: bool = True, extension: str = ".txt", ) -> str | None: ... @t.overload def edit( text: None = None, editor: str | None = None, env: cabc.Mapping[str, str] | None = None, require_save: bool = True, extension: str = ".txt", filename: str | cabc.Iterable[str] | None = None, ) -> None: ... def edit( text: str | bytes | bytearray | None = None, editor: str | None = None, env: cabc.Mapping[str, str] | None = None, require_save: bool = True, extension: str = ".txt", filename: str | cabc.Iterable[str] | None = None, ) -> str | bytes | bytearray | None: r"""Edits the given text in the defined editor. If an editor is given (should be the full path to the executable but the regular operating system search path is used for finding the executable) it overrides the detected editor. Optionally, some environment variables can be used. If the editor is closed without changes, `None` is returned. In case a file is edited directly the return value is always `None` and `require_save` and `extension` are ignored. If the editor cannot be opened a :exc:`UsageError` is raised. Note for Windows: to simplify cross-platform usage, the newlines are automatically converted from POSIX to Windows and vice versa. As such, the message here will have ``\n`` as newline markers. :param text: the text to edit. :param editor: optionally the editor to use. Defaults to automatic detection. :param env: environment variables to forward to the editor. :param require_save: if this is true, then not saving in the editor will make the return value become `None`. :param extension: the extension to tell the editor about. This defaults to `.txt` but changing this might change syntax highlighting. :param filename: if provided it will edit this file instead of the provided text contents. It will not use a temporary file as an indirection in that case. If the editor supports editing multiple files at once, a sequence of files may be passed as well. Invoke `click.file` once per file instead if multiple files cannot be managed at once or editing the files serially is desired. .. versionchanged:: 8.2.0 ``filename`` now accepts any ``Iterable[str]`` in addition to a ``str`` if the ``editor`` supports editing multiple files at once. """ from ._termui_impl import Editor ed = Editor(editor=editor, env=env, require_save=require_save, extension=extension) if filename is None: return ed.edit(text) if isinstance(filename, str): filename = (filename,) ed.edit_files(filenames=filename) return None def launch(url: str, wait: bool = False, locate: bool = False) -> int: """This function launches the given URL (or filename) in the default viewer application for this file type. If this is an executable, it might launch the executable in a new session. The return value is the exit code of the launched application. Usually, ``0`` indicates success. Examples:: click.launch('https://click.palletsprojects.com/') click.launch('/my/downloaded/file', locate=True) .. versionadded:: 2.0 :param url: URL or filename of the thing to launch. :param wait: Wait for the program to exit before returning. This only works if the launched program blocks. In particular, ``xdg-open`` on Linux does not block. :param locate: if this is set to `True` then instead of launching the application associated with the URL it will attempt to launch a file manager with the file located. This might have weird effects if the URL does not point to the filesystem. """ from ._termui_impl import open_url return open_url(url, wait=wait, locate=locate) # If this is provided, getchar() calls into this instead. This is used # for unittesting purposes. _getchar: t.Callable[[bool], str] | None = None def getchar(echo: bool = False) -> str: """Fetches a single character from the terminal and returns it. This will always return a unicode character and under certain rare circumstances this might return more than one character. The situations which more than one character is returned is when for whatever reason multiple characters end up in the terminal buffer or standard input was not actually a terminal. Note that this will always read from the terminal, even if something is piped into the standard input. Note for Windows: in rare cases when typing non-ASCII characters, this function might wait for a second character and then return both at once. This is because certain Unicode characters look like special-key markers. .. versionadded:: 2.0 :param echo: if set to `True`, the character read will also show up on the terminal. The default is to not show it. """ global _getchar if _getchar is None: from ._termui_impl import getchar as f _getchar = f return _getchar(echo) def raw_terminal() -> AbstractContextManager[int]: from ._termui_impl import raw_terminal as f return f() def pause(info: str | None = None, err: bool = False) -> None: """This command stops execution and waits for the user to press any key to continue. This is similar to the Windows batch "pause" command. If the program is not run through a terminal, this command will instead do nothing. .. versionadded:: 2.0 .. versionadded:: 4.0 Added the `err` parameter. :param info: The message to print before pausing. Defaults to ``"Press any key to continue..."``. :param err: if set to message goes to ``stderr`` instead of ``stdout``, the same as with echo. """ if not isatty(sys.stdin) or not isatty(sys.stdout): return if info is None: info = _("Press any key to continue...") try: if info: echo(info, nl=False, err=err) try: getchar() except (KeyboardInterrupt, EOFError): pass finally: if info: echo(err=err) asyncclick-8.3.0.5-async/src/asyncclick/testing.py000066400000000000000000000454751507140761400221100ustar00rootroot00000000000000from __future__ import annotations import collections.abc as cabc import contextlib import io import os import shlex import sys import tempfile import typing as t from types import TracebackType from . import _compat from . import formatting from . import termui from . import utils from ._compat import _find_binary_reader if t.TYPE_CHECKING: from _typeshed import ReadableBuffer from .core import Command class EchoingStdin: def __init__(self, input: t.BinaryIO, output: t.BinaryIO) -> None: self._input = input self._output = output self._paused = False def __getattr__(self, x: str) -> t.Any: return getattr(self._input, x) def _echo(self, rv: bytes) -> bytes: if not self._paused: self._output.write(rv) return rv def read(self, n: int = -1) -> bytes: return self._echo(self._input.read(n)) def read1(self, n: int = -1) -> bytes: return self._echo(self._input.read1(n)) # type: ignore def readline(self, n: int = -1) -> bytes: return self._echo(self._input.readline(n)) def readlines(self) -> list[bytes]: return [self._echo(x) for x in self._input.readlines()] def __iter__(self) -> cabc.Iterator[bytes]: return iter(self._echo(x) for x in self._input) def __repr__(self) -> str: return repr(self._input) @contextlib.contextmanager def _pause_echo(stream: EchoingStdin | None) -> cabc.Iterator[None]: if stream is None: yield else: stream._paused = True yield stream._paused = False class BytesIOCopy(io.BytesIO): """Patch ``io.BytesIO`` to let the written stream be copied to another. .. versionadded:: 8.2 """ def __init__(self, copy_to: io.BytesIO) -> None: super().__init__() self.copy_to = copy_to def flush(self) -> None: super().flush() self.copy_to.flush() def write(self, b: ReadableBuffer) -> int: self.copy_to.write(b) return super().write(b) class StreamMixer: """Mixes `` and `` streams. The result is available in the ``output`` attribute. .. versionadded:: 8.2 """ def __init__(self) -> None: self.output: io.BytesIO = io.BytesIO() self.stdout: io.BytesIO = BytesIOCopy(copy_to=self.output) self.stderr: io.BytesIO = BytesIOCopy(copy_to=self.output) def __del__(self) -> None: """ Guarantee that embedded file-like objects are closed in a predictable order, protecting against races between self.output being closed and other streams being flushed on close .. versionadded:: 8.2.2 """ self.stderr.close() self.stdout.close() self.output.close() class _NamedTextIOWrapper(io.TextIOWrapper): def __init__( self, buffer: t.BinaryIO, name: str, mode: str, **kwargs: t.Any ) -> None: super().__init__(buffer, **kwargs) self._name = name self._mode = mode @property def name(self) -> str: return self._name @property def mode(self) -> str: return self._mode def make_input_stream( input: str | bytes | t.IO[t.Any] | None, charset: str ) -> t.BinaryIO: # Is already an input stream. if hasattr(input, "read"): rv = _find_binary_reader(t.cast("t.IO[t.Any]", input)) if rv is not None: return rv raise TypeError("Could not find binary reader for input stream.") if input is None: input = b"" elif isinstance(input, str): input = input.encode(charset) return io.BytesIO(input) class Result: """Holds the captured result of an invoked CLI script. :param runner: The runner that created the result :param stdout_bytes: The standard output as bytes. :param stderr_bytes: The standard error as bytes. :param output_bytes: A mix of ``stdout_bytes`` and ``stderr_bytes``, as the user would see it in its terminal. :param return_value: The value returned from the invoked command. :param exit_code: The exit code as integer. :param exception: The exception that happened if one did. :param exc_info: Exception information (exception type, exception instance, traceback type). .. versionchanged:: 8.2 ``stderr_bytes`` no longer optional, ``output_bytes`` introduced and ``mix_stderr`` has been removed. .. versionadded:: 8.0 Added ``return_value``. """ def __init__( self, runner: CliRunner, stdout_bytes: bytes, stderr_bytes: bytes, output_bytes: bytes, return_value: t.Any, exit_code: int, exception: BaseException | None, exc_info: tuple[type[BaseException], BaseException, TracebackType] | None = None, ): self.runner = runner self.stdout_bytes = stdout_bytes self.stderr_bytes = stderr_bytes self.output_bytes = output_bytes self.return_value = return_value self.exit_code = exit_code self.exception = exception self.exc_info = exc_info @property def output(self) -> str: """The terminal output as unicode string, as the user would see it. .. versionchanged:: 8.2 No longer a proxy for ``self.stdout``. Now has its own independent stream that is mixing `` and ``, in the order they were written. """ return self.output_bytes.decode(self.runner.charset, "replace").replace( "\r\n", "\n" ) @property def stdout(self) -> str: """The standard output as unicode string.""" return self.stdout_bytes.decode(self.runner.charset, "replace").replace( "\r\n", "\n" ) @property def stderr(self) -> str: """The standard error as unicode string. .. versionchanged:: 8.2 No longer raise an exception, always returns the `` string. """ return self.stderr_bytes.decode(self.runner.charset, "replace").replace( "\r\n", "\n" ) def __repr__(self) -> str: exc_str = repr(self.exception) if self.exception else "okay" return f"<{type(self).__name__} {exc_str}>" class CliRunner: """The CLI runner provides functionality to invoke a Click command line script for unittesting purposes in a isolated environment. This only works in single-threaded systems without any concurrency as it changes the global interpreter state. :param charset: the character set for the input and output data. :param env: a dictionary with environment variables for overriding. :param echo_stdin: if this is set to `True`, then reading from `` writes to ``. This is useful for showing examples in some circumstances. Note that regular prompts will automatically echo the input. :param catch_exceptions: Whether to catch any exceptions other than ``SystemExit`` when running :meth:`~CliRunner.invoke`. .. versionchanged:: 8.2 Added the ``catch_exceptions`` parameter. .. versionchanged:: 8.2 ``mix_stderr`` parameter has been removed. """ def __init__( self, charset: str = "utf-8", env: cabc.Mapping[str, str | None] | None = None, echo_stdin: bool = False, catch_exceptions: bool = True, ) -> None: self.charset = charset self.env: cabc.Mapping[str, str | None] = env or {} self.echo_stdin = echo_stdin self.catch_exceptions = catch_exceptions def get_default_prog_name(self, cli: Command) -> str: """Given a command object it will return the default program name for it. The default is the `name` attribute or ``"root"`` if not set. """ return cli.name or "root" def make_env( self, overrides: cabc.Mapping[str, str | None] | None = None ) -> cabc.Mapping[str, str | None]: """Returns the environment overrides for invoking a script.""" rv = dict(self.env) if overrides: rv.update(overrides) return rv @contextlib.contextmanager def isolation( self, input: str | bytes | t.IO[t.Any] | None = None, env: cabc.Mapping[str, str | None] | None = None, color: bool = False, ) -> cabc.Iterator[tuple[io.BytesIO, io.BytesIO, io.BytesIO]]: """A context manager that sets up the isolation for invoking of a command line tool. This sets up `` with the given input data and `os.environ` with the overrides from the given dictionary. This also rebinds some internals in Click to be mocked (like the prompt functionality). This is automatically done in the :meth:`invoke` method. :param input: the input stream to put into `sys.stdin`. :param env: the environment overrides as dictionary. :param color: whether the output should contain color codes. The application can still override this explicitly. .. versionadded:: 8.2 An additional output stream is returned, which is a mix of `` and `` streams. .. versionchanged:: 8.2 Always returns the `` stream. .. versionchanged:: 8.0 `` is opened with ``errors="backslashreplace"`` instead of the default ``"strict"``. .. versionchanged:: 4.0 Added the ``color`` parameter. """ bytes_input = make_input_stream(input, self.charset) echo_input = None global o_stdin, o_stdout, o_stderr old_stdin = sys.stdin old_stdout = sys.stdout old_stderr = sys.stderr old_forced_width = formatting.FORCED_WIDTH formatting.FORCED_WIDTH = 80 env = self.make_env(env) stream_mixer = StreamMixer() if self.echo_stdin: bytes_input = echo_input = t.cast( t.BinaryIO, EchoingStdin(bytes_input, stream_mixer.stdout) ) text_input = _NamedTextIOWrapper( bytes_input, encoding=self.charset, name="", mode="r" ) sys.stdin = text_input if self.echo_stdin: # Force unbuffered reads, otherwise TextIOWrapper reads a # large chunk which is echoed early. text_input._CHUNK_SIZE = 1 # type: ignore sys.stdout = _NamedTextIOWrapper( stream_mixer.stdout, encoding=self.charset, name="", mode="w" ) sys.stderr = _NamedTextIOWrapper( stream_mixer.stderr, encoding=self.charset, name="", mode="w", errors="backslashreplace", ) @_pause_echo(echo_input) # type: ignore def visible_input(prompt: str | None = None) -> str: sys.stdout.write(prompt or "") try: val = next(text_input).rstrip("\r\n") except StopIteration as e: raise EOFError() from e sys.stdout.write(f"{val}\n") sys.stdout.flush() return val @_pause_echo(echo_input) # type: ignore def hidden_input(prompt: str | None = None) -> str: sys.stdout.write(f"{prompt or ''}\n") sys.stdout.flush() try: return next(text_input).rstrip("\r\n") except StopIteration as e: raise EOFError() from e @_pause_echo(echo_input) # type: ignore def _getchar(echo: bool) -> str: char = sys.stdin.read(1) if echo: sys.stdout.write(char) sys.stdout.flush() return char default_color = color def should_strip_ansi( stream: t.IO[t.Any] | None = None, color: bool | None = None ) -> bool: if color is None: return not default_color return not color old_visible_prompt_func = termui.visible_prompt_func old_hidden_prompt_func = termui.hidden_prompt_func old__getchar_func = termui._getchar old_should_strip_ansi = utils.should_strip_ansi # type: ignore old__compat_should_strip_ansi = _compat.should_strip_ansi termui.visible_prompt_func = visible_input termui.hidden_prompt_func = hidden_input termui._getchar = _getchar utils.should_strip_ansi = should_strip_ansi # type: ignore _compat.should_strip_ansi = should_strip_ansi old_env = {} try: for key, value in env.items(): old_env[key] = os.environ.get(key) if value is None: try: del os.environ[key] except Exception: pass else: os.environ[key] = value yield (stream_mixer.stdout, stream_mixer.stderr, stream_mixer.output) finally: for key, value in old_env.items(): if value is None: try: del os.environ[key] except Exception: pass else: os.environ[key] = value global o_stdin, o_stdout, o_stderr sys.stdout = old_stdout sys.stderr = old_stderr sys.stdin = old_stdin termui.visible_prompt_func = old_visible_prompt_func termui.hidden_prompt_func = old_hidden_prompt_func termui._getchar = old__getchar_func utils.should_strip_ansi = old_should_strip_ansi # type: ignore _compat.should_strip_ansi = old__compat_should_strip_ansi formatting.FORCED_WIDTH = old_forced_width async def invoke( self, cli: Command, args: str | cabc.Sequence[str] | None = None, input: str | bytes | t.IO[t.Any] | None = None, env: cabc.Mapping[str, str | None] | None = None, catch_exceptions: bool | None = None, color: bool = False, **extra: t.Any, ) -> Result: """Invokes a command in an isolated environment. The arguments are forwarded directly to the command line script, the `extra` keyword arguments are passed to the :meth:`~clickpkg.Command.main` function of the command. This returns a :class:`Result` object. :param cli: the command to invoke :param args: the arguments to invoke. It may be given as an iterable or a string. When given as string it will be interpreted as a Unix shell command. More details at :func:`shlex.split`. :param input: the input data for `sys.stdin`. :param env: the environment overrides. :param catch_exceptions: Whether to catch any other exceptions than ``SystemExit``. If :data:`None`, the value from :class:`CliRunner` is used. :param extra: the keyword arguments to pass to :meth:`main`. :param color: whether the output should contain color codes. The application can still override this explicitly. .. versionadded:: 8.2 The result object has the ``output_bytes`` attribute with the mix of ``stdout_bytes`` and ``stderr_bytes``, as the user would see it in its terminal. .. versionchanged:: 8.2 The result object always returns the ``stderr_bytes`` stream. .. versionchanged:: 8.0 The result object has the ``return_value`` attribute with the value returned from the invoked command. .. versionchanged:: 4.0 Added the ``color`` parameter. .. versionchanged:: 3.0 Added the ``catch_exceptions`` parameter. .. versionchanged:: 3.0 The result object has the ``exc_info`` attribute with the traceback if available. """ exc_info = None if catch_exceptions is None: catch_exceptions = self.catch_exceptions with self.isolation(input=input, env=env, color=color) as outstreams: return_value = None exception: BaseException | None = None exit_code = 0 if isinstance(args, str): args = shlex.split(args) try: prog_name = extra.pop("prog_name") except KeyError: prog_name = self.get_default_prog_name(cli) try: return_value = await cli.main( args=args or (), prog_name=prog_name, **extra ) except SystemExit as e: exc_info = sys.exc_info() e_code = t.cast("int | t.Any | None", e.code) if e_code is None: e_code = 0 if e_code != 0: exception = e if not isinstance(e_code, int): sys.stdout.write(str(e_code)) sys.stdout.write("\n") e_code = 1 exit_code = e_code except Exception as e: if not catch_exceptions: raise exception = e exit_code = 1 exc_info = sys.exc_info() finally: sys.stdout.flush() sys.stderr.flush() stdout = outstreams[0].getvalue() stderr = outstreams[1].getvalue() output = outstreams[2].getvalue() return Result( runner=self, stdout_bytes=stdout, stderr_bytes=stderr, output_bytes=output, return_value=return_value, exit_code=exit_code, exception=exception, exc_info=exc_info, # type: ignore ) @contextlib.contextmanager def isolated_filesystem( self, temp_dir: str | os.PathLike[str] | None = None ) -> cabc.Iterator[str]: """A context manager that creates a temporary directory and changes the current working directory to it. This isolates tests that affect the contents of the CWD to prevent them from interfering with each other. :param temp_dir: Create the temporary directory under this directory. If given, the created directory is not removed when exiting. .. versionchanged:: 8.0 Added the ``temp_dir`` parameter. """ cwd = os.getcwd() dt = tempfile.mkdtemp(dir=temp_dir) os.chdir(dt) try: yield dt finally: os.chdir(cwd) if temp_dir is None: import shutil try: shutil.rmtree(dt) except OSError: pass asyncclick-8.3.0.5-async/src/asyncclick/types.py000066400000000000000000001161101507140761400215600ustar00rootroot00000000000000from __future__ import annotations import collections.abc as cabc import enum import os import stat import sys import typing as t from datetime import datetime from gettext import gettext as _ from gettext import ngettext from ._compat import _get_argv_encoding from ._compat import open_stream from .exceptions import BadParameter from .utils import format_filename from .utils import LazyFile from .utils import safecall if t.TYPE_CHECKING: import typing_extensions as te from .core import Context from .core import Parameter from .shell_completion import CompletionItem ParamTypeValue = t.TypeVar("ParamTypeValue") class ParamType: """Represents the type of a parameter. Validates and converts values from the command line or Python into the correct type. To implement a custom type, subclass and implement at least the following: - The :attr:`name` class attribute must be set. - Calling an instance of the type with ``None`` must return ``None``. This is already implemented by default. - :meth:`convert` must convert string values to the correct type. - :meth:`convert` must accept values that are already the correct type. - It must be able to convert a value if the ``ctx`` and ``param`` arguments are ``None``. This can occur when converting prompt input. """ is_composite: t.ClassVar[bool] = False arity: t.ClassVar[int] = 1 #: the descriptive name of this type name: str #: if a list of this type is expected and the value is pulled from a #: string environment variable, this is what splits it up. `None` #: means any whitespace. For all parameters the general rule is that #: whitespace splits them up. The exception are paths and files which #: are split by ``os.path.pathsep`` by default (":" on Unix and ";" on #: Windows). envvar_list_splitter: t.ClassVar[str | None] = None async def to_info_dict(self) -> dict[str, t.Any]: """Gather information that could be useful for a tool generating user-facing documentation. Use :meth:`click.Context.to_info_dict` to traverse the entire CLI structure. .. versionadded:: 8.0 """ # The class name without the "ParamType" suffix. param_type = type(self).__name__.partition("ParamType")[0] param_type = param_type.partition("ParameterType")[0] # Custom subclasses might not remember to set a name. if hasattr(self, "name"): name = self.name else: name = param_type return {"param_type": param_type, "name": name} def __call__( self, value: t.Any, param: Parameter | None = None, ctx: Context | None = None, ) -> t.Any: if value is not None: return self.convert(value, param, ctx) def get_metavar(self, param: Parameter, ctx: Context) -> str | None: """Returns the metavar default for this param if it provides one.""" def get_missing_message(self, param: Parameter, ctx: Context | None) -> str | None: """Optionally might return extra information about a missing parameter. .. versionadded:: 2.0 """ def convert( self, value: t.Any, param: Parameter | None, ctx: Context | None ) -> t.Any: """Convert the value to the correct type. This is not called if the value is ``None`` (the missing value). This must accept string values from the command line, as well as values that are already the correct type. It may also convert other compatible types. The ``param`` and ``ctx`` arguments may be ``None`` in certain situations, such as when converting prompt input. If the value cannot be converted, call :meth:`fail` with a descriptive message. :param value: The value to convert. :param param: The parameter that is using this type to convert its value. May be ``None``. :param ctx: The current context that arrived at this value. May be ``None``. """ return value def split_envvar_value(self, rv: str) -> cabc.Sequence[str]: """Given a value from an environment variable this splits it up into small chunks depending on the defined envvar list splitter. If the splitter is set to `None`, which means that whitespace splits, then leading and trailing whitespace is ignored. Otherwise, leading and trailing splitters usually lead to empty items being included. """ return (rv or "").split(self.envvar_list_splitter) def fail( self, message: str, param: Parameter | None = None, ctx: Context | None = None, ) -> t.NoReturn: """Helper method to fail with an invalid value message.""" raise BadParameter(message, ctx=ctx, param=param) def shell_complete( self, ctx: Context, param: Parameter, incomplete: str ) -> list[CompletionItem]: """Return a list of :class:`~click.shell_completion.CompletionItem` objects for the incomplete value. Most types do not provide completions, but some do, and this allows custom types to provide custom completions as well. :param ctx: Invocation context for this command. :param param: The parameter that is requesting completion. :param incomplete: Value being completed. May be empty. .. versionadded:: 8.0 """ return [] class CompositeParamType(ParamType): is_composite = True @property def arity(self) -> int: # type: ignore raise NotImplementedError() class FuncParamType(ParamType): def __init__(self, func: t.Callable[[t.Any], t.Any]) -> None: self.name: str = func.__name__ self.func = func async def to_info_dict(self) -> dict[str, t.Any]: info_dict = await super().to_info_dict() info_dict["func"] = self.func return info_dict def convert( self, value: t.Any, param: Parameter | None, ctx: Context | None ) -> t.Any: try: return self.func(value) except ValueError: try: value = str(value) except UnicodeError: value = value.decode("utf-8", "replace") self.fail(value, param, ctx) class UnprocessedParamType(ParamType): name = "text" def convert( self, value: t.Any, param: Parameter | None, ctx: Context | None ) -> t.Any: return value def __repr__(self) -> str: return "UNPROCESSED" class StringParamType(ParamType): name = "text" def convert( self, value: t.Any, param: Parameter | None, ctx: Context | None ) -> t.Any: if isinstance(value, bytes): enc = _get_argv_encoding() try: value = value.decode(enc) except UnicodeError: fs_enc = sys.getfilesystemencoding() if fs_enc != enc: try: value = value.decode(fs_enc) except UnicodeError: value = value.decode("utf-8", "replace") else: value = value.decode("utf-8", "replace") return value return str(value) def __repr__(self) -> str: return "STRING" class Choice(ParamType, t.Generic[ParamTypeValue]): """The choice type allows a value to be checked against a fixed set of supported values. You may pass any iterable value which will be converted to a tuple and thus will only be iterated once. The resulting value will always be one of the originally passed choices. See :meth:`normalize_choice` for more info on the mapping of strings to choices. See :ref:`choice-opts` for an example. :param case_sensitive: Set to false to make choices case insensitive. Defaults to true. .. versionchanged:: 8.2.0 Non-``str`` ``choices`` are now supported. It can additionally be any iterable. Before you were not recommended to pass anything but a list or tuple. .. versionadded:: 8.2.0 Choice normalization can be overridden via :meth:`normalize_choice`. """ name = "choice" def __init__( self, choices: cabc.Iterable[ParamTypeValue], case_sensitive: bool = True ) -> None: self.choices: cabc.Sequence[ParamTypeValue] = tuple(choices) self.case_sensitive = case_sensitive async def to_info_dict(self) -> dict[str, t.Any]: info_dict = await super().to_info_dict() info_dict["choices"] = self.choices info_dict["case_sensitive"] = self.case_sensitive return info_dict def _normalized_mapping( self, ctx: Context | None = None ) -> cabc.Mapping[ParamTypeValue, str]: """ Returns mapping where keys are the original choices and the values are the normalized values that are accepted via the command line. This is a simple wrapper around :meth:`normalize_choice`, use that instead which is supported. """ return { choice: self.normalize_choice( choice=choice, ctx=ctx, ) for choice in self.choices } def normalize_choice(self, choice: ParamTypeValue, ctx: Context | None) -> str: """ Normalize a choice value, used to map a passed string to a choice. Each choice must have a unique normalized value. By default uses :meth:`Context.token_normalize_func` and if not case sensitive, convert it to a casefolded value. .. versionadded:: 8.2.0 """ normed_value = choice.name if isinstance(choice, enum.Enum) else str(choice) if ctx is not None and ctx.token_normalize_func is not None: normed_value = ctx.token_normalize_func(normed_value) if not self.case_sensitive: normed_value = normed_value.casefold() return normed_value def get_metavar(self, param: Parameter, ctx: Context) -> str | None: if param.param_type_name == "option" and not param.show_choices: # type: ignore choice_metavars = [ convert_type(type(choice)).name.upper() for choice in self.choices ] choices_str = "|".join([*dict.fromkeys(choice_metavars)]) else: choices_str = "|".join( [str(i) for i in self._normalized_mapping(ctx=ctx).values()] ) # Use curly braces to indicate a required argument. if param.required and param.param_type_name == "argument": return f"{{{choices_str}}}" # Use square braces to indicate an option or optional argument. return f"[{choices_str}]" def get_missing_message(self, param: Parameter, ctx: Context | None) -> str: """ Message shown when no choice is passed. .. versionchanged:: 8.2.0 Added ``ctx`` argument. """ return _("Choose from:\n\t{choices}").format( choices=",\n\t".join(self._normalized_mapping(ctx=ctx).values()) ) def convert( self, value: t.Any, param: Parameter | None, ctx: Context | None ) -> ParamTypeValue: """ For a given value from the parser, normalize it and find its matching normalized value in the list of choices. Then return the matched "original" choice. """ normed_value = self.normalize_choice(choice=value, ctx=ctx) normalized_mapping = self._normalized_mapping(ctx=ctx) try: return next( original for original, normalized in normalized_mapping.items() if normalized == normed_value ) except StopIteration: self.fail( self.get_invalid_choice_message(value=value, ctx=ctx), param=param, ctx=ctx, ) def get_invalid_choice_message(self, value: t.Any, ctx: Context | None) -> str: """Get the error message when the given choice is invalid. :param value: The invalid value. .. versionadded:: 8.2 """ choices_str = ", ".join(map(repr, self._normalized_mapping(ctx=ctx).values())) return ngettext( "{value!r} is not {choice}.", "{value!r} is not one of {choices}.", len(self.choices), ).format(value=value, choice=choices_str, choices=choices_str) def __repr__(self) -> str: return f"Choice({list(self.choices)})" def shell_complete( self, ctx: Context, param: Parameter, incomplete: str ) -> list[CompletionItem]: """Complete choices that start with the incomplete value. :param ctx: Invocation context for this command. :param param: The parameter that is requesting completion. :param incomplete: Value being completed. May be empty. .. versionadded:: 8.0 """ from .shell_completion import CompletionItem str_choices = map(str, self.choices) if self.case_sensitive: matched = (c for c in str_choices if c.startswith(incomplete)) else: incomplete = incomplete.lower() matched = (c for c in str_choices if c.lower().startswith(incomplete)) return [CompletionItem(c) for c in matched] class DateTime(ParamType): """The DateTime type converts date strings into `datetime` objects. The format strings which are checked are configurable, but default to some common (non-timezone aware) ISO 8601 formats. When specifying *DateTime* formats, you should only pass a list or a tuple. Other iterables, like generators, may lead to surprising results. The format strings are processed using ``datetime.strptime``, and this consequently defines the format strings which are allowed. Parsing is tried using each format, in order, and the first format which parses successfully is used. :param formats: A list or tuple of date format strings, in the order in which they should be tried. Defaults to ``'%Y-%m-%d'``, ``'%Y-%m-%dT%H:%M:%S'``, ``'%Y-%m-%d %H:%M:%S'``. """ name = "datetime" def __init__(self, formats: cabc.Sequence[str] | None = None): self.formats: cabc.Sequence[str] = formats or [ "%Y-%m-%d", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%d %H:%M:%S", ] async def to_info_dict(self) -> dict[str, t.Any]: info_dict = await super().to_info_dict() info_dict["formats"] = self.formats return info_dict def get_metavar(self, param: Parameter, ctx: Context) -> str | None: return f"[{'|'.join(self.formats)}]" def _try_to_convert_date(self, value: t.Any, format: str) -> datetime | None: try: return datetime.strptime(value, format) except ValueError: return None def convert( self, value: t.Any, param: Parameter | None, ctx: Context | None ) -> t.Any: if isinstance(value, datetime): return value for format in self.formats: converted = self._try_to_convert_date(value, format) if converted is not None: return converted formats_str = ", ".join(map(repr, self.formats)) self.fail( ngettext( "{value!r} does not match the format {format}.", "{value!r} does not match the formats {formats}.", len(self.formats), ).format(value=value, format=formats_str, formats=formats_str), param, ctx, ) def __repr__(self) -> str: return "DateTime" class _NumberParamTypeBase(ParamType): _number_class: t.ClassVar[type[t.Any]] def convert( self, value: t.Any, param: Parameter | None, ctx: Context | None ) -> t.Any: try: return self._number_class(value) except ValueError: self.fail( _("{value!r} is not a valid {number_type}.").format( value=value, number_type=self.name ), param, ctx, ) class _NumberRangeBase(_NumberParamTypeBase): def __init__( self, min: float | None = None, max: float | None = None, min_open: bool = False, max_open: bool = False, clamp: bool = False, ) -> None: self.min = min self.max = max self.min_open = min_open self.max_open = max_open self.clamp = clamp async def to_info_dict(self) -> dict[str, t.Any]: info_dict = await super().to_info_dict() info_dict.update( min=self.min, max=self.max, min_open=self.min_open, max_open=self.max_open, clamp=self.clamp, ) return info_dict def convert( self, value: t.Any, param: Parameter | None, ctx: Context | None ) -> t.Any: import operator rv = super().convert(value, param, ctx) lt_min: bool = self.min is not None and ( operator.le if self.min_open else operator.lt )(rv, self.min) gt_max: bool = self.max is not None and ( operator.ge if self.max_open else operator.gt )(rv, self.max) if self.clamp: if lt_min: return self._clamp(self.min, 1, self.min_open) # type: ignore if gt_max: return self._clamp(self.max, -1, self.max_open) # type: ignore if lt_min or gt_max: self.fail( _("{value} is not in the range {range}.").format( value=rv, range=self._describe_range() ), param, ctx, ) return rv def _clamp(self, bound: float, dir: t.Literal[1, -1], open: bool) -> float: """Find the valid value to clamp to bound in the given direction. :param bound: The boundary value. :param dir: 1 or -1 indicating the direction to move. :param open: If true, the range does not include the bound. """ raise NotImplementedError def _describe_range(self) -> str: """Describe the range for use in help text.""" if self.min is None: op = "<" if self.max_open else "<=" return f"x{op}{self.max}" if self.max is None: op = ">" if self.min_open else ">=" return f"x{op}{self.min}" lop = "<" if self.min_open else "<=" rop = "<" if self.max_open else "<=" return f"{self.min}{lop}x{rop}{self.max}" def __repr__(self) -> str: clamp = " clamped" if self.clamp else "" return f"<{type(self).__name__} {self._describe_range()}{clamp}>" class IntParamType(_NumberParamTypeBase): name = "integer" _number_class = int def __repr__(self) -> str: return "INT" class IntRange(_NumberRangeBase, IntParamType): """Restrict an :data:`click.INT` value to a range of accepted values. See :ref:`ranges`. If ``min`` or ``max`` are not passed, any value is accepted in that direction. If ``min_open`` or ``max_open`` are enabled, the corresponding boundary is not included in the range. If ``clamp`` is enabled, a value outside the range is clamped to the boundary instead of failing. .. versionchanged:: 8.0 Added the ``min_open`` and ``max_open`` parameters. """ name = "integer range" def _clamp( # type: ignore self, bound: int, dir: t.Literal[1, -1], open: bool ) -> int: if not open: return bound return bound + dir class FloatParamType(_NumberParamTypeBase): name = "float" _number_class = float def __repr__(self) -> str: return "FLOAT" class FloatRange(_NumberRangeBase, FloatParamType): """Restrict a :data:`click.FLOAT` value to a range of accepted values. See :ref:`ranges`. If ``min`` or ``max`` are not passed, any value is accepted in that direction. If ``min_open`` or ``max_open`` are enabled, the corresponding boundary is not included in the range. If ``clamp`` is enabled, a value outside the range is clamped to the boundary instead of failing. This is not supported if either boundary is marked ``open``. .. versionchanged:: 8.0 Added the ``min_open`` and ``max_open`` parameters. """ name = "float range" def __init__( self, min: float | None = None, max: float | None = None, min_open: bool = False, max_open: bool = False, clamp: bool = False, ) -> None: super().__init__( min=min, max=max, min_open=min_open, max_open=max_open, clamp=clamp ) if (min_open or max_open) and clamp: raise TypeError("Clamping is not supported for open bounds.") def _clamp(self, bound: float, dir: t.Literal[1, -1], open: bool) -> float: if not open: return bound # Could use math.nextafter here, but clamping an # open float range doesn't seem to be particularly useful. It's # left up to the user to write a callback to do it if needed. raise RuntimeError("Clamping is not supported for open bounds.") class BoolParamType(ParamType): name = "boolean" bool_states: dict[str, bool] = { "1": True, "0": False, "yes": True, "no": False, "true": True, "false": False, "on": True, "off": False, "t": True, "f": False, "y": True, "n": False, # Absence of value is considered False. "": False, } """A mapping of string values to boolean states. Mapping is inspired by :py:attr:`configparser.ConfigParser.BOOLEAN_STATES` and extends it. .. caution:: String values are lower-cased, as the ``str_to_bool`` comparison function below is case-insensitive. .. warning:: The mapping is not exhaustive, and does not cover all possible boolean strings representations. It will remains as it is to avoid endless bikeshedding. Future work my be considered to make this mapping user-configurable from public API. """ @staticmethod def str_to_bool(value: str | bool) -> bool | None: """Convert a string to a boolean value. If the value is already a boolean, it is returned as-is. If the value is a string, it is stripped of whitespaces and lower-cased, then checked against the known boolean states pre-defined in the `BoolParamType.bool_states` mapping above. Returns `None` if the value does not match any known boolean state. """ if isinstance(value, bool): return value return BoolParamType.bool_states.get(value.strip().lower()) def convert( self, value: t.Any, param: Parameter | None, ctx: Context | None ) -> bool: normalized = self.str_to_bool(value) if normalized is None: self.fail( _( "{value!r} is not a valid boolean. Recognized values: {states}" ).format(value=value, states=", ".join(sorted(self.bool_states))), param, ctx, ) return normalized def __repr__(self) -> str: return "BOOL" class UUIDParameterType(ParamType): name = "uuid" def convert( self, value: t.Any, param: Parameter | None, ctx: Context | None ) -> t.Any: import uuid if isinstance(value, uuid.UUID): return value value = value.strip() try: return uuid.UUID(value) except ValueError: self.fail( _("{value!r} is not a valid UUID.").format(value=value), param, ctx ) def __repr__(self) -> str: return "UUID" class File(ParamType): """Declares a parameter to be a file for reading or writing. The file is automatically closed once the context tears down (after the command finished working). Files can be opened for reading or writing. The special value ``-`` indicates stdin or stdout depending on the mode. By default, the file is opened for reading text data, but it can also be opened in binary mode or for writing. The encoding parameter can be used to force a specific encoding. The `lazy` flag controls if the file should be opened immediately or upon first IO. The default is to be non-lazy for standard input and output streams as well as files opened for reading, `lazy` otherwise. When opening a file lazily for reading, it is still opened temporarily for validation, but will not be held open until first IO. lazy is mainly useful when opening for writing to avoid creating the file until it is needed. Files can also be opened atomically in which case all writes go into a separate file in the same folder and upon completion the file will be moved over to the original location. This is useful if a file regularly read by other users is modified. See :ref:`file-args` for more information. .. versionchanged:: 2.0 Added the ``atomic`` parameter. """ name = "filename" envvar_list_splitter: t.ClassVar[str] = os.path.pathsep def __init__( self, mode: str = "r", encoding: str | None = None, errors: str | None = "strict", lazy: bool | None = None, atomic: bool = False, ) -> None: self.mode = mode self.encoding = encoding self.errors = errors self.lazy = lazy self.atomic = atomic async def to_info_dict(self) -> dict[str, t.Any]: info_dict = await super().to_info_dict() info_dict.update(mode=self.mode, encoding=self.encoding) return info_dict def resolve_lazy_flag(self, value: str | os.PathLike[str]) -> bool: if self.lazy is not None: return self.lazy if os.fspath(value) == "-": return False elif "w" in self.mode: return True return False def convert( self, value: str | os.PathLike[str] | t.IO[t.Any], param: Parameter | None, ctx: Context | None, ) -> t.IO[t.Any]: if _is_file_like(value): return value value = t.cast("str | os.PathLike[str]", value) try: lazy = self.resolve_lazy_flag(value) if lazy: lf = LazyFile( value, self.mode, self.encoding, self.errors, atomic=self.atomic ) if ctx is not None: ctx.call_on_close(lf.close_intelligently) return t.cast("t.IO[t.Any]", lf) f, should_close = open_stream( value, self.mode, self.encoding, self.errors, atomic=self.atomic ) # If a context is provided, we automatically close the file # at the end of the context execution (or flush out). If a # context does not exist, it's the caller's responsibility to # properly close the file. This for instance happens when the # type is used with prompts. if ctx is not None: if should_close: ctx.call_on_close(safecall(f.close)) else: ctx.call_on_close(safecall(f.flush)) return f except OSError as e: self.fail(f"'{format_filename(value)}': {e.strerror}", param, ctx) def shell_complete( self, ctx: Context, param: Parameter, incomplete: str ) -> list[CompletionItem]: """Return a special completion marker that tells the completion system to use the shell to provide file path completions. :param ctx: Invocation context for this command. :param param: The parameter that is requesting completion. :param incomplete: Value being completed. May be empty. .. versionadded:: 8.0 """ from .shell_completion import CompletionItem return [CompletionItem(incomplete, type="file")] def _is_file_like(value: t.Any) -> te.TypeGuard[t.IO[t.Any]]: return hasattr(value, "read") or hasattr(value, "write") class Path(ParamType): """The ``Path`` type is similar to the :class:`File` type, but returns the filename instead of an open file. Various checks can be enabled to validate the type of file and permissions. :param exists: The file or directory needs to exist for the value to be valid. If this is not set to ``True``, and the file does not exist, then all further checks are silently skipped. :param file_okay: Allow a file as a value. :param dir_okay: Allow a directory as a value. :param readable: if true, a readable check is performed. :param writable: if true, a writable check is performed. :param executable: if true, an executable check is performed. :param resolve_path: Make the value absolute and resolve any symlinks. A ``~`` is not expanded, as this is supposed to be done by the shell only. :param allow_dash: Allow a single dash as a value, which indicates a standard stream (but does not open it). Use :func:`~click.open_file` to handle opening this value. :param path_type: Convert the incoming path value to this type. If ``None``, keep Python's default, which is ``str``. Useful to convert to :class:`pathlib.Path`. .. versionchanged:: 8.1 Added the ``executable`` parameter. .. versionchanged:: 8.0 Allow passing ``path_type=pathlib.Path``. .. versionchanged:: 6.0 Added the ``allow_dash`` parameter. """ envvar_list_splitter: t.ClassVar[str] = os.path.pathsep def __init__( self, exists: bool = False, file_okay: bool = True, dir_okay: bool = True, writable: bool = False, readable: bool = True, resolve_path: bool = False, allow_dash: bool = False, path_type: type[t.Any] | None = None, executable: bool = False, ): self.exists = exists self.file_okay = file_okay self.dir_okay = dir_okay self.readable = readable self.writable = writable self.executable = executable self.resolve_path = resolve_path self.allow_dash = allow_dash self.type = path_type if self.file_okay and not self.dir_okay: self.name: str = _("file") elif self.dir_okay and not self.file_okay: self.name = _("directory") else: self.name = _("path") async def to_info_dict(self) -> dict[str, t.Any]: info_dict = await super().to_info_dict() info_dict.update( exists=self.exists, file_okay=self.file_okay, dir_okay=self.dir_okay, writable=self.writable, readable=self.readable, allow_dash=self.allow_dash, ) return info_dict def coerce_path_result( self, value: str | os.PathLike[str] ) -> str | bytes | os.PathLike[str]: if self.type is not None and not isinstance(value, self.type): if self.type is str: return os.fsdecode(value) elif self.type is bytes: return os.fsencode(value) else: return t.cast("os.PathLike[str]", self.type(value)) return value def convert( self, value: str | os.PathLike[str], param: Parameter | None, ctx: Context | None, ) -> str | bytes | os.PathLike[str]: rv = value is_dash = self.file_okay and self.allow_dash and rv in (b"-", "-") if not is_dash: if self.resolve_path: rv = os.path.realpath(rv) try: st = os.stat(rv) except OSError: if not self.exists: return self.coerce_path_result(rv) self.fail( _("{name} {filename!r} does not exist.").format( name=self.name.title(), filename=format_filename(value) ), param, ctx, ) if not self.file_okay and stat.S_ISREG(st.st_mode): self.fail( _("{name} {filename!r} is a file.").format( name=self.name.title(), filename=format_filename(value) ), param, ctx, ) if not self.dir_okay and stat.S_ISDIR(st.st_mode): self.fail( _("{name} {filename!r} is a directory.").format( name=self.name.title(), filename=format_filename(value) ), param, ctx, ) if self.readable and not os.access(rv, os.R_OK): self.fail( _("{name} {filename!r} is not readable.").format( name=self.name.title(), filename=format_filename(value) ), param, ctx, ) if self.writable and not os.access(rv, os.W_OK): self.fail( _("{name} {filename!r} is not writable.").format( name=self.name.title(), filename=format_filename(value) ), param, ctx, ) if self.executable and not os.access(value, os.X_OK): self.fail( _("{name} {filename!r} is not executable.").format( name=self.name.title(), filename=format_filename(value) ), param, ctx, ) return self.coerce_path_result(rv) def shell_complete( self, ctx: Context, param: Parameter, incomplete: str ) -> list[CompletionItem]: """Return a special completion marker that tells the completion system to use the shell to provide path completions for only directories or any paths. :param ctx: Invocation context for this command. :param param: The parameter that is requesting completion. :param incomplete: Value being completed. May be empty. .. versionadded:: 8.0 """ from .shell_completion import CompletionItem type = "dir" if self.dir_okay and not self.file_okay else "file" return [CompletionItem(incomplete, type=type)] class Tuple(CompositeParamType): """The default behavior of Click is to apply a type on a value directly. This works well in most cases, except for when `nargs` is set to a fixed count and different types should be used for different items. In this case the :class:`Tuple` type can be used. This type can only be used if `nargs` is set to a fixed number. For more information see :ref:`tuple-type`. This can be selected by using a Python tuple literal as a type. :param types: a list of types that should be used for the tuple items. """ def __init__(self, types: cabc.Sequence[type[t.Any] | ParamType]) -> None: self.types: cabc.Sequence[ParamType] = [convert_type(ty) for ty in types] async def to_info_dict(self) -> dict[str, t.Any]: info_dict = await super().to_info_dict() info_dict["types"] = [await t.to_info_dict() for t in self.types] return info_dict @property def name(self) -> str: # type: ignore return f"<{' '.join(ty.name for ty in self.types)}>" @property def arity(self) -> int: # type: ignore return len(self.types) def convert( self, value: t.Any, param: Parameter | None, ctx: Context | None ) -> t.Any: len_type = len(self.types) len_value = len(value) if len_value != len_type: self.fail( ngettext( "{len_type} values are required, but {len_value} was given.", "{len_type} values are required, but {len_value} were given.", len_value, ).format(len_type=len_type, len_value=len_value), param=param, ctx=ctx, ) return tuple( ty(x, param, ctx) for ty, x in zip(self.types, value, strict=False) ) def convert_type(ty: t.Any | None, default: t.Any | None = None) -> ParamType: """Find the most appropriate :class:`ParamType` for the given Python type. If the type isn't provided, it can be inferred from a default value. """ guessed_type = False if ty is None and default is not None: if isinstance(default, (tuple, list)): # If the default is empty, ty will remain None and will # return STRING. if default: item = default[0] # A tuple of tuples needs to detect the inner types. # Can't call convert recursively because that would # incorrectly unwind the tuple to a single type. if isinstance(item, (tuple, list)): ty = tuple(map(type, item)) else: ty = type(item) else: ty = type(default) guessed_type = True if isinstance(ty, tuple): return Tuple(ty) if isinstance(ty, ParamType): return ty if ty is str or ty is None: return STRING if ty is int: return INT if ty is float: return FLOAT if ty is bool: return BOOL if guessed_type: return STRING if __debug__: try: if issubclass(ty, ParamType): raise AssertionError( f"Attempted to use an uninstantiated parameter type ({ty})." ) except TypeError: # ty is an instance (correct), so issubclass fails. pass return FuncParamType(ty) #: A dummy parameter type that just does nothing. From a user's #: perspective this appears to just be the same as `STRING` but #: internally no string conversion takes place if the input was bytes. #: This is usually useful when working with file paths as they can #: appear in bytes and unicode. #: #: For path related uses the :class:`Path` type is a better choice but #: there are situations where an unprocessed type is useful which is why #: it is is provided. #: #: .. versionadded:: 4.0 UNPROCESSED = UnprocessedParamType() #: A unicode string parameter type which is the implicit default. This #: can also be selected by using ``str`` as type. STRING = StringParamType() #: An integer parameter. This can also be selected by using ``int`` as #: type. INT = IntParamType() #: A floating point value parameter. This can also be selected by using #: ``float`` as type. FLOAT = FloatParamType() #: A boolean parameter. This is the default for boolean flags. This can #: also be selected by using ``bool`` as a type. BOOL = BoolParamType() #: A UUID parameter. UUID = UUIDParameterType() class OptionHelpExtra(t.TypedDict, total=False): envvars: tuple[str, ...] default: str range: str required: str asyncclick-8.3.0.5-async/src/asyncclick/utils.py000066400000000000000000000474411507140761400215660ustar00rootroot00000000000000from __future__ import annotations import collections.abc as cabc import os import re import sys import typing as t from functools import update_wrapper from types import ModuleType from types import TracebackType from ._compat import _default_text_stderr from ._compat import _default_text_stdout from ._compat import _find_binary_writer from ._compat import auto_wrap_for_ansi from ._compat import binary_streams from ._compat import open_stream from ._compat import should_strip_ansi from ._compat import strip_ansi from ._compat import text_streams from ._compat import WIN from .globals import resolve_color_default if t.TYPE_CHECKING: import typing_extensions as te P = te.ParamSpec("P") R = t.TypeVar("R") def _posixify(name: str) -> str: return "-".join(name.split()).lower() def safecall(func: t.Callable[P, R]) -> t.Callable[P, R | None]: """Wraps a function so that it swallows exceptions.""" def wrapper(*args: P.args, **kwargs: P.kwargs) -> R | None: try: return func(*args, **kwargs) except Exception: pass return None return update_wrapper(wrapper, func) def make_str(value: t.Any) -> str: """Converts a value into a valid string.""" if isinstance(value, bytes): try: return value.decode(sys.getfilesystemencoding()) except UnicodeError: return value.decode("utf-8", "replace") return str(value) def make_default_short_help(help: str, max_length: int = 45) -> str: """Returns a condensed version of help string.""" # Consider only the first paragraph. paragraph_end = help.find("\n\n") if paragraph_end != -1: help = help[:paragraph_end] # Collapse newlines, tabs, and spaces. words = help.split() if not words: return "" # The first paragraph started with a "no rewrap" marker, ignore it. if words[0] == "\b": words = words[1:] total_length = 0 last_index = len(words) - 1 for i, word in enumerate(words): total_length += len(word) + (i > 0) if total_length > max_length: # too long, truncate break if word[-1] == ".": # sentence end, truncate without "..." return " ".join(words[: i + 1]) if total_length == max_length and i != last_index: break # not at sentence end, truncate with "..." else: return " ".join(words) # no truncation needed # Account for the length of the suffix. total_length += len("...") # remove words until the length is short enough while i > 0: total_length -= len(words[i]) + (i > 0) if total_length <= max_length: break i -= 1 return " ".join(words[:i]) + "..." class LazyFile: """A lazy file works like a regular file but it does not fully open the file but it does perform some basic checks early to see if the filename parameter does make sense. This is useful for safely opening files for writing. """ def __init__( self, filename: str | os.PathLike[str], mode: str = "r", encoding: str | None = None, errors: str | None = "strict", atomic: bool = False, ): self.name: str = os.fspath(filename) self.mode = mode self.encoding = encoding self.errors = errors self.atomic = atomic self._f: t.IO[t.Any] | None self.should_close: bool if self.name == "-": self._f, self.should_close = open_stream(filename, mode, encoding, errors) else: if "r" in mode: # Open and close the file in case we're opening it for # reading so that we can catch at least some errors in # some cases early. open(filename, mode).close() self._f = None self.should_close = True def __getattr__(self, name: str) -> t.Any: return getattr(self.open(), name) def __repr__(self) -> str: if self._f is not None: return repr(self._f) return f"" def open(self) -> t.IO[t.Any]: """Opens the file if it's not yet open. This call might fail with a :exc:`FileError`. Not handling this error will produce an error that Click shows. """ if self._f is not None: return self._f try: rv, self.should_close = open_stream( self.name, self.mode, self.encoding, self.errors, atomic=self.atomic ) except OSError as e: from .exceptions import FileError raise FileError(self.name, hint=e.strerror) from e self._f = rv return rv def close(self) -> None: """Closes the underlying file, no matter what.""" if self._f is not None: self._f.close() def close_intelligently(self) -> None: """This function only closes the file if it was opened by the lazy file wrapper. For instance this will never close stdin. """ if self.should_close: self.close() def __enter__(self) -> LazyFile: return self def __exit__( self, exc_type: type[BaseException] | None, exc_value: BaseException | None, tb: TracebackType | None, ) -> None: self.close_intelligently() def __iter__(self) -> cabc.Iterator[t.AnyStr]: self.open() return iter(self._f) # type: ignore class KeepOpenFile: def __init__(self, file: t.IO[t.Any]) -> None: self._file: t.IO[t.Any] = file def __getattr__(self, name: str) -> t.Any: return getattr(self._file, name) def __enter__(self) -> KeepOpenFile: return self def __exit__( self, exc_type: type[BaseException] | None, exc_value: BaseException | None, tb: TracebackType | None, ) -> None: pass def __repr__(self) -> str: return repr(self._file) def __iter__(self) -> cabc.Iterator[t.AnyStr]: return iter(self._file) def echo( message: t.Any | None = None, file: t.IO[t.Any] | None = None, nl: bool = True, err: bool = False, color: bool | None = None, ) -> None: """Print a message and newline to stdout or a file. This should be used instead of :func:`print` because it provides better support for different data, files, and environments. Compared to :func:`print`, this does the following: - Ensures that the output encoding is not misconfigured on Linux. - Supports Unicode in the Windows console. - Supports writing to binary outputs, and supports writing bytes to text outputs. - Supports colors and styles on Windows. - Removes ANSI color and style codes if the output does not look like an interactive terminal. - Always flushes the output. :param message: The string or bytes to output. Other objects are converted to strings. :param file: The file to write to. Defaults to ``stdout``. :param err: Write to ``stderr`` instead of ``stdout``. :param nl: Print a newline after the message. Enabled by default. :param color: Force showing or hiding colors and other styles. By default Click will remove color if the output does not look like an interactive terminal. .. versionchanged:: 6.0 Support Unicode output on the Windows console. Click does not modify ``sys.stdout``, so ``sys.stdout.write()`` and ``print()`` will still not support Unicode. .. versionchanged:: 4.0 Added the ``color`` parameter. .. versionadded:: 3.0 Added the ``err`` parameter. .. versionchanged:: 2.0 Support colors on Windows if colorama is installed. """ if file is None: if err: file = _default_text_stderr() else: file = _default_text_stdout() # There are no standard streams attached to write to. For example, # pythonw on Windows. if file is None: return # Convert non bytes/text into the native string type. if message is not None and not isinstance(message, (str, bytes, bytearray)): out: str | bytes | bytearray | None = str(message) else: out = message if nl: out = out or "" if isinstance(out, str): out += "\n" else: out += b"\n" if not out: file.flush() return # If there is a message and the value looks like bytes, we manually # need to find the binary stream and write the message in there. # This is done separately so that most stream types will work as you # would expect. Eg: you can write to StringIO for other cases. if isinstance(out, (bytes, bytearray)): binary_file = _find_binary_writer(file) if binary_file is not None: file.flush() binary_file.write(out) binary_file.flush() return # ANSI style code support. For no message or bytes, nothing happens. # When outputting to a file instead of a terminal, strip codes. else: color = resolve_color_default(color) if should_strip_ansi(file, color): out = strip_ansi(out) elif WIN: if auto_wrap_for_ansi is not None: file = auto_wrap_for_ansi(file, color) # type: ignore elif not color: out = strip_ansi(out) file.write(out) # type: ignore file.flush() def get_binary_stream(name: t.Literal["stdin", "stdout", "stderr"]) -> t.BinaryIO: """Returns a system stream for byte processing. :param name: the name of the stream to open. Valid names are ``'stdin'``, ``'stdout'`` and ``'stderr'`` """ opener = binary_streams.get(name) if opener is None: raise TypeError(f"Unknown standard stream '{name}'") return opener() def get_text_stream( name: t.Literal["stdin", "stdout", "stderr"], encoding: str | None = None, errors: str | None = "strict", ) -> t.TextIO: """Returns a system stream for text processing. This usually returns a wrapped stream around a binary stream returned from :func:`get_binary_stream` but it also can take shortcuts for already correctly configured streams. :param name: the name of the stream to open. Valid names are ``'stdin'``, ``'stdout'`` and ``'stderr'`` :param encoding: overrides the detected default encoding. :param errors: overrides the default error mode. """ opener = text_streams.get(name) if opener is None: raise TypeError(f"Unknown standard stream '{name}'") return opener(encoding, errors) def open_file( filename: str | os.PathLike[str], mode: str = "r", encoding: str | None = None, errors: str | None = "strict", lazy: bool = False, atomic: bool = False, ) -> t.IO[t.Any]: """Open a file, with extra behavior to handle ``'-'`` to indicate a standard stream, lazy open on write, and atomic write. Similar to the behavior of the :class:`~click.File` param type. If ``'-'`` is given to open ``stdout`` or ``stdin``, the stream is wrapped so that using it in a context manager will not close it. This makes it possible to use the function without accidentally closing a standard stream: .. code-block:: python with open_file(filename) as f: ... :param filename: The name or Path of the file to open, or ``'-'`` for ``stdin``/``stdout``. :param mode: The mode in which to open the file. :param encoding: The encoding to decode or encode a file opened in text mode. :param errors: The error handling mode. :param lazy: Wait to open the file until it is accessed. For read mode, the file is temporarily opened to raise access errors early, then closed until it is read again. :param atomic: Write to a temporary file and replace the given file on close. .. versionadded:: 3.0 """ if lazy: return t.cast( "t.IO[t.Any]", LazyFile(filename, mode, encoding, errors, atomic=atomic) ) f, should_close = open_stream(filename, mode, encoding, errors, atomic=atomic) if not should_close: f = t.cast("t.IO[t.Any]", KeepOpenFile(f)) return f def format_filename( filename: str | bytes | os.PathLike[str] | os.PathLike[bytes], shorten: bool = False, ) -> str: """Format a filename as a string for display. Ensures the filename can be displayed by replacing any invalid bytes or surrogate escapes in the name with the replacement character ``�``. Invalid bytes or surrogate escapes will raise an error when written to a stream with ``errors="strict"``. This will typically happen with ``stdout`` when the locale is something like ``en_GB.UTF-8``. Many scenarios *are* safe to write surrogates though, due to PEP 538 and PEP 540, including: - Writing to ``stderr``, which uses ``errors="backslashreplace"``. - The system has ``LANG=C.UTF-8``, ``C``, or ``POSIX``. Python opens stdout and stderr with ``errors="surrogateescape"``. - None of ``LANG/LC_*`` are set. Python assumes ``LANG=C.UTF-8``. - Python is started in UTF-8 mode with ``PYTHONUTF8=1`` or ``-X utf8``. Python opens stdout and stderr with ``errors="surrogateescape"``. :param filename: formats a filename for UI display. This will also convert the filename into unicode without failing. :param shorten: this optionally shortens the filename to strip of the path that leads up to it. """ if shorten: filename = os.path.basename(filename) else: filename = os.fspath(filename) if isinstance(filename, bytes): filename = filename.decode(sys.getfilesystemencoding(), "replace") else: filename = filename.encode("utf-8", "surrogateescape").decode( "utf-8", "replace" ) return filename def get_app_dir(app_name: str, roaming: bool = True, force_posix: bool = False) -> str: r"""Returns the config folder for the application. The default behavior is to return whatever is most appropriate for the operating system. To give you an idea, for an app called ``"Foo Bar"``, something like the following folders could be returned: Mac OS X: ``~/Library/Application Support/Foo Bar`` Mac OS X (POSIX): ``~/.foo-bar`` Unix: ``~/.config/foo-bar`` Unix (POSIX): ``~/.foo-bar`` Windows (roaming): ``C:\Users\\AppData\Roaming\Foo Bar`` Windows (not roaming): ``C:\Users\\AppData\Local\Foo Bar`` .. versionadded:: 2.0 :param app_name: the application name. This should be properly capitalized and can contain whitespace. :param roaming: controls if the folder should be roaming or not on Windows. Has no effect otherwise. :param force_posix: if this is set to `True` then on any POSIX system the folder will be stored in the home folder with a leading dot instead of the XDG config home or darwin's application support folder. """ if WIN: key = "APPDATA" if roaming else "LOCALAPPDATA" folder = os.environ.get(key) if folder is None: folder = os.path.expanduser("~") return os.path.join(folder, app_name) if force_posix: return os.path.join(os.path.expanduser(f"~/.{_posixify(app_name)}")) if sys.platform == "darwin": return os.path.join( os.path.expanduser("~/Library/Application Support"), app_name ) return os.path.join( os.environ.get("XDG_CONFIG_HOME", os.path.expanduser("~/.config")), _posixify(app_name), ) class PacifyFlushWrapper: """This wrapper is used to catch and suppress BrokenPipeErrors resulting from ``.flush()`` being called on broken pipe during the shutdown/final-GC of the Python interpreter. Notably ``.flush()`` is always called on ``sys.stdout`` and ``sys.stderr``. So as to have minimal impact on any other cleanup code, and the case where the underlying file is not a broken pipe, all calls and attributes are proxied. """ def __init__(self, wrapped: t.IO[t.Any]) -> None: self.wrapped = wrapped def flush(self) -> None: try: self.wrapped.flush() except OSError as e: import errno if e.errno != errno.EPIPE: raise def __getattr__(self, attr: str) -> t.Any: return getattr(self.wrapped, attr) def _detect_program_name( path: str | None = None, _main: ModuleType | None = None ) -> str: """Determine the command used to run the program, for use in help text. If a file or entry point was executed, the file name is returned. If ``python -m`` was used to execute a module or package, ``python -m name`` is returned. This doesn't try to be too precise, the goal is to give a concise name for help text. Files are only shown as their name without the path. ``python`` is only shown for modules, and the full path to ``sys.executable`` is not shown. :param path: The Python file being executed. Python puts this in ``sys.argv[0]``, which is used by default. :param _main: The ``__main__`` module. This should only be passed during internal testing. .. versionadded:: 8.0 Based on command args detection in the Werkzeug reloader. :meta private: """ if _main is None: _main = sys.modules["__main__"] if not path: path = sys.argv[0] # The value of __package__ indicates how Python was called. It may # not exist if a setuptools script is installed as an egg. It may be # set incorrectly for entry points created with pip on Windows. # It is set to "" inside a Shiv or PEX zipapp. if getattr(_main, "__package__", None) in {None, ""} or ( os.name == "nt" and _main.__package__ == "" and not os.path.exists(path) and os.path.exists(f"{path}.exe") ): # Executed a file, like "python app.py". return os.path.basename(path) # Executed a module, like "python -m example". # Rewritten by Python from "-m script" to "/path/to/script.py". # Need to look at main module to determine how it was executed. py_module = t.cast(str, _main.__package__) name = os.path.splitext(os.path.basename(path))[0] # A submodule like "example.cli". if name != "__main__": py_module = f"{py_module}.{name}" return f"python -m {py_module.lstrip('.')}" def _expand_args( args: cabc.Iterable[str], *, user: bool = True, env: bool = True, glob_recursive: bool = True, ) -> list[str]: """Simulate Unix shell expansion with Python functions. See :func:`glob.glob`, :func:`os.path.expanduser`, and :func:`os.path.expandvars`. This is intended for use on Windows, where the shell does not do any expansion. It may not exactly match what a Unix shell would do. :param args: List of command line arguments to expand. :param user: Expand user home directory. :param env: Expand environment variables. :param glob_recursive: ``**`` matches directories recursively. .. versionchanged:: 8.1 Invalid glob patterns are treated as empty expansions rather than raising an error. .. versionadded:: 8.0 :meta private: """ from glob import glob out = [] for arg in args: if user: arg = os.path.expanduser(arg) if env: arg = os.path.expandvars(arg) try: matches = glob(arg, recursive=glob_recursive) except re.error: matches = [] if not matches: out.append(arg) else: out.extend(matches) return out asyncclick-8.3.0.5-async/tests/000077500000000000000000000000001507140761400162725ustar00rootroot00000000000000asyncclick-8.3.0.5-async/tests/conftest.py000066400000000000000000000014241507140761400204720ustar00rootroot00000000000000from threading import Thread import anyio import pytest from asyncclick.testing import CliRunner class SyncCliRunner(CliRunner): def invoke(self, *a, _sync=False, **k): fn = super().invoke if _sync: return fn(*a, **k) # anyio now protects against nested calls, so we use a thread result = None def f(): nonlocal result, fn async def r(): return await fn(*a, **k) result = anyio.run(r) ## , backend="trio") t = Thread(target=f, name="TEST") t.start() t.join() return result @pytest.fixture(scope="function") def runner(request): return SyncCliRunner() @pytest.fixture(scope="function") def arunner(request): return CliRunner() asyncclick-8.3.0.5-async/tests/test_arguments.py000066400000000000000000000435241507140761400217200ustar00rootroot00000000000000import sys from unittest import mock import pytest import asyncclick as click from asyncclick._utils import UNSET PY2 = False # churn @pytest.mark.anyio async def test_nargs_star(arunner): @click.command() @click.argument("src", nargs=-1) @click.argument("dst") def copy(src, dst): click.echo(f"src={'|'.join(src)}") click.echo(f"dst={dst}") sys.stdin = sys.__stdin__ sys.stdout = sys.__stdout__ result = await arunner.invoke(copy, ["foo.txt", "bar.txt", "dir"]) if result.exception: raise result.exception assert not result.exception assert result.output.splitlines() == ["src=foo.txt|bar.txt", "dst=dir"] def test_nargs_tup(runner): @click.command() @click.argument("name", nargs=1) @click.argument("point", nargs=2, type=click.INT) def copy(name, point): click.echo(f"name={name}") x, y = point click.echo(f"point={x}/{y}") result = runner.invoke(copy, ["peter", "1", "2"]) assert not result.exception assert result.output.splitlines() == ["name=peter", "point=1/2"] @pytest.mark.parametrize( "opts", [ dict(type=(str, int)), dict(type=click.Tuple([str, int])), dict(nargs=2, type=click.Tuple([str, int])), dict(nargs=2, type=(str, int)), ], ) def test_nargs_tup_composite(runner, opts): @click.command() @click.argument("item", **opts) def copy(item): name, id = item click.echo(f"name={name} id={id:d}") result = runner.invoke(copy, ["peter", "1"]) assert result.exception is None assert result.output.splitlines() == ["name=peter id=1"] def test_nargs_mismatch_with_tuple_type(): with pytest.raises(ValueError, match="nargs.*must be 2.*but it was 3"): @click.command() @click.argument("test", type=(str, int), nargs=3) def cli(_): pass def test_nargs_err(runner): @click.command() @click.argument("x") def copy(x): click.echo(x) result = runner.invoke(copy, ["foo"]) assert not result.exception assert result.output == "foo\n" result = runner.invoke(copy, ["foo", "bar"]) assert result.exit_code == 2 assert "Got unexpected extra argument (bar)" in result.output def test_bytes_args(runner, monkeypatch): @click.command() @click.argument("arg") def from_bytes(arg): assert isinstance(arg, str), ( "UTF-8 encoded argument should be implicitly converted to Unicode" ) # Simulate empty locale environment variables monkeypatch.setattr(sys, "getfilesystemencoding", lambda: "utf-8") monkeypatch.setattr(sys, "getdefaultencoding", lambda: "utf-8") # sys.stdin.encoding is readonly, needs some extra effort to patch. stdin = mock.Mock(wraps=sys.stdin) stdin.encoding = "utf-8" monkeypatch.setattr(sys, "stdin", stdin) runner.invoke( from_bytes, ["Something outside of ASCII range: 林".encode()], catch_exceptions=False, ) def test_file_args(runner): @click.command() @click.argument("input", type=click.File("rb")) @click.argument("output", type=click.File("wb")) def inout(input, output): while True: chunk = input.read(1024) if not chunk: break output.write(chunk) with runner.isolated_filesystem(): result = runner.invoke(inout, ["-", "hello.txt"], input="Hey!") assert result.output == "" assert result.exit_code == 0 with open("hello.txt", "rb") as f: assert f.read() == b"Hey!" result = runner.invoke(inout, ["hello.txt", "-"]) assert result.output == "Hey!" assert result.exit_code == 0 def test_path_allow_dash(runner): @click.command() @click.argument("input", type=click.Path(allow_dash=True)) def foo(input): click.echo(input) result = runner.invoke(foo, ["-"]) assert result.output == "-\n" assert result.exit_code == 0 def test_file_atomics(runner): @click.command() @click.argument("output", type=click.File("wb", atomic=True)) def inout(output): output.write(b"Foo bar baz\n") output.flush() with open(output.name, "rb") as f: old_content = f.read() assert old_content == b"OLD\n" with runner.isolated_filesystem(): with open("foo.txt", "wb") as f: f.write(b"OLD\n") result = runner.invoke(inout, ["foo.txt"], input="Hey!", catch_exceptions=False) assert result.output == "" assert result.exit_code == 0 with open("foo.txt", "rb") as f: assert f.read() == b"Foo bar baz\n" def test_stdout_default(runner): @click.command() @click.argument("output", type=click.File("w"), default="-") def inout(output): output.write("Foo bar baz\n") output.flush() result = runner.invoke(inout, []) assert not result.exception assert result.output == "Foo bar baz\n" assert result.stdout == "Foo bar baz\n" assert not result.stderr @pytest.mark.parametrize( ("nargs", "value", "expect"), [ (2, "", None), (2, "a", "Takes 2 values but 1 was given."), (2, "a b", ("a", "b")), (2, "a b c", "Takes 2 values but 3 were given."), (-1, "a b c", ("a", "b", "c")), (-1, "", ()), ], ) def test_nargs_envvar(runner, nargs, value, expect): if nargs == -1: param = click.argument("arg", envvar="X", nargs=nargs) else: param = click.option("--arg", envvar="X", nargs=nargs) @click.command() @param def cmd(arg): return arg result = runner.invoke(cmd, env={"X": value}, standalone_mode=False) if isinstance(expect, str): assert isinstance(result.exception, click.BadParameter) assert expect in result.exception.format_message() else: assert result.return_value == expect def test_nargs_envvar_only_if_values_empty(runner): @click.command() @click.argument("arg", envvar="X", nargs=-1) def cli(arg): return arg result = runner.invoke(cli, ["a", "b"], standalone_mode=False) assert result.return_value == ("a", "b") result = runner.invoke(cli, env={"X": "a"}, standalone_mode=False) assert result.return_value == ("a",) def test_empty_nargs(runner): @click.command() @click.argument("arg", nargs=-1) def cmd(arg): click.echo(f"arg:{'|'.join(arg)}") result = runner.invoke(cmd, []) assert result.exit_code == 0 assert result.output == "arg:\n" @click.command() @click.argument("arg", nargs=-1, required=True) def cmd2(arg): click.echo(f"arg:{'|'.join(arg)}") result = runner.invoke(cmd2, []) assert result.exit_code == 2 assert "Missing argument 'ARG...'" in result.output def test_missing_arg(runner): @click.command() @click.argument("arg") def cmd(arg): click.echo(f"arg:{arg}") result = runner.invoke(cmd, []) assert result.exit_code == 2 assert "Missing argument 'ARG'." in result.output @pytest.mark.parametrize( ("value", "expect_missing", "processed_value"), [ # Unspecified type of the argument fallback to string, so everything is # processed the click.STRING type. ("", False, ""), (" ", False, " "), ("foo", False, "foo"), ("12", False, "12"), (12, False, "12"), (12.1, False, "12.1"), (list(), False, "[]"), (tuple(), False, "()"), (set(), False, "set()"), (frozenset(), False, "frozenset()"), (dict(), False, "{}"), # None is a value that is allowed to be processed by a required argument # because at this stage, the process_value method happens after the default is # applied. (None, False, None), # An UNSET required argument will raise MissingParameter. (UNSET, True, None), ], ) @pytest.mark.anyio async def test_required_argument(value, expect_missing, processed_value): """Test how a required argument is processing the provided values.""" ctx = click.Context(click.Command("")) argument = click.Argument(["a"], required=True) if expect_missing: with pytest.raises(click.MissingParameter) as excinfo: await argument.process_value(ctx, value) assert str(excinfo.value) == "Missing parameter: a" else: value = await argument.process_value(ctx, value) assert value == processed_value def test_implicit_non_required(runner): @click.command() @click.argument("f", default="test") def cli(f): click.echo(f) result = runner.invoke(cli, []) assert result.exit_code == 0 assert result.output == "test\n" @pytest.mark.anyio async def test_deprecated_usage(arunner): @click.command() @click.argument("f", required=False, deprecated=True) def cli(f): click.echo(f) result = await arunner.invoke(cli, ["--help"], catch_exceptions=False) assert result.exit_code == 0, result.output assert "[F!]" in result.output @pytest.mark.parametrize("deprecated", [True, "USE B INSTEAD"]) def test_deprecated_warning(runner, deprecated): @click.command() @click.argument( "my-argument", required=False, deprecated=deprecated, default="default argument" ) def cli(my_argument: str): click.echo(f"{my_argument}") # defaults should not give a deprecated warning result = runner.invoke(cli, []) assert result.exit_code == 0, result.output assert "is deprecated" not in result.output result = runner.invoke(cli, ["hello"]) assert result.exit_code == 0, result.output assert "argument 'MY_ARGUMENT' is deprecated" in result.output if isinstance(deprecated, str): assert deprecated in result.output def test_deprecated_required(runner): with pytest.raises(ValueError, match="is deprecated and still required"): click.Argument(["a"], required=True, deprecated=True) @pytest.mark.anyio async def test_eat_options(arunner): @click.command() @click.option("-f") @click.argument("files", nargs=-1) def cmd(f, files): for filename in files: click.echo(filename) click.echo(f) result = await arunner.invoke(cmd, ["-f", "xx"]) assert result.output.splitlines() == ["xx"] result = await arunner.invoke(cmd, ["--", "-foo", "bar"]) assert result.output.splitlines() == ["-foo", "bar", ""] result = await arunner.invoke(cmd, ["-f", "-x", "--", "-foo", "bar"]) assert result.output.splitlines() == ["-foo", "bar", "-x"] @pytest.mark.anyio async def test_nargs_star_ordering(arunner): @click.command() @click.argument("a", nargs=-1) @click.argument("b") @click.argument("c") def cmd(a, b, c): for arg in (a, b, c): click.echo(arg) result = await arunner.invoke(cmd, ["a", "b", "c"]) assert result.output.splitlines() == ["('a',)", "b", "c"] def test_nargs_specified_plus_star_ordering(runner): @click.command() @click.argument("a", nargs=-1) @click.argument("b") @click.argument("c", nargs=2) def cmd(a, b, c): for arg in (a, b, c): click.echo(arg) result = runner.invoke(cmd, ["a", "b", "c", "d", "e", "f"]) assert result.output.splitlines() == ["('a', 'b', 'c')", "d", "('e', 'f')"] @pytest.mark.parametrize( ("argument_params", "args", "expected"), [ # Any iterable with the same number of arguments as nargs is valid. [{"nargs": 2, "default": (1, 2)}, [], (1, 2)], [{"nargs": 2, "default": (1.1, 2.2)}, [], (1, 2)], [{"nargs": 2, "default": ("1", "2")}, [], (1, 2)], [{"nargs": 2, "default": (None, None)}, [], (None, None)], [{"nargs": 2, "default": [1, 2]}, [], (1, 2)], [{"nargs": 2, "default": {1, 2}}, [], (1, 2)], [{"nargs": 2, "default": frozenset([1, 2])}, [], (1, 2)], [{"nargs": 2, "default": {1: "a", 2: "b"}}, [], (1, 2)], # Empty iterable is valid if default is None. [{"nargs": 2, "default": None}, [], None], # Arguments overrides the default. [{"nargs": 2, "default": (1, 2)}, ["3", "4"], (3, 4)], # Unbounded arguments are allowed to have a default. # See: https://github.com/pallets/click/issues/2164 [{"nargs": -1, "default": [42]}, [], (42,)], [{"nargs": -1, "default": None}, [], ()], [{"nargs": -1, "default": {1, 2, 3, 4, 5}}, [], (1, 2, 3, 4, 5)], ], ) def test_good_defaults_for_nargs(runner, argument_params, args, expected): @click.command() @click.argument("a", type=int, **argument_params) def cmd(a): click.echo(repr(a), nl=False) result = runner.invoke(cmd, args) assert result.output == repr(expected) @pytest.mark.parametrize( ("default", "message"), [ # Non-iterables defaults. ["Yo", "Error: Invalid value for '[A]...': Value must be an iterable."], ["", "Error: Invalid value for '[A]...': Value must be an iterable."], [True, "Error: Invalid value for '[A]...': Value must be an iterable."], [False, "Error: Invalid value for '[A]...': Value must be an iterable."], [12, "Error: Invalid value for '[A]...': Value must be an iterable."], [7.9, "Error: Invalid value for '[A]...': Value must be an iterable."], # Generator default. [(), "Error: Invalid value for '[A]...': Takes 2 values but 0 were given."], # Unset default. [UNSET, "Error: Missing argument 'A...'."], # Tuples defaults with wrong length. [ tuple(), "Error: Invalid value for '[A]...': Takes 2 values but 0 were given.", ], [(1,), "Error: Invalid value for '[A]...': Takes 2 values but 1 was given."], [ (1, 2, 3), "Error: Invalid value for '[A]...': Takes 2 values but 3 were given.", ], # Lists defaults with wrong length. [list(), "Error: Invalid value for '[A]...': Takes 2 values but 0 were given."], [[1], "Error: Invalid value for '[A]...': Takes 2 values but 1 was given."], [ [1, 2, 3], "Error: Invalid value for '[A]...': Takes 2 values but 3 were given.", ], # Sets defaults with wrong length. [set(), "Error: Invalid value for '[A]...': Takes 2 values but 0 were given."], [ set([1]), "Error: Invalid value for '[A]...': Takes 2 values but 1 was given.", ], [ set([1, 2, 3]), "Error: Invalid value for '[A]...': Takes 2 values but 3 were given.", ], # Frozensets defaults with wrong length. [ frozenset(), "Error: Invalid value for '[A]...': Takes 2 values but 0 were given.", ], [ frozenset([1]), "Error: Invalid value for '[A]...': Takes 2 values but 1 was given.", ], [ frozenset([1, 2, 3]), "Error: Invalid value for '[A]...': Takes 2 values but 3 were given.", ], # Dictionaries defaults with wrong length. [dict(), "Error: Invalid value for '[A]...': Takes 2 values but 0 were given."], [ {1: "a"}, "Error: Invalid value for '[A]...': Takes 2 values but 1 was given.", ], [ {1: "a", 2: "b", 3: "c"}, "Error: Invalid value for '[A]...': Takes 2 values but 3 were given.", ], ], ) def test_bad_defaults_for_nargs(runner, default, message): """Some defaults are not valid when nargs is set.""" @click.command() @click.argument("a", nargs=2, type=int, default=default) def cmd(a): click.echo(repr(a)) result = runner.invoke(cmd, []) assert message in result.stderr def test_multiple_param_decls_not_allowed(runner): with pytest.raises(TypeError): @click.command() @click.argument("x", click.Choice(["a", "b"])) def copy(x): click.echo(x) def test_multiple_not_allowed(): with pytest.raises(TypeError, match="multiple"): click.Argument(["a"], multiple=True) def test_subcommand_help(runner): @click.group() @click.argument("name") @click.argument("val") @click.option("--opt") @click.pass_context def cli(ctx, name, val, opt): ctx.obj = dict(name=name, val=val) @cli.command() @click.pass_obj def cmd(obj): click.echo(f"CMD for {obj['name']} with value {obj['val']}") result = runner.invoke(cli, ["foo", "bar", "cmd", "--help"]) if result.exception: raise result.exception assert "Usage: cli NAME VAL cmd [OPTIONS]" in result.output def test_nested_subcommand_help(runner): @click.group() @click.argument("arg1") @click.option("--opt1") def cli(arg1, opt1): pass @cli.group() @click.argument("arg2") @click.option("--opt2") def cmd(arg2, opt2): pass @cmd.command() def subcmd(): click.echo("subcommand") result = runner.invoke(cli, ["arg1", "cmd", "arg2", "subcmd", "--help"]) assert not result.exception assert "Usage: cli ARG1 cmd ARG2 subcmd [OPTIONS]" in result.output def test_when_argument_decorator_is_used_multiple_times_cls_is_preserved(): class CustomArgument(click.Argument): pass reusable_argument = click.argument("art", cls=CustomArgument) @click.command() @reusable_argument def foo(arg): pass @click.command() @reusable_argument def bar(arg): pass assert isinstance(foo.params[0], CustomArgument) assert isinstance(bar.params[0], CustomArgument) @pytest.mark.parametrize( "args_one,args_two", [ ( ("aardvark",), ("aardvark",), ), ], ) def test_duplicate_names_warning(runner, args_one, args_two): @click.command() @click.argument(*args_one) @click.argument(*args_two) def cli(one, two): pass with pytest.warns(UserWarning): runner.invoke(cli, []) asyncclick-8.3.0.5-async/tests/test_basic.py000066400000000000000000000501721507140761400207710ustar00rootroot00000000000000from __future__ import annotations import enum import os from itertools import chain import pytest import asyncclick as click from asyncclick._utils import UNSET def test_basic_functionality(runner): @click.command() def cli(): """Hello World!""" click.echo("I EXECUTED") result = runner.invoke(cli, ["--help"]) assert not result.exception assert "Hello World!" in result.output assert "Show this message and exit." in result.output assert result.exit_code == 0 assert "I EXECUTED" not in result.output result = runner.invoke(cli, []) assert not result.exception assert "I EXECUTED" in result.output assert result.exit_code == 0 def test_repr(): @click.command() def command(): pass @click.group() def group(): pass @group.command() def subcommand(): pass assert repr(command) == "" assert repr(group) == "" assert repr(subcommand) == "" @pytest.mark.anyio async def test_return_values(): @click.command() async def cli(): return 42 async with await cli.make_context("foo", []) as ctx: rv = await cli.invoke(ctx) assert rv == 42 def test_basic_group(runner): @click.group() def cli(): """This is the root.""" click.echo("ROOT EXECUTED") @cli.command() def subcommand(): """This is a subcommand.""" click.echo("SUBCOMMAND EXECUTED") result = runner.invoke(cli, ["--help"]) assert not result.exception assert "COMMAND [ARGS]..." in result.output assert "This is the root" in result.output assert "This is a subcommand." in result.output assert result.exit_code == 0 assert "ROOT EXECUTED" not in result.output result = runner.invoke(cli, ["subcommand"]) if result.exception: raise result.exception assert result.exit_code == 0 assert "ROOT EXECUTED" in result.output assert "SUBCOMMAND EXECUTED" in result.output def test_group_commands_dict(runner): """A Group can be built with a dict of commands.""" @click.command() def sub(): click.echo("sub", nl=False) cli = click.Group(commands={"other": sub}) result = runner.invoke(cli, ["other"]) assert result.output == "sub" def test_group_from_list(runner): """A Group can be built with a list of commands.""" @click.command() def sub(): click.echo("sub", nl=False) cli = click.Group(commands=[sub]) result = runner.invoke(cli, ["sub"]) assert result.output == "sub" @pytest.mark.parametrize( ("args", "expect"), [ ([], "S:[no value]"), (["--s=42"], "S:[42]"), (["--s"], "Error: Option '--s' requires an argument."), (["--s="], "S:[]"), (["--s=\N{SNOWMAN}"], "S:[\N{SNOWMAN}]"), ], ) def test_string_option(runner, args, expect): @click.command() @click.option("--s", default="no value") def cli(s): click.echo(f"S:[{s}]") result = runner.invoke(cli, args) assert expect in result.output if expect.startswith("Error:"): assert result.exception is not None else: assert result.exception is None @pytest.mark.parametrize( ("args", "expect"), [ ([], "I:[84]"), (["--i=23"], "I:[46]"), (["--i=x"], "Error: Invalid value for '--i': 'x' is not a valid integer."), ], ) def test_int_option(runner, args, expect): @click.command() @click.option("--i", default=42) def cli(i): click.echo(f"I:[{i * 2}]") result = runner.invoke(cli, args) assert expect in result.output if expect.startswith("Error:"): assert result.exception is not None else: assert result.exception is None @pytest.mark.parametrize( ("args", "expect"), [ ([], "U:[ba122011-349f-423b-873b-9d6a79c688ab]"), ( ["--u=821592c1-c50e-4971-9cd6-e89dc6832f86"], "U:[821592c1-c50e-4971-9cd6-e89dc6832f86]", ), (["--u=x"], "Error: Invalid value for '--u': 'x' is not a valid UUID."), ], ) def test_uuid_option(runner, args, expect): @click.command() @click.option( "--u", default="ba122011-349f-423b-873b-9d6a79c688ab", type=click.UUID ) def cli(u): click.echo(f"U:[{u}]") result = runner.invoke(cli, args) assert expect in result.output if expect.startswith("Error:"): assert result.exception is not None else: assert result.exception is None @pytest.mark.parametrize( ("args", "expect"), [ ([], "F:[42.0]"), ("--f=23.5", "F:[23.5]"), ("--f=x", "Error: Invalid value for '--f': 'x' is not a valid float."), ], ) def test_float_option(runner, args, expect): @click.command() @click.option("--f", default=42.0) def cli(f): click.echo(f"F:[{f}]") result = runner.invoke(cli, args) assert expect in result.output if expect.startswith("Error:"): assert result.exception is not None else: assert result.exception is None @pytest.mark.parametrize( ("args", "default", "expect"), [ (["--on"], True, True), (["--on"], False, True), (["--on"], None, True), (["--on"], UNSET, True), (["--off"], True, False), (["--off"], False, False), (["--off"], None, False), (["--off"], UNSET, False), ([], True, True), ([], False, False), ([], None, None), ([], UNSET, False), ], ) def test_boolean_switch(runner, args, default, expect): @click.command() @click.option("--on/--off", default=default) def cli(on): return on result = runner.invoke(cli, args, standalone_mode=False) assert result.return_value is expect @pytest.mark.parametrize( ("default", "args", "expect"), ( (True, ["--f"], True), (True, [], True), (False, ["--f"], True), (False, [], False), # Boolean flags have a 3-states logic. # See: https://github.com/pallets/click/issues/3024#issue-3285556668 (None, ["--f"], True), (None, [], None), ), ) def test_boolean_flag(runner, default, args, expect): @click.command() @click.option("--f", is_flag=True, default=default) def cli(f): return f result = runner.invoke(cli, args, standalone_mode=False) assert result.return_value is expect @pytest.mark.parametrize( ("value", "expect"), chain( ((x, "True") for x in ("1", "true", "t", "yes", "y", "on")), ((x, "False") for x in ("0", "false", "f", "no", "n", "off")), ), ) def test_boolean_conversion(runner, value, expect): @click.command() @click.option("--flag", type=bool) def cli(flag): click.echo(flag, nl=False) result = runner.invoke(cli, ["--flag", value]) assert result.output == expect result = runner.invoke(cli, ["--flag", value.title()]) assert result.output == expect @pytest.mark.parametrize( ("default", "args", "expected"), # These test cases are similar to the ones in # tests/test_options.py::test_default_dual_option_callback, so keep them in sync. ( # Each option is returning its own flag_value, whatever the default is. (True, ["--upper"], "upper"), (True, ["--lower"], "lower"), (False, ["--upper"], "upper"), (False, ["--lower"], "lower"), (None, ["--upper"], "upper"), (None, ["--lower"], "lower"), (UNSET, ["--upper"], "upper"), (UNSET, ["--lower"], "lower"), # Check that the last option wins when both are specified. (True, ["--upper", "--lower"], "lower"), (True, ["--lower", "--upper"], "upper"), # Check that the default is returned as-is when no option is specified. ("upper", [], "upper"), ("lower", [], "lower"), ("uPPer", [], "uPPer"), ("lOwEr", [], "lOwEr"), (" ᕕ( ᐛ )ᕗ ", [], " ᕕ( ᐛ )ᕗ "), (None, [], None), # Default is normalized to None if it is UNSET. (UNSET, [], None), # Special case: if default=True and flag_value is set, the value returned is the # flag_value, not the True Python value itself. (True, [], "upper"), # Non-string defaults are process as strings by the default Parameter's type. (False, [], "False"), (42, [], "42"), (12.3, [], "12.3"), ), ) def test_flag_value_dual_options(runner, default, args, expected): """Check how default is processed when options compete for the same variable name. Covers the regression reported in https://github.com/pallets/click/issues/3024#issuecomment-3146199461 """ @click.command() @click.option("--upper", "case", flag_value="upper", default=default) @click.option("--lower", "case", flag_value="lower") def cli(case): click.echo(repr(case), nl=False) result = runner.invoke(cli, args) assert result.output == repr(expected) def test_file_option(runner): @click.command() @click.option("--file", type=click.File("w")) def input(file): file.write("Hello World!\n") @click.command() @click.option("--file", type=click.File("r")) def output(file): click.echo(file.read()) with runner.isolated_filesystem(): result_in = runner.invoke(input, ["--file=example.txt"]) result_out = runner.invoke(output, ["--file=example.txt"]) assert not result_in.exception assert result_in.output == "" assert not result_out.exception assert result_out.output == "Hello World!\n\n" def test_file_lazy_mode(runner): do_io = False @click.command() @click.option("--file", type=click.File("w")) def input(file): if do_io: file.write("Hello World!\n") @click.command() @click.option("--file", type=click.File("r")) def output(file): pass with runner.isolated_filesystem(): os.mkdir("example.txt") do_io = True result_in = runner.invoke(input, ["--file=example.txt"]) assert result_in.exit_code == 1 do_io = False result_in = runner.invoke(input, ["--file=example.txt"]) assert result_in.exit_code == 0 result_out = runner.invoke(output, ["--file=example.txt"]) assert result_out.exception @click.command() @click.option("--file", type=click.File("w", lazy=False)) def input_non_lazy(file): file.write("Hello World!\n") with runner.isolated_filesystem(): os.mkdir("example.txt") result_in = runner.invoke(input_non_lazy, ["--file=example.txt"]) assert result_in.exit_code == 2 assert "Invalid value for '--file': 'example.txt'" in result_in.output def test_path_option(runner): @click.command() @click.option("-O", type=click.Path(file_okay=False, exists=True, writable=True)) def write_to_dir(o): with open(os.path.join(o, "foo.txt"), "wb") as f: f.write(b"meh\n") with runner.isolated_filesystem(): os.mkdir("test") result = runner.invoke(write_to_dir, ["-O", "test"]) assert not result.exception with open("test/foo.txt", "rb") as f: assert f.read() == b"meh\n" result = runner.invoke(write_to_dir, ["-O", "test/foo.txt"]) assert "is a file" in result.output @click.command() @click.option("-f", type=click.Path(exists=True)) def showtype(f): click.echo(f"is_file={os.path.isfile(f)}") click.echo(f"is_dir={os.path.isdir(f)}") with runner.isolated_filesystem(): result = runner.invoke(showtype, ["-f", "xxx"]) assert "does not exist" in result.output result = runner.invoke(showtype, ["-f", "."]) assert "is_file=False" in result.output assert "is_dir=True" in result.output @click.command() @click.option("-f", type=click.Path()) def exists(f): click.echo(f"exists={os.path.exists(f)}") with runner.isolated_filesystem(): result = runner.invoke(exists, ["-f", "xxx"]) assert "exists=False" in result.output result = runner.invoke(exists, ["-f", "."]) assert "exists=True" in result.output def test_choice_option(runner): @click.command() @click.option("--method", type=click.Choice(["foo", "bar", "baz"])) def cli(method): click.echo(method) result = runner.invoke(cli, ["--method=foo"]) assert not result.exception assert result.output == "foo\n" result = runner.invoke(cli, ["--method=meh"]) assert result.exit_code == 2 assert ( "Invalid value for '--method': 'meh' is not one of 'foo', 'bar', 'baz'." in result.output ) result = runner.invoke(cli, ["--help"]) assert "--method [foo|bar|baz]" in result.output def test_choice_argument(runner): @click.command() @click.argument("method", type=click.Choice(["foo", "bar", "baz"])) def cli(method): click.echo(method) result = runner.invoke(cli, ["foo"]) assert not result.exception assert result.output == "foo\n" result = runner.invoke(cli, ["meh"]) assert result.exit_code == 2 assert ( "Invalid value for '{foo|bar|baz}': 'meh' is not one of 'foo'," " 'bar', 'baz'." in result.output ) result = runner.invoke(cli, ["--help"]) assert "{foo|bar|baz}" in result.output def test_choice_argument_enum(runner): class MyEnum(str, enum.Enum): FOO = "foo-value" BAR = "bar-value" BAZ = "baz-value" @click.command() @click.argument("method", type=click.Choice(MyEnum, case_sensitive=False)) def cli(method: MyEnum): assert isinstance(method, MyEnum) click.echo(method) result = runner.invoke(cli, ["foo"]) assert result.output == "foo-value\n" assert not result.exception result = runner.invoke(cli, ["meh"]) assert result.exit_code == 2 assert ( "Invalid value for '{foo|bar|baz}': 'meh' is not one of 'foo'," " 'bar', 'baz'." in result.output ) result = runner.invoke(cli, ["--help"]) assert "{foo|bar|baz}" in result.output def test_choice_argument_custom_type(runner): class MyClass: def __init__(self, value: str) -> None: self.value = value def __str__(self) -> str: return self.value @click.command() @click.argument( "method", type=click.Choice([MyClass("foo"), MyClass("bar"), MyClass("baz")]) ) def cli(method: MyClass): assert isinstance(method, MyClass) click.echo(method) result = runner.invoke(cli, ["foo"]) assert not result.exception assert result.output == "foo\n" result = runner.invoke(cli, ["meh"]) assert result.exit_code == 2 assert ( "Invalid value for '{foo|bar|baz}': 'meh' is not one of 'foo'," " 'bar', 'baz'." in result.output ) result = runner.invoke(cli, ["--help"]) assert "{foo|bar|baz}" in result.output def test_choice_argument_none(runner): @click.command() @click.argument( "method", type=click.Choice(["not-none", None], case_sensitive=False) ) def cli(method: str | None): assert isinstance(method, str) or method is None click.echo(repr(method), nl=False) result = runner.invoke(cli, ["not-none"]) assert not result.exception assert result.output == repr("not-none") result = runner.invoke(cli, ["none"]) assert not result.exception assert result.output == repr(None) result = runner.invoke(cli, []) assert result.exception assert ( "Error: Missing argument '{not-none|none}'. " "Choose from:\n\tnot-none,\n\tnone\n" in result.stderr ) result = runner.invoke(cli, ["--help"]) assert result.output.startswith("Usage: cli [OPTIONS] {not-none|none}\n") def test_datetime_option_default(runner): @click.command() @click.option("--start_date", type=click.DateTime()) def cli(start_date): click.echo(start_date.strftime("%Y-%m-%dT%H:%M:%S")) result = runner.invoke(cli, ["--start_date=2015-09-29"]) assert not result.exception assert result.output == "2015-09-29T00:00:00\n" result = runner.invoke(cli, ["--start_date=2015-09-29T09:11:22"]) assert not result.exception assert result.output == "2015-09-29T09:11:22\n" result = runner.invoke(cli, ["--start_date=2015-09"]) assert result.exit_code == 2 assert ( "Invalid value for '--start_date': '2015-09' does not match the formats" " '%Y-%m-%d', '%Y-%m-%dT%H:%M:%S', '%Y-%m-%d %H:%M:%S'." ) in result.output result = runner.invoke(cli, ["--help"]) assert ( "--start_date [%Y-%m-%d|%Y-%m-%dT%H:%M:%S|%Y-%m-%d %H:%M:%S]" in result.output ) def test_datetime_option_custom(runner): @click.command() @click.option("--start_date", type=click.DateTime(formats=["%A %B %d, %Y"])) def cli(start_date): click.echo(start_date.strftime("%Y-%m-%dT%H:%M:%S")) result = runner.invoke(cli, ["--start_date=Wednesday June 05, 2010"]) assert not result.exception assert result.output == "2010-06-05T00:00:00\n" def test_required_option(runner): @click.command() @click.option("--foo", required=True) def cli(foo): click.echo(foo) result = runner.invoke(cli, []) assert result.exit_code == 2 assert "Missing option '--foo'" in result.output def test_evaluation_order(runner): called = [] def memo(ctx, param, value): called.append(value) return value @click.command() @click.option("--missing", default="missing", is_eager=False, callback=memo) @click.option("--eager-flag1", flag_value="eager1", is_eager=True, callback=memo) @click.option("--eager-flag2", flag_value="eager2", is_eager=True, callback=memo) @click.option("--eager-flag3", flag_value="eager3", is_eager=True, callback=memo) @click.option("--normal-flag1", flag_value="normal1", is_eager=False, callback=memo) @click.option("--normal-flag2", flag_value="normal2", is_eager=False, callback=memo) @click.option("--normal-flag3", flag_value="normal3", is_eager=False, callback=memo) def cli(**x): pass result = runner.invoke( cli, [ "--eager-flag2", "--eager-flag1", "--normal-flag2", "--eager-flag3", "--normal-flag3", "--normal-flag3", "--normal-flag1", "--normal-flag1", ], ) assert not result.exception assert called == [ "eager2", "eager1", "eager3", "normal2", "normal3", "normal1", "missing", ] def test_hidden_option(runner): @click.command() @click.option("--nope", hidden=True) def cli(nope): click.echo(nope) result = runner.invoke(cli, ["--help"]) assert result.exit_code == 0 assert "--nope" not in result.output def test_hidden_command(runner): @click.group() def cli(): pass @cli.command(hidden=True) def nope(): pass result = runner.invoke(cli, ["--help"]) assert result.exit_code == 0 assert "nope" not in result.output def test_hidden_group(runner): @click.group() def cli(): pass @cli.group(hidden=True) def subgroup(): pass @subgroup.command() def nope(): pass result = runner.invoke(cli, ["--help"]) assert result.exit_code == 0 assert "subgroup" not in result.output assert "nope" not in result.output def test_summary_line(runner): @click.group() def cli(): pass @cli.command() def cmd(): """ Summary line without period Here is a sentence. And here too. """ pass result = runner.invoke(cli, ["--help"]) assert "Summary line without period" in result.output assert "Here is a sentence." not in result.output def test_help_invalid_default(runner): cli = click.Command( "cli", params=[ click.Option( ["-a"], type=click.Path(exists=True), default="not found", show_default=True, ), ], ) result = runner.invoke(cli, ["--help"]) assert result.exit_code == 0 assert "default: not found" in result.output asyncclick-8.3.0.5-async/tests/test_chain.py000066400000000000000000000132501507140761400207660ustar00rootroot00000000000000import sys import pytest import asyncclick as click def debug(): click.echo( f"{sys._getframe(1).f_code.co_name}" f"={'|'.join(click.get_current_context().args)}" ) def test_basic_chaining(runner): @click.group(chain=True) def cli(): pass @cli.command("sdist") def sdist(): click.echo("sdist called") @cli.command("bdist") def bdist(): click.echo("bdist called") result = runner.invoke(cli, ["bdist", "sdist", "bdist"]) assert not result.exception assert result.output.splitlines() == [ "bdist called", "sdist called", "bdist called", ] @pytest.mark.parametrize( ("args", "expect"), [ (["--help"], "COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]..."), (["--help"], "ROOT HELP"), (["sdist", "--help"], "SDIST HELP"), (["bdist", "--help"], "BDIST HELP"), (["bdist", "sdist", "--help"], "SDIST HELP"), ], ) def test_chaining_help(runner, args, expect): @click.group(chain=True) def cli(): """ROOT HELP""" pass @cli.command("sdist") def sdist(): """SDIST HELP""" click.echo("sdist called") @cli.command("bdist") def bdist(): """BDIST HELP""" click.echo("bdist called") result = runner.invoke(cli, args) assert not result.exception assert expect in result.output def test_chaining_with_options(runner): @click.group(chain=True) def cli(): pass @cli.command("sdist") @click.option("--format") def sdist(format): click.echo(f"sdist called {format}") @cli.command("bdist") @click.option("--format") def bdist(format): click.echo(f"bdist called {format}") result = runner.invoke(cli, ["bdist", "--format=1", "sdist", "--format=2"]) assert not result.exception assert result.output.splitlines() == ["bdist called 1", "sdist called 2"] @pytest.mark.parametrize(("chain", "expect"), [(False, "1"), (True, "[]")]) def test_no_command_result_callback(runner, chain, expect): """When a group has ``invoke_without_command=True``, the result callback is always invoked. A regular group invokes it with its return value, a chained group with ``[]``. """ @click.group(invoke_without_command=True, chain=chain) def cli(): return 1 @cli.result_callback() def process_result(result): click.echo(result, nl=False) result = runner.invoke(cli, []) assert result.output == expect def test_chaining_with_arguments(runner): @click.group(chain=True) def cli(): pass @cli.command("sdist") @click.argument("format") def sdist(format): click.echo(f"sdist called {format}") @cli.command("bdist") @click.argument("format") def bdist(format): click.echo(f"bdist called {format}") result = runner.invoke(cli, ["bdist", "1", "sdist", "2"]) assert not result.exception assert result.output.splitlines() == ["bdist called 1", "sdist called 2"] @pytest.mark.parametrize( ("args", "input", "expect"), [ (["-f", "-"], "foo\nbar", ["foo", "bar"]), (["-f", "-", "strip"], "foo \n bar", ["foo", "bar"]), (["-f", "-", "strip", "uppercase"], "foo \n bar", ["FOO", "BAR"]), ], ) def test_pipeline(runner, args, input, expect): @click.group(chain=True, invoke_without_command=True) @click.option("-f", type=click.File("r")) def cli(f): pass @cli.result_callback() def process_pipeline(processors, f): iterator = (x.rstrip("\r\n") for x in f) for processor in processors: iterator = processor(iterator) for item in iterator: click.echo(item) @cli.command("uppercase") def make_uppercase(): def processor(iterator): for line in iterator: yield line.upper() return processor @cli.command("strip") def make_strip(): def processor(iterator): for line in iterator: yield line.strip() return processor result = runner.invoke(cli, args, input=input) assert not result.exception assert result.output.splitlines() == expect def test_args_and_chain(runner): @click.group(chain=True) def cli(): debug() @cli.command() def a(): debug() @cli.command() def b(): debug() @cli.command() def c(): debug() result = runner.invoke(cli, ["a", "b", "c"]) assert not result.exception assert result.output.splitlines() == ["cli=", "a=", "b=", "c="] def test_group_arg_behavior(runner): with pytest.raises(RuntimeError): @click.group(chain=True) @click.argument("forbidden", required=False) def bad_cli(): pass with pytest.raises(RuntimeError): @click.group(chain=True) @click.argument("forbidden", nargs=-1) def bad_cli2(): pass @click.group(chain=True) @click.argument("arg") def cli(arg): click.echo(f"cli:{arg}") @cli.command() def a(): click.echo("a") result = runner.invoke(cli, ["foo", "a"]) assert not result.exception assert result.output.splitlines() == ["cli:foo", "a"] @pytest.mark.xfail def test_group_chaining(runner): @click.group(chain=True) def cli(): debug() @cli.group() def l1a(): debug() @l1a.command() def l2a(): debug() @l1a.command() def l2b(): debug() @cli.command() def l1b(): debug() result = runner.invoke(cli, ["l1a", "l2a", "l1b"]) assert not result.exception assert result.output.splitlines() == ["cli=", "l1a=", "l2a=", "l1b="] asyncclick-8.3.0.5-async/tests/test_command_decorators.py000066400000000000000000000035461507140761400235560ustar00rootroot00000000000000import pytest import asyncclick as click def test_command_no_parens(runner): @click.command def cli(): click.echo("hello") result = runner.invoke(cli) assert result.exception is None assert result.output == "hello\n" def test_custom_command_no_parens(runner): class CustomCommand(click.Command): pass class CustomGroup(click.Group): command_class = CustomCommand @click.group(cls=CustomGroup) def grp(): pass @grp.command def cli(): click.echo("hello custom command class") result = runner.invoke(cli) assert result.exception is None assert result.output == "hello custom command class\n" def test_group_no_parens(runner): @click.group def grp(): click.echo("grp1") @grp.command def cmd1(): click.echo("cmd1") @grp.group def grp2(): click.echo("grp2") @grp2.command def cmd2(): click.echo("cmd2") result = runner.invoke(grp, ["cmd1"]) assert result.exception is None assert result.output == "grp1\ncmd1\n" result = runner.invoke(grp, ["grp2", "cmd2"]) assert result.exception is None assert result.output == "grp1\ngrp2\ncmd2\n" def test_params_argument(runner): opt = click.Argument(["a"]) @click.command(params=[opt]) @click.argument("b") def cli(a, b): click.echo(f"{a} {b}") assert cli.params[0].name == "a" assert cli.params[1].name == "b" result = runner.invoke(cli, ["1", "2"]) assert result.output == "1 2\n" @pytest.mark.parametrize( "name", [ "init_data", "init_data_command", "init_data_cmd", "init_data_group", "init_data_grp", ], ) def test_generate_name(name: str) -> None: def f(): pass f.__name__ = name f = click.command(f) assert f.name == "init-data" asyncclick-8.3.0.5-async/tests/test_commands.py000066400000000000000000000422611507140761400215110ustar00rootroot00000000000000import re from inspect import iscoroutine import pytest import asyncclick as click def test_other_command_invoke(runner): @click.command() @click.pass_context def cli(ctx): return ctx.invoke(other_cmd, arg=42) @click.command() @click.argument("arg", type=click.INT) def other_cmd(arg): click.echo(arg) result = runner.invoke(cli, []) if result.exception: raise result.exception assert result.output == "42\n" @pytest.mark.anyio async def test_other_command_forward(runner): cli = click.Group() @cli.command() @click.option("--count", default=1) def test(count): click.echo(f"Count: {count:d}") @cli.command() @click.option("--count", default=1) @click.pass_context async def dist(ctx, count): await ctx.forward(test) await ctx.invoke(test, count=42) result = await runner.invoke(cli, ["dist"], _sync=True) if result.exception: raise result.exception assert result.output == "Count: 1\nCount: 42\n" @pytest.mark.anyio async def test_forwarded_params_consistency(runner): cli = click.Group() @cli.command() @click.option("-a") @click.pass_context def first(ctx, **kwargs): click.echo(f"{ctx.params}") @cli.command() @click.option("-a") @click.option("-b") @click.pass_context async def second(ctx, **kwargs): click.echo(f"{ctx.params}") await ctx.forward(first) result = runner.invoke(cli, ["second", "-a", "foo", "-b", "bar"]) if result.exception: raise result.exception assert result.output == "{'a': 'foo', 'b': 'bar'}\n{'a': 'foo', 'b': 'bar'}\n" def test_auto_shorthelp(runner): @click.group() def cli(): pass @cli.command() def short(): """This is a short text.""" @cli.command() def special_chars(): """Login and store the token in ~/.netrc.""" @cli.command() def long(): """This is a long text that is too long to show as short help and will be truncated instead.""" result = runner.invoke(cli, ["--help"]) assert ( re.search( r"Commands:\n\s+" r"long\s+This is a long text that is too long to show as short help" r"\.\.\.\n\s+" r"short\s+This is a short text\.\n\s+" r"special-chars\s+Login and store the token in ~/.netrc\.\s*", result.output, ) is not None ) def test_command_no_args_is_help(runner): result = runner.invoke(click.Command("test", no_args_is_help=True)) assert result.exit_code == 2 assert "Show this message and exit." in result.output def test_default_maps(runner): @click.group() def cli(): pass @cli.command() @click.option("--name", default="normal") def foo(name): click.echo(name) result = runner.invoke(cli, ["foo"], default_map={"foo": {"name": "changed"}}) if result.exception: raise result.exception assert result.output == "changed\n" @pytest.mark.parametrize( ("args", "exit_code", "expect"), [ (["obj1"], 2, "Error: Missing command."), (["obj1", "--help"], 0, "Show this message and exit."), (["obj1", "move"], 0, "obj=obj1\nmove\n"), ([], 2, "Show this message and exit."), ], ) def test_group_with_args(runner, args, exit_code, expect): @click.group() @click.argument("obj") def cli(obj): click.echo(f"obj={obj}") @cli.command() def move(): click.echo("move") result = runner.invoke(cli, args) assert result.exit_code == exit_code assert expect in result.output def test_custom_parser(runner): import optparse @click.group() def cli(): pass class OptParseCommand(click.Command): def __init__(self, name, parser, callback): super().__init__(name) self.parser = parser self.callback = callback async def parse_args(self, ctx, args): try: opts, args = parser.parse_args(args) except Exception as e: ctx.fail(str(e)) ctx.args = args ctx.params = vars(opts) def get_usage(self, ctx): return self.parser.get_usage() def get_help(self, ctx): return self.parser.format_help() async def invoke(self, ctx): rv = ctx.invoke(self.callback, ctx.args, **ctx.params) if iscoroutine(rv): await rv parser = optparse.OptionParser(usage="Usage: foo test [OPTIONS]") parser.add_option( "-f", "--file", dest="filename", help="write report to FILE", metavar="FILE" ) parser.add_option( "-q", "--quiet", action="store_false", dest="verbose", default=True, help="don't print status messages to stdout", ) def test_callback(args, filename, verbose): click.echo(" ".join(args)) click.echo(filename) click.echo(verbose) cli.add_command(OptParseCommand("test", parser, test_callback)) result = runner.invoke(cli, ["test", "-f", "f.txt", "-q", "q1.txt", "q2.txt"]) if result.exception is not None: raise result.exception assert result.output.splitlines() == ["q1.txt q2.txt", "f.txt", "False"] result = runner.invoke(cli, ["test", "--help"]) if result.exception is not None: raise result.exception assert result.output.splitlines() == [ "Usage: foo test [OPTIONS]", "", "Options:", " -h, --help show this help message and exit", " -f FILE, --file=FILE write report to FILE", " -q, --quiet don't print status messages to stdout", ] def test_object_propagation(runner): for chain in False, True: @click.group(chain=chain) @click.option("--debug/--no-debug", default=False) @click.pass_context def cli(ctx, debug): if ctx.obj is None: ctx.obj = {} ctx.obj["DEBUG"] = debug @cli.command() @click.pass_context def sync(ctx): click.echo(f"Debug is {'on' if ctx.obj['DEBUG'] else 'off'}") result = runner.invoke(cli, ["sync"]) assert result.exception is None assert result.output == "Debug is off\n" def test_other_command_invoke_with_defaults(runner): @click.command() @click.pass_context def cli(ctx): return ctx.invoke(other_cmd) @click.command() @click.option("-a", type=click.INT, default=42) @click.option("-b", type=click.INT, default="15") @click.option("-c", multiple=True) @click.pass_context def other_cmd(ctx, a, b, c): return ctx.info_name, a, b, c result = runner.invoke(cli, standalone_mode=False) # invoke should type cast default values, str becomes int, empty # multiple should be empty tuple instead of None assert result.return_value == ("other", 42, 15, ()) def test_invoked_subcommand(runner): @click.group(invoke_without_command=True) @click.pass_context async def cli(ctx): if ctx.invoked_subcommand is None: click.echo("no subcommand, use default") await ctx.invoke(sync) else: click.echo("invoke subcommand") @cli.command() def sync(): click.echo("in subcommand") result = runner.invoke(cli, ["sync"]) if result.exception: raise result.exception assert result.output == "invoke subcommand\nin subcommand\n" result = runner.invoke(cli) if result.exception: raise result.exception assert result.output == "no subcommand, use default\nin subcommand\n" def test_aliased_command_canonical_name(runner): class AliasedGroup(click.Group): def get_command(self, ctx, cmd_name): return push async def resolve_command(self, ctx, args): _, command, args = await super().resolve_command(ctx, args) return command.name, command, args cli = AliasedGroup() @cli.command() def push(): click.echo("push command") result = runner.invoke(cli, ["pu", "--help"]) if result.exception: raise result.exception assert result.output.startswith("Usage: root push [OPTIONS]") def test_group_add_command_name(runner): cli = click.Group("cli") cmd = click.Command("a", params=[click.Option(["-x"], required=True)]) cli.add_command(cmd, "b") # Check that the command is accessed through the registered name, # not the original name. result = runner.invoke(cli, ["b"], default_map={"b": {"x": 3}}) assert result.exit_code == 0 @pytest.mark.parametrize( ("invocation_order", "declaration_order", "expected_order"), [ # Non-eager options. ([], ["-a"], ["-a"]), (["-a"], ["-a"], ["-a"]), ([], ["-a", "-c"], ["-a", "-c"]), (["-a"], ["-a", "-c"], ["-a", "-c"]), (["-c"], ["-a", "-c"], ["-c", "-a"]), ([], ["-c", "-a"], ["-c", "-a"]), (["-a"], ["-c", "-a"], ["-a", "-c"]), (["-c"], ["-c", "-a"], ["-c", "-a"]), (["-a", "-c"], ["-a", "-c"], ["-a", "-c"]), (["-c", "-a"], ["-a", "-c"], ["-c", "-a"]), # Eager options. ([], ["-b"], ["-b"]), (["-b"], ["-b"], ["-b"]), ([], ["-b", "-d"], ["-b", "-d"]), (["-b"], ["-b", "-d"], ["-b", "-d"]), (["-d"], ["-b", "-d"], ["-d", "-b"]), ([], ["-d", "-b"], ["-d", "-b"]), (["-b"], ["-d", "-b"], ["-b", "-d"]), (["-d"], ["-d", "-b"], ["-d", "-b"]), (["-b", "-d"], ["-b", "-d"], ["-b", "-d"]), (["-d", "-b"], ["-b", "-d"], ["-d", "-b"]), # Mixed options. ([], ["-a", "-b", "-c", "-d"], ["-b", "-d", "-a", "-c"]), (["-a"], ["-a", "-b", "-c", "-d"], ["-b", "-d", "-a", "-c"]), (["-b"], ["-a", "-b", "-c", "-d"], ["-b", "-d", "-a", "-c"]), (["-c"], ["-a", "-b", "-c", "-d"], ["-b", "-d", "-c", "-a"]), (["-d"], ["-a", "-b", "-c", "-d"], ["-d", "-b", "-a", "-c"]), (["-a", "-b"], ["-a", "-b", "-c", "-d"], ["-b", "-d", "-a", "-c"]), (["-b", "-a"], ["-a", "-b", "-c", "-d"], ["-b", "-d", "-a", "-c"]), (["-d", "-c"], ["-a", "-b", "-c", "-d"], ["-d", "-b", "-c", "-a"]), (["-c", "-d"], ["-a", "-b", "-c", "-d"], ["-d", "-b", "-c", "-a"]), (["-a", "-b", "-c", "-d"], ["-a", "-b", "-c", "-d"], ["-b", "-d", "-a", "-c"]), (["-b", "-d", "-a", "-c"], ["-a", "-b", "-c", "-d"], ["-b", "-d", "-a", "-c"]), ([], ["-b", "-d", "-e", "-a", "-c"], ["-b", "-d", "-e", "-a", "-c"]), (["-a", "-d"], ["-b", "-d", "-e", "-a", "-c"], ["-d", "-b", "-e", "-a", "-c"]), (["-c", "-d"], ["-b", "-d", "-e", "-a", "-c"], ["-d", "-b", "-e", "-c", "-a"]), ], ) def test_iter_params_for_processing( invocation_order, declaration_order, expected_order ): parameters = { "-a": click.Option(["-a"]), "-b": click.Option(["-b"], is_eager=True), "-c": click.Option(["-c"]), "-d": click.Option(["-d"], is_eager=True), "-e": click.Option(["-e"], is_eager=True), } invocation_params = [parameters[opt_id] for opt_id in invocation_order] declaration_params = [parameters[opt_id] for opt_id in declaration_order] expected_params = [parameters[opt_id] for opt_id in expected_order] assert ( click.core.iter_params_for_processing(invocation_params, declaration_params) == expected_params ) def test_help_param_priority(runner): """Cover the edge-case in which the eagerness of help option was not respected, because it was internally generated multiple times. See: https://github.com/pallets/click/pull/2811 """ async def print_and_exit(ctx, param, value): if value: click.echo(f"Value of {param.name} is: {value}") await ctx.aexit() @click.command(context_settings={"help_option_names": ("--my-help",)}) @click.option("-a", is_flag=True, expose_value=False, callback=print_and_exit) @click.option( "-b", is_flag=True, expose_value=False, callback=print_and_exit, is_eager=True ) def cli(): pass # --my-help is properly called and stop execution. result = runner.invoke(cli, ["--my-help"]) assert "Value of a is: True" not in result.stdout assert "Value of b is: True" not in result.stdout assert "--my-help" in result.stdout assert result.exit_code == 0 # -a is properly called and stop execution. result = runner.invoke(cli, ["-a"]) assert "Value of a is: True" in result.stdout assert "Value of b is: True" not in result.stdout assert "--my-help" not in result.stdout assert result.exit_code == 0 # -a takes precedence over -b and stop execution. result = runner.invoke(cli, ["-a", "-b"]) assert "Value of a is: True" not in result.stdout assert "Value of b is: True" in result.stdout assert "--my-help" not in result.stdout assert result.exit_code == 0 # --my-help is eager by default so takes precedence over -a and stop # execution, whatever the order. for args in [["-a", "--my-help"], ["--my-help", "-a"]]: result = runner.invoke(cli, args) assert "Value of a is: True" not in result.stdout assert "Value of b is: True" not in result.stdout assert "--my-help" in result.stdout assert result.exit_code == 0 # Both -b and --my-help are eager so they're called in the order they're # invoked by the user. result = runner.invoke(cli, ["-b", "--my-help"]) assert "Value of a is: True" not in result.stdout assert "Value of b is: True" in result.stdout assert "--my-help" not in result.stdout assert result.exit_code == 0 # But there was a bug when --my-help is called before -b, because the # --my-help option created by click via help_option_names is internally # created twice and is not the same object, breaking the priority order # produced by iter_params_for_processing. result = runner.invoke(cli, ["--my-help", "-b"]) assert "Value of a is: True" not in result.stdout assert "Value of b is: True" not in result.stdout assert "--my-help" in result.stdout assert result.exit_code == 0 def test_unprocessed_options(runner): @click.command(context_settings=dict(ignore_unknown_options=True)) @click.argument("args", nargs=-1, type=click.UNPROCESSED) @click.option("--verbose", "-v", count=True) def cli(verbose, args): click.echo(f"Verbosity: {verbose}") click.echo(f"Args: {'|'.join(args)}") result = runner.invoke(cli, ["-foo", "-vvvvx", "--muhaha", "x", "y", "-x"]) if result.exception: raise result.exception assert result.output.splitlines() == [ "Verbosity: 4", "Args: -foo|-x|--muhaha|x|y|-x", ] @pytest.mark.parametrize("doc", ["CLI HELP", None]) @pytest.mark.parametrize("deprecated", [True, "USE OTHER COMMAND INSTEAD"]) def test_deprecated_in_help_messages(runner, doc, deprecated): @click.command(deprecated=deprecated, help=doc) def cli(): pass result = runner.invoke(cli, ["--help"]) assert "(DEPRECATED" in result.output if isinstance(deprecated, str): assert deprecated in result.output @pytest.mark.parametrize("deprecated", [True, "USE OTHER COMMAND INSTEAD"]) def test_deprecated_in_invocation(runner, deprecated): @click.command(deprecated=deprecated) def deprecated_cmd(): pass result = runner.invoke(deprecated_cmd) assert "DeprecationWarning:" in result.output if isinstance(deprecated, str): assert deprecated in result.output @pytest.mark.anyio async def test_command_parse_args_collects_option_prefixes(): @click.command() @click.option("+p", is_flag=True) @click.option("!e", is_flag=True) def test(p, e): pass ctx = click.Context(test) await test.parse_args(ctx, []) assert ctx._opt_prefixes == {"-", "--", "+", "!"} @pytest.mark.anyio async def test_group_parse_args_collects_base_option_prefixes(): @click.group() @click.option("~t", is_flag=True) def group(t): pass @group.command() @click.option("+p", is_flag=True) def command1(p): pass @group.command() @click.option("!e", is_flag=True) def command2(e): pass ctx = click.Context(group) await group.parse_args(ctx, ["command1", "+p"]) assert ctx._opt_prefixes == {"-", "--", "~"} def test_group_invoke_collects_used_option_prefixes(runner): opt_prefixes = set() @click.group() @click.option("~t", is_flag=True) def group(t): pass @group.command() @click.option("+p", is_flag=True) @click.pass_context def command1(ctx, p): nonlocal opt_prefixes opt_prefixes = ctx._opt_prefixes @group.command() @click.option("!e", is_flag=True) def command2(e): pass runner.invoke(group, ["command1"]) assert opt_prefixes == {"-", "--", "~", "+"} @pytest.mark.parametrize("exc", (EOFError, KeyboardInterrupt)) def test_abort_exceptions_with_disabled_standalone_mode(runner, exc): @click.command() def cli(): raise exc("catch me!") rv = runner.invoke(cli, standalone_mode=False) assert rv.exit_code == 1 assert isinstance(rv.exception.__cause__, exc) assert rv.exception.__cause__.args == ("catch me!",) asyncclick-8.3.0.5-async/tests/test_compat.py000066400000000000000000000004701507140761400211670ustar00rootroot00000000000000from asyncclick._compat import should_strip_ansi def test_is_jupyter_kernel_output(): class JupyterKernelFakeStream: pass # implementation detail, aka cheapskate test JupyterKernelFakeStream.__module__ = "ipykernel.faked" assert not should_strip_ansi(stream=JupyterKernelFakeStream()) asyncclick-8.3.0.5-async/tests/test_context.py000066400000000000000000000475371507140761400214070ustar00rootroot00000000000000import logging from contextlib import AbstractContextManager from contextlib import asynccontextmanager from contextlib import contextmanager from types import TracebackType import pytest import asyncclick as click from asyncclick import Context from asyncclick import Option from asyncclick import Parameter from asyncclick.core import ParameterSource from asyncclick.decorators import help_option from asyncclick.decorators import pass_meta_key def test_ensure_context_objects(runner): class Foo: def __init__(self): self.title = "default" pass_foo = click.make_pass_decorator(Foo, ensure=True) @click.group() @pass_foo def cli(foo): pass @cli.command() @pass_foo def test(foo): click.echo(foo.title) result = runner.invoke(cli, ["test"]) assert not result.exception assert result.output == "default\n" def test_get_context_objects(runner): class Foo: def __init__(self): self.title = "default" pass_foo = click.make_pass_decorator(Foo, ensure=True) @click.group() @click.pass_context def cli(ctx): ctx.obj = Foo() ctx.obj.title = "test" @cli.command() @pass_foo def test(foo): click.echo(foo.title) result = runner.invoke(cli, ["test"]) assert not result.exception assert result.output == "test\n" def test_get_context_objects_no_ensuring(runner): class Foo: def __init__(self): self.title = "default" pass_foo = click.make_pass_decorator(Foo) @click.group() @click.pass_context def cli(ctx): ctx.obj = Foo() ctx.obj.title = "test" @cli.command() @pass_foo def test(foo): click.echo(foo.title) result = runner.invoke(cli, ["test"]) assert not result.exception assert result.output == "test\n" def test_get_context_objects_missing(runner): class Foo: pass pass_foo = click.make_pass_decorator(Foo) @click.group() @click.pass_context def cli(ctx): pass @cli.command() @pass_foo def test(foo): click.echo(foo.title) result = runner.invoke(cli, ["test"]) assert result.exception is not None assert isinstance(result.exception, RuntimeError) assert ( "Managed to invoke callback without a context object of type" " 'Foo' existing" in str(result.exception) ) def test_multi_enter(runner): called = [] @click.command() @click.pass_context async def cli(ctx): def callback(): called.append(True) ctx.call_on_close(callback) async with ctx: pass assert not called result = runner.invoke(cli, []) if result.exception: raise result.exception assert called == [True] def test_global_context_object(runner): @click.command() @click.pass_context def cli(ctx): assert click.get_current_context() is ctx ctx.obj = "FOOBAR" assert click.get_current_context().obj == "FOOBAR" assert click.get_current_context(silent=True) is None runner.invoke(cli, [], catch_exceptions=False) assert click.get_current_context(silent=True) is None def test_context_meta(runner): LANG_KEY = f"{__name__}.lang" def set_language(value): click.get_current_context().meta[LANG_KEY] = value def get_language(): return click.get_current_context().meta.get(LANG_KEY, "en_US") @click.command() @click.pass_context def cli(ctx): assert get_language() == "en_US" set_language("de_DE") assert get_language() == "de_DE" runner.invoke(cli, [], catch_exceptions=False) def test_make_pass_meta_decorator(runner): @click.group() @click.pass_context def cli(ctx): ctx.meta["value"] = "good" @cli.command() @pass_meta_key("value") def show(value): return value result = runner.invoke(cli, ["show"], standalone_mode=False) assert result.return_value == "good" def test_make_pass_meta_decorator_doc(): pass_value = pass_meta_key("value") assert "the 'value' key from :attr:`click.Context.meta`" in pass_value.__doc__ pass_value = pass_meta_key("value", doc_description="the test value") assert "passes the test value" in pass_value.__doc__ @pytest.mark.anyio async def test_context_pushing(): rv = [] @click.command() def cli(): pass ctx = click.Context(cli) @ctx.call_on_close def test_callback(): rv.append(42) async with ctx.scope(cleanup=False): # Internal assert ctx._depth == 2 assert rv == [] async with ctx.scope(): # Internal assert ctx._depth == 1 assert rv == [42] @pytest.mark.anyio async def test_async_context_mgr(): @asynccontextmanager async def manager(): val = [1] yield val val[0] = 0 @click.command() def cli(): pass ctx = click.Context(cli) async with ctx.scope(): rv = await ctx.with_async_resource(manager()) assert rv[0] == 1, rv # Internal assert ctx._depth == 1 assert rv == [0], rv @pytest.mark.anyio async def test_context_mgr(): @contextmanager def manager(): val = [1] yield val val[0] = 0 @click.command() def cli(): pass ctx = click.Context(cli) async with ctx.scope(): rv = ctx.with_resource(manager()) assert rv[0] == 1, rv # Internal assert ctx._depth == 1 assert rv == [0], rv def test_pass_obj(runner): @click.group() @click.pass_context def cli(ctx): ctx.obj = "test" @cli.command() @click.pass_obj def test(obj): click.echo(obj) result = runner.invoke(cli, ["test"]) assert not result.exception assert result.output == "test\n" def test_close_before_pop(runner): called = [] @click.command() @click.pass_context def cli(ctx): ctx.obj = "test" @ctx.call_on_close def foo(): assert click.get_current_context().obj == "test" called.append(True) click.echo("aha!") result = runner.invoke(cli, []) assert not result.exception assert result.output == "aha!\n" assert called == [True] @pytest.mark.anyio async def test_close_before_exit(runner): called = [] @click.command() @click.pass_context async def cli(ctx): ctx.obj = "test" @ctx.call_on_close def foo(): assert click.get_current_context().obj == "test" called.append(True) await ctx.aexit() click.echo("aha!") result = runner.invoke(cli, []) assert not result.exception assert not result.output assert called == [True] @pytest.mark.anyio async def test_aclose_before_exit(runner): called = [] @click.command() @click.pass_context async def cli(ctx): ctx.obj = "test" @ctx.call_on_close def foo(): assert click.get_current_context().obj == "test" called.append(True) await ctx.aexit() click.echo("aha!") result = runner.invoke(cli, []) assert not result.exception assert not result.output assert called == [True] @pytest.mark.parametrize( ("cli_args", "expect"), [ pytest.param( ("--option-with-callback", "--force-exit"), ["ExitingOption", "NonExitingOption"], id="natural_order", ), pytest.param( ("--force-exit", "--option-with-callback"), ["ExitingOption"], id="eagerness_precedence", ), ], ) def test_multiple_eager_callbacks(runner, cli_args, expect): """Checks all callbacks are called on exit, even the nasty ones hidden within callbacks. Also checks the order in which they're called. """ # Keeps track of callback calls. called = [] class NonExitingOption(Option): def reset_state(self): called.append(self.__class__.__name__) def set_state(self, ctx: Context, param: Parameter, value: str) -> str: ctx.call_on_close(self.reset_state) return value def __init__(self, *args, **kwargs) -> None: kwargs.setdefault("expose_value", False) kwargs.setdefault("callback", self.set_state) super().__init__(*args, **kwargs) class ExitingOption(NonExitingOption): async def set_state(self, ctx: Context, param: Parameter, value: str) -> str: value = super().set_state(ctx, param, value) await ctx.aexit() return value @click.command() @click.option("--option-with-callback", is_eager=True, cls=NonExitingOption) @click.option("--force-exit", is_eager=True, cls=ExitingOption) def cli(): click.echo("This will never be printed as we forced exit via --force-exit") result = runner.invoke(cli, cli_args) assert not result.exception assert not result.output assert called == expect def test_no_state_leaks(runner): """Demonstrate state leaks with a specific case of the generic test above. Use a logger as a real-world example of a common fixture which, due to its global nature, can leak state if not clean-up properly in a callback. """ # Keeps track of callback calls. called = [] class DebugLoggerOption(Option): """A custom option to set the name of the debug logger.""" logger_name: str """The ID of the logger to use.""" def reset_loggers(self): """Forces logger managed by the option to be reset to the default level.""" logger = logging.getLogger(self.logger_name) logger.setLevel(logging.NOTSET) # Logger has been properly reset to its initial state. assert logger.level == logging.NOTSET assert logger.getEffectiveLevel() == logging.WARNING called.append(True) def set_level(self, ctx: Context, param: Parameter, value: str) -> None: """Set the logger to DEBUG level.""" # Keep the logger name around so we can reset it later when winding down # the option. self.logger_name = value # Get the global logger object. logger = logging.getLogger(self.logger_name) # Check pre-conditions: new logger is not set, but inherits its level from # default logger. That's the exact same state we are expecting our # logger to be in after being messed with by the CLI. assert logger.level == logging.NOTSET assert logger.getEffectiveLevel() == logging.WARNING logger.setLevel(logging.DEBUG) ctx.call_on_close(self.reset_loggers) return value def __init__(self, *args, **kwargs) -> None: kwargs.setdefault("callback", self.set_level) super().__init__(*args, **kwargs) @click.command() @click.option("--debug-logger-name", is_eager=True, cls=DebugLoggerOption) @help_option() @click.pass_context async def messing_with_logger(ctx, debug_logger_name): # Introspect context to make sure logger name are aligned. assert debug_logger_name == ctx.command.params[0].logger_name logger = logging.getLogger(debug_logger_name) # Logger's level has been properly set to DEBUG by DebugLoggerOption. assert logger.level == logging.DEBUG assert logger.getEffectiveLevel() == logging.DEBUG logger.debug("Blah blah blah") await ctx.aexit() click.echo("This will never be printed as we exited early") # Call the CLI to mess with the custom logger. result = runner.invoke( messing_with_logger, ["--debug-logger-name", "my_logger", "--help"] ) assert called == [True] # Check the custom logger has been reverted to it initial state by the option # callback after being messed with by the CLI. logger = logging.getLogger("my_logger") assert logger.level == logging.NOTSET assert logger.getEffectiveLevel() == logging.WARNING assert not result.exception assert result.output.startswith("Usage: messing-with-logger [OPTIONS]") @pytest.mark.anyio async def test_with_resource(): @contextmanager def manager(): val = [1] yield val val[0] = 0 ctx = click.Context(click.Command("test")) async with ctx.scope(): rv = ctx.with_resource(manager()) assert rv[0] == 1 assert rv == [0] @pytest.mark.anyio async def test_with_async_resource(): @asynccontextmanager async def manager(): val = [1] yield val val[0] = 0 ctx = click.Context(click.Command("test")) async with ctx.scope(): rv = await ctx.with_async_resource(manager()) assert rv[0] == 1 assert rv == [0] @pytest.mark.anyio async def test_with_resource_exception() -> None: class TestContext(AbstractContextManager[list[int]]): _handle_exception: bool _base_val: int val: list[int] def __init__(self, base_val: int = 1, *, handle_exception: bool = True) -> None: self._handle_exception = handle_exception self._base_val = base_val def __enter__(self) -> list[int]: self.val = [self._base_val] return self.val def __exit__( self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, ) -> bool | None: if not exc_type: self.val[0] = self._base_val - 1 return None self.val[0] = self._base_val + 1 return self._handle_exception class TestException(Exception): pass ctx = click.Context(click.Command("test")) base_val = 1 async with ctx.scope(): rv = ctx.with_resource(TestContext(base_val=base_val)) assert rv[0] == base_val assert rv == [base_val - 1] async with ctx.scope(): rv = ctx.with_resource(TestContext(base_val=base_val)) raise TestException() assert rv == [base_val + 1] with pytest.raises(TestException): async with ctx.scope(): rv = ctx.with_resource( TestContext(base_val=base_val, handle_exception=False) ) raise TestException() @pytest.mark.anyio async def test_with_resource_nested_exception() -> None: class TestContext(AbstractContextManager[list[int]]): _handle_exception: bool _base_val: int val: list[int] def __init__(self, base_val: int = 1, *, handle_exception: bool = True) -> None: self._handle_exception = handle_exception self._base_val = base_val def __enter__(self) -> list[int]: self.val = [self._base_val] return self.val def __exit__( self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, ) -> bool | None: if not exc_type: self.val[0] = self._base_val - 1 return None self.val[0] = self._base_val + 1 return self._handle_exception class TestException(Exception): pass ctx = click.Context(click.Command("test")) base_val = 1 base_val_nested = 11 async with ctx.scope(): rv = ctx.with_resource(TestContext(base_val=base_val)) rv_nested = ctx.with_resource(TestContext(base_val=base_val_nested)) assert rv[0] == base_val assert rv_nested[0] == base_val_nested assert rv == [base_val - 1] assert rv_nested == [base_val_nested - 1] async with ctx.scope(): rv = ctx.with_resource(TestContext(base_val=base_val)) rv_nested = ctx.with_resource(TestContext(base_val=base_val_nested)) raise TestException() # If one of the context "eats" the exceptions they will not be forwarded to other # parts. This is due to how ExitStack unwinding works assert rv_nested == [base_val_nested + 1] assert rv == [base_val - 1] async with ctx.scope(): rv = ctx.with_resource(TestContext(base_val=base_val)) rv_nested = ctx.with_resource( TestContext(base_val=base_val_nested, handle_exception=False) ) raise TestException() assert rv_nested == [base_val_nested + 1] assert rv == [base_val + 1] with pytest.raises(TestException): rv = ctx.with_resource(TestContext(base_val=base_val, handle_exception=False)) rv_nested = ctx.with_resource( TestContext(base_val=base_val_nested, handle_exception=False) ) raise TestException() def test_make_pass_decorator_args(runner): """ Test to check that make_pass_decorator doesn't consume arguments based on invocation order. """ class Foo: title = "foocmd" pass_foo = click.make_pass_decorator(Foo) @click.group() @click.pass_context def cli(ctx): ctx.obj = Foo() @cli.command() @click.pass_context @pass_foo def test1(foo, ctx): click.echo(foo.title) @cli.command() @pass_foo @click.pass_context def test2(ctx, foo): click.echo(foo.title) result = runner.invoke(cli, ["test1"]) assert not result.exception assert result.output == "foocmd\n" result = runner.invoke(cli, ["test2"]) assert not result.exception assert result.output == "foocmd\n" def test_propagate_show_default_setting(runner): """A context's ``show_default`` setting defaults to the value from the parent context. """ group = click.Group( commands={ "sub": click.Command("sub", params=[click.Option(["-a"], default="a")]), }, context_settings={"show_default": True}, ) result = runner.invoke(group, ["sub", "--help"]) assert "[default: a]" in result.output @pytest.mark.anyio async def test_exit_not_standalone(): @click.command() @click.pass_context async def cli(ctx): await ctx.aexit(1) assert await cli.main([], "test_exit_not_standalone", standalone_mode=False) == 1 @click.command() @click.pass_context async def cli(ctx): await ctx.aexit(0) assert await cli.main([], "test_exit_not_standalone", standalone_mode=False) == 0 @pytest.mark.parametrize( ("option_args", "invoke_args", "expect"), [ pytest.param({}, {}, ParameterSource.DEFAULT, id="default"), pytest.param( {}, {"default_map": {"option": 1}}, ParameterSource.DEFAULT_MAP, id="default_map", ), pytest.param( {}, {"args": ["-o", "1"]}, ParameterSource.COMMANDLINE, id="commandline short", ), pytest.param( {}, {"args": ["--option", "1"]}, ParameterSource.COMMANDLINE, id="commandline long", ), pytest.param( {}, {"auto_envvar_prefix": "TEST", "env": {"TEST_OPTION": "1"}}, ParameterSource.ENVIRONMENT, id="environment auto", ), pytest.param( {"envvar": "NAME"}, {"env": {"NAME": "1"}}, ParameterSource.ENVIRONMENT, id="environment manual", ), ], ) def test_parameter_source(runner, option_args, invoke_args, expect): @click.command() @click.pass_context @click.option("-o", "--option", default=1, **option_args) def cli(ctx, option): return ctx.get_parameter_source("option") rv = runner.invoke(cli, standalone_mode=False, **invoke_args) assert rv.return_value == expect def test_propagate_opt_prefixes(): parent = click.Context(click.Command("test")) parent._opt_prefixes = {"-", "--", "!"} ctx = click.Context(click.Command("test2"), parent=parent) assert ctx._opt_prefixes == {"-", "--", "!"} asyncclick-8.3.0.5-async/tests/test_custom_classes.py000066400000000000000000000060261507140761400227360ustar00rootroot00000000000000import pytest import asyncclick as click @pytest.mark.anyio async def test_command_context_class(): """A command with a custom ``context_class`` should produce a context using that type. """ class CustomContext(click.Context): pass class CustomCommand(click.Command): context_class = CustomContext command = CustomCommand("test") context = await command.make_context("test", []) assert isinstance(context, CustomContext) def test_context_invoke_type(runner): """A command invoked from a custom context should have a new context with the same type. """ class CustomContext(click.Context): pass class CustomCommand(click.Command): context_class = CustomContext @click.command() @click.argument("first_id", type=int) @click.pass_context def second(ctx, first_id): assert isinstance(ctx, CustomContext) assert id(ctx) != first_id @click.command(cls=CustomCommand) @click.pass_context async def first(ctx): assert isinstance(ctx, CustomContext) await ctx.invoke(second, first_id=id(ctx)) assert not runner.invoke(first).exception def test_context_formatter_class(): """A context with a custom ``formatter_class`` should format help using that type. """ class CustomFormatter(click.HelpFormatter): def write_heading(self, heading): heading = click.style(heading, fg="yellow") return super().write_heading(heading) class CustomContext(click.Context): formatter_class = CustomFormatter context = CustomContext( click.Command("test", params=[click.Option(["--value"])]), color=True ) assert "\x1b[33mOptions\x1b[0m:" in context.get_help() def test_group_command_class(runner): """A group with a custom ``command_class`` should create subcommands of that type by default. """ class CustomCommand(click.Command): pass class CustomGroup(click.Group): command_class = CustomCommand group = CustomGroup() subcommand = group.command()(lambda: None) assert type(subcommand) is CustomCommand subcommand = group.command(cls=click.Command)(lambda: None) assert type(subcommand) is click.Command def test_group_group_class(runner): """A group with a custom ``group_class`` should create subgroups of that type by default. """ class CustomSubGroup(click.Group): pass class CustomGroup(click.Group): group_class = CustomSubGroup group = CustomGroup() subgroup = group.group()(lambda: None) assert type(subgroup) is CustomSubGroup subgroup = group.command(cls=click.Group)(lambda: None) assert type(subgroup) is click.Group def test_group_group_class_self(runner): """A group with ``group_class = type`` should create subgroups of the same type as itself. """ class CustomGroup(click.Group): group_class = type group = CustomGroup() subgroup = group.group()(lambda: None) assert type(subgroup) is CustomGroup asyncclick-8.3.0.5-async/tests/test_defaults.py000066400000000000000000000047611507140761400215220ustar00rootroot00000000000000import asyncclick as click def test_basic_defaults(runner): @click.command() @click.option("--foo", default=42, type=click.FLOAT) def cli(foo): assert isinstance(foo, float) click.echo(f"FOO:[{foo}]") result = runner.invoke(cli, []) assert not result.exception assert "FOO:[42.0]" in result.output def test_multiple_defaults(runner): @click.command() @click.option("--foo", default=[23, 42], type=click.FLOAT, multiple=True) def cli(foo): for item in foo: assert isinstance(item, float) click.echo(item) result = runner.invoke(cli, []) assert not result.exception assert result.output.splitlines() == ["23.0", "42.0"] def test_nargs_plus_multiple(runner): @click.command() @click.option( "--arg", default=((1, 2), (3, 4)), nargs=2, multiple=True, type=click.INT ) def cli(arg): for a, b in arg: click.echo(f"<{a:d}|{b:d}>") result = runner.invoke(cli, []) assert not result.exception assert result.output.splitlines() == ["<1|2>", "<3|4>"] def test_multiple_flag_default(runner): """Default default for flags when multiple=True should be empty tuple.""" @click.command # flag due to secondary token @click.option("-y/-n", multiple=True) # flag due to is_flag @click.option("-f", is_flag=True, multiple=True) # flag due to flag_value @click.option("-v", "v", flag_value=1, multiple=True) @click.option("-q", "v", flag_value=-1, multiple=True) def cli(y, f, v): return y, f, v result = runner.invoke(cli, standalone_mode=False) assert result.return_value == ((), (), ()) result = runner.invoke(cli, ["-y", "-n", "-f", "-v", "-q"], standalone_mode=False) assert result.return_value == ((True, False), (True,), (1, -1)) def test_flag_default_map(runner): """test flag with default map""" @click.group() def cli(): pass @cli.command() @click.option("--name/--no-name", is_flag=True, show_default=True, help="name flag") def foo(name): click.echo(name) result = runner.invoke(cli, ["foo"]) assert "False" in result.output result = runner.invoke(cli, ["foo", "--help"]) assert "default: no-name" in result.output result = runner.invoke(cli, ["foo"], default_map={"foo": {"name": True}}) assert "True" in result.output result = runner.invoke(cli, ["foo", "--help"], default_map={"foo": {"name": True}}) assert "default: name" in result.output asyncclick-8.3.0.5-async/tests/test_formatting.py000066400000000000000000000223701507140761400220610ustar00rootroot00000000000000import asyncclick as click def test_basic_functionality(runner): @click.command() def cli(): """First paragraph. This is a very long second paragraph and not correctly wrapped but it will be rewrapped. \b This is a paragraph without rewrapping. \b 1 2 3 And this is a paragraph that will be rewrapped again. """ result = runner.invoke(cli, ["--help"], terminal_width=60) assert not result.exception assert result.output.splitlines() == [ "Usage: cli [OPTIONS]", "", " First paragraph.", "", " This is a very long second paragraph and not correctly", " wrapped but it will be rewrapped.", "", " This is", " a paragraph", " without rewrapping.", "", " 1", " 2", " 3", "", " And this is a paragraph that will be rewrapped again.", "", "Options:", " --help Show this message and exit.", ] def test_wrapping_long_options_strings(runner): @click.group() def cli(): """Top level command""" @cli.group() def a_very_long(): """Second level""" @a_very_long.command() @click.argument("first") @click.argument("second") @click.argument("third") @click.argument("fourth") @click.argument("fifth") @click.argument("sixth") def command(): """A command.""" # 54 is chosen as a length where the second line is one character # longer than the maximum length. result = runner.invoke(cli, ["a-very-long", "command", "--help"], terminal_width=54) assert not result.exception assert result.output.splitlines() == [ "Usage: cli a-very-long command [OPTIONS] FIRST SECOND", " THIRD FOURTH FIFTH", " SIXTH", "", " A command.", "", "Options:", " --help Show this message and exit.", ] def test_wrapping_long_command_name(runner): @click.group() def cli(): """Top level command""" @cli.group() def a_very_very_very_long(): """Second level""" @a_very_very_very_long.command() @click.argument("first") @click.argument("second") @click.argument("third") @click.argument("fourth") @click.argument("fifth") @click.argument("sixth") def command(): """A command.""" result = runner.invoke( cli, ["a-very-very-very-long", "command", "--help"], terminal_width=54 ) assert not result.exception assert result.output.splitlines() == [ "Usage: cli a-very-very-very-long command ", " [OPTIONS] FIRST SECOND THIRD FOURTH FIFTH", " SIXTH", "", " A command.", "", "Options:", " --help Show this message and exit.", ] def test_formatting_empty_help_lines(runner): @click.command() def cli(): # fmt: off """Top level command """ # fmt: on result = runner.invoke(cli, ["--help"]) assert not result.exception assert result.output.splitlines() == [ "Usage: cli [OPTIONS]", "", " Top level command", "", "", "", "Options:", " --help Show this message and exit.", ] def test_formatting_usage_error(runner): @click.command() @click.argument("arg") def cmd(arg): click.echo(f"arg:{arg}") result = runner.invoke(cmd, []) assert result.exit_code == 2 assert result.output.splitlines() == [ "Usage: cmd [OPTIONS] ARG", "Try 'cmd --help' for help.", "", "Error: Missing argument 'ARG'.", ] def test_formatting_usage_error_metavar_missing_arg(runner): """ :author: @r-m-n Including attribution to #612 """ @click.command() @click.argument("arg", metavar="metavar") def cmd(arg): pass result = runner.invoke(cmd, []) assert result.exit_code == 2 assert result.output.splitlines() == [ "Usage: cmd [OPTIONS] metavar", "Try 'cmd --help' for help.", "", "Error: Missing argument 'metavar'.", ] def test_formatting_usage_error_metavar_bad_arg(runner): @click.command() @click.argument("arg", type=click.INT, metavar="metavar") def cmd(arg): pass result = runner.invoke(cmd, ["3.14"]) assert result.exit_code == 2 assert result.output.splitlines() == [ "Usage: cmd [OPTIONS] metavar", "Try 'cmd --help' for help.", "", "Error: Invalid value for 'metavar': '3.14' is not a valid integer.", ] def test_formatting_usage_error_nested(runner): @click.group() def cmd(): pass @cmd.command() @click.argument("bar") def foo(bar): click.echo(f"foo:{bar}") result = runner.invoke(cmd, ["foo"]) assert result.exit_code == 2 assert result.output.splitlines() == [ "Usage: cmd foo [OPTIONS] BAR", "Try 'cmd foo --help' for help.", "", "Error: Missing argument 'BAR'.", ] def test_formatting_usage_error_no_help(runner): @click.command(add_help_option=False) @click.argument("arg") def cmd(arg): click.echo(f"arg:{arg}") result = runner.invoke(cmd, []) assert result.exit_code == 2 assert result.output.splitlines() == [ "Usage: cmd [OPTIONS] ARG", "", "Error: Missing argument 'ARG'.", ] def test_formatting_usage_custom_help(runner): @click.command(context_settings=dict(help_option_names=["--man"])) @click.argument("arg") def cmd(arg): click.echo(f"arg:{arg}") result = runner.invoke(cmd, []) assert result.exit_code == 2 assert result.output.splitlines() == [ "Usage: cmd [OPTIONS] ARG", "Try 'cmd --man' for help.", "", "Error: Missing argument 'ARG'.", ] def test_formatting_custom_type_metavar(runner): class MyType(click.ParamType): def get_metavar(self, param: click.Parameter, ctx: click.Context): return "MY_TYPE" @click.command("foo") @click.help_option() @click.argument("param", type=MyType()) def cmd(param): pass result = runner.invoke(cmd, "--help") assert not result.exception assert result.output.splitlines() == [ "Usage: foo [OPTIONS] MY_TYPE", "", "Options:", " --help Show this message and exit.", ] def test_truncating_docstring(runner): @click.command() @click.pass_context def cli(ctx): """First paragraph. This is a very long second paragraph and not correctly wrapped but it will be rewrapped. \f :param click.core.Context ctx: Click context. """ result = runner.invoke(cli, ["--help"], terminal_width=60) assert not result.exception assert result.output.splitlines() == [ "Usage: cli [OPTIONS]", "", " First paragraph.", "", " This is a very long second paragraph and not correctly", " wrapped but it will be rewrapped.", "", "Options:", " --help Show this message and exit.", ] def test_truncating_docstring_no_help(runner): @click.command() @click.pass_context def cli(ctx): """ \f This text should be truncated. """ result = runner.invoke(cli, ["--help"], terminal_width=60) assert not result.exception assert result.output.splitlines() == [ "Usage: cli [OPTIONS]", "", "Options:", " --help Show this message and exit.", ] def test_removing_multiline_marker(runner): @click.group() def cli(): pass @cli.command() def cmd1(): """\b This is command with a multiline help text which should not be rewrapped. The output of the short help text should not contain the multiline marker. """ pass result = runner.invoke(cli, ["--help"]) assert "\b" not in result.output def test_global_show_default(runner): @click.command(context_settings=dict(show_default=True)) @click.option("-f", "in_file", default="out.txt", help="Output file name") def cli(): pass result = runner.invoke(cli, ["--help"]) # the default to "--help" is not shown because it is False assert result.output.splitlines() == [ "Usage: cli [OPTIONS]", "", "Options:", " -f TEXT Output file name [default: out.txt]", " --help Show this message and exit.", ] def test_formatting_with_options_metavar_empty(runner): cli = click.Command("cli", options_metavar="", params=[click.Argument(["var"])]) result = runner.invoke(cli, ["--help"]) assert "Usage: cli VAR\n" in result.output def test_help_formatter_write_text(): text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit" formatter = click.HelpFormatter(width=len(" Lorem ipsum dolor sit amet,")) formatter.current_indent = 2 formatter.write_text(text) actual = formatter.getvalue() expected = " Lorem ipsum dolor sit amet,\n consectetur adipiscing elit\n" assert actual == expected asyncclick-8.3.0.5-async/tests/test_imports.py000066400000000000000000000027561507140761400214120ustar00rootroot00000000000000import json import subprocess import sys from asyncclick._compat import WIN IMPORT_TEST = b"""\ import builtins found_imports = set() real_import = builtins.__import__ import sys def tracking_import(module, locals=None, globals=None, fromlist=None, level=0): rv = real_import(module, locals, globals, fromlist, level) if globals and '__name__' in globals and \\ globals['__name__'].startswith('asyncclick') and level == 0: found_imports.add(module) return rv builtins.__import__ = tracking_import import asyncclick rv = list(found_imports) import json asyncclick.echo(json.dumps(rv)) """ ALLOWED_IMPORTS = { "__future__", "anyio", "codecs", "collections", "collections.abc", "configparser", "contextlib", "datetime", "enum", "errno", "fcntl", "functools", "gettext", "inspect", "io", "itertools", "os", "re", "stat", "struct", "sys", "threading", "types", "typing", "weakref", } if WIN: ALLOWED_IMPORTS.update(["ctypes", "ctypes.wintypes", "msvcrt", "time"]) def test_light_imports(): c = subprocess.Popen( [sys.executable, "-"], stdin=subprocess.PIPE, stdout=subprocess.PIPE ) rv = c.communicate(IMPORT_TEST)[0] rv = rv.decode("utf-8") imported = json.loads(rv) for module in imported: if module == "asyncclick" or module.startswith("asyncclick."): continue assert module in ALLOWED_IMPORTS asyncclick-8.3.0.5-async/tests/test_info_dict.py000066400000000000000000000176311507140761400216510ustar00rootroot00000000000000import pytest import asyncclick as click import asyncclick.types # Common (obj, expect) pairs used to construct multiple tests. STRING_PARAM_TYPE = (click.STRING, {"param_type": "String", "name": "text"}) INT_PARAM_TYPE = (click.INT, {"param_type": "Int", "name": "integer"}) BOOL_PARAM_TYPE = (click.BOOL, {"param_type": "Bool", "name": "boolean"}) HELP_OPTION = ( None, { "name": "help", "param_type_name": "option", "opts": ["--help"], "secondary_opts": [], "type": BOOL_PARAM_TYPE[1], "required": False, "nargs": 1, "multiple": False, "default": False, "envvar": None, "help": "Show this message and exit.", "prompt": None, "is_flag": True, "flag_value": True, "count": False, "hidden": False, }, ) NAME_ARGUMENT = ( click.Argument(["name"]), { "name": "name", "param_type_name": "argument", "opts": ["name"], "secondary_opts": [], "type": STRING_PARAM_TYPE[1], "required": True, "nargs": 1, "multiple": False, "default": None, "envvar": None, }, ) NUMBER_OPTION = ( click.Option(["-c", "--count", "number"], default=1), { "name": "number", "param_type_name": "option", "opts": ["-c", "--count"], "secondary_opts": [], "type": INT_PARAM_TYPE[1], "required": False, "nargs": 1, "multiple": False, "default": 1, "envvar": None, "help": None, "prompt": None, "is_flag": False, "flag_value": None, "count": False, "hidden": False, }, ) HELLO_COMMAND = ( click.Command("hello", params=[NUMBER_OPTION[0]]), { "name": "hello", "params": [NUMBER_OPTION[1], HELP_OPTION[1]], "help": None, "epilog": None, "short_help": None, "hidden": False, "deprecated": False, }, ) HELLO_GROUP = ( click.Group("cli", [HELLO_COMMAND[0]]), { "name": "cli", "params": [HELP_OPTION[1]], "help": None, "epilog": None, "short_help": None, "hidden": False, "deprecated": False, "commands": {"hello": HELLO_COMMAND[1]}, "chain": False, }, ) @pytest.mark.parametrize( ("obj", "expect"), [ pytest.param( click.types.FuncParamType(range), {"param_type": "Func", "name": "range", "func": range}, id="Func ParamType", ), pytest.param( click.UNPROCESSED, {"param_type": "Unprocessed", "name": "text"}, id="UNPROCESSED ParamType", ), pytest.param(*STRING_PARAM_TYPE, id="STRING ParamType"), pytest.param( click.Choice(("a", "b")), { "param_type": "Choice", "name": "choice", "choices": ("a", "b"), "case_sensitive": True, }, id="Choice ParamType", ), pytest.param( click.DateTime(["%Y-%m-%d"]), {"param_type": "DateTime", "name": "datetime", "formats": ["%Y-%m-%d"]}, id="DateTime ParamType", ), pytest.param(*INT_PARAM_TYPE, id="INT ParamType"), pytest.param( click.IntRange(0, 10, clamp=True), { "param_type": "IntRange", "name": "integer range", "min": 0, "max": 10, "min_open": False, "max_open": False, "clamp": True, }, id="IntRange ParamType", ), pytest.param( click.FLOAT, {"param_type": "Float", "name": "float"}, id="FLOAT ParamType" ), pytest.param( click.FloatRange(-0.5, 0.5), { "param_type": "FloatRange", "name": "float range", "min": -0.5, "max": 0.5, "min_open": False, "max_open": False, "clamp": False, }, id="FloatRange ParamType", ), pytest.param(*BOOL_PARAM_TYPE, id="Bool ParamType"), pytest.param( click.UUID, {"param_type": "UUID", "name": "uuid"}, id="UUID ParamType" ), pytest.param( click.File(), {"param_type": "File", "name": "filename", "mode": "r", "encoding": None}, id="File ParamType", ), pytest.param( click.Path(), { "param_type": "Path", "name": "path", "exists": False, "file_okay": True, "dir_okay": True, "writable": False, "readable": True, "allow_dash": False, }, id="Path ParamType", ), pytest.param( click.Tuple((click.STRING, click.INT)), { "param_type": "Tuple", "name": "", "types": [STRING_PARAM_TYPE[1], INT_PARAM_TYPE[1]], }, id="Tuple ParamType", ), pytest.param(*NUMBER_OPTION, id="Option"), pytest.param( click.Option(["--cache/--no-cache", "-c/-u"]), { "name": "cache", "param_type_name": "option", "opts": ["--cache", "-c"], "secondary_opts": ["--no-cache", "-u"], "type": BOOL_PARAM_TYPE[1], "required": False, "nargs": 1, "multiple": False, "default": False, "envvar": None, "help": None, "prompt": None, "is_flag": True, "flag_value": True, "count": False, "hidden": False, }, id="Flag Option", ), pytest.param(*NAME_ARGUMENT, id="Argument"), ], ) @pytest.mark.anyio async def test_parameter(obj, expect): out = await obj.to_info_dict() assert out == expect @pytest.mark.parametrize( ("obj", "expect"), [ pytest.param(*HELLO_COMMAND, id="Command"), pytest.param(*HELLO_GROUP, id="Group"), pytest.param( click.Group( "base", [click.Command("test", params=[NAME_ARGUMENT[0]]), HELLO_GROUP[0]], ), { "name": "base", "params": [HELP_OPTION[1]], "help": None, "epilog": None, "short_help": None, "hidden": False, "deprecated": False, "commands": { "cli": HELLO_GROUP[1], "test": { "name": "test", "params": [NAME_ARGUMENT[1], HELP_OPTION[1]], "help": None, "epilog": None, "short_help": None, "hidden": False, "deprecated": False, }, }, "chain": False, }, id="Nested Group", ), ], ) @pytest.mark.anyio async def test_command(obj, expect): ctx = click.Context(obj) out = await obj.to_info_dict(ctx) assert out == expect @pytest.mark.anyio async def test_context(): ctx = click.Context(HELLO_COMMAND[0]) out = await ctx.to_info_dict() assert out == { "command": HELLO_COMMAND[1], "info_name": None, "allow_extra_args": False, "allow_interspersed_args": True, "ignore_unknown_options": False, "auto_envvar_prefix": None, } @pytest.mark.anyio async def test_paramtype_no_name(): class TestType(click.ParamType): pass assert (await TestType().to_info_dict())["name"] == "TestType" asyncclick-8.3.0.5-async/tests/test_normalization.py000066400000000000000000000034201507140761400225700ustar00rootroot00000000000000import asyncclick as click CONTEXT_SETTINGS = dict(token_normalize_func=lambda x: x.lower()) def test_option_normalization(runner): @click.command(context_settings=CONTEXT_SETTINGS) @click.option("--foo") @click.option("-x") def cli(foo, x): click.echo(foo) click.echo(x) result = runner.invoke(cli, ["--FOO", "42", "-X", 23]) assert result.output == "42\n23\n" def test_choice_normalization(runner): @click.command(context_settings=CONTEXT_SETTINGS) @click.option( "--method", type=click.Choice( ["SCREAMING_SNAKE_CASE", "snake_case", "PascalCase", "kebab-case"], case_sensitive=False, ), ) def cli(method): click.echo(method) result = runner.invoke(cli, ["--METHOD=snake_case"]) assert not result.exception, result.output assert result.output == "snake_case\n" # Even though it's case sensitive, the choice's original value is preserved result = runner.invoke(cli, ["--method=pascalcase"]) assert not result.exception, result.output assert result.output == "PascalCase\n" result = runner.invoke(cli, ["--method=meh"]) assert result.exit_code == 2 assert ( "Invalid value for '--method': 'meh' is not one of " "'screaming_snake_case', 'snake_case', 'pascalcase', 'kebab-case'." ) in result.output result = runner.invoke(cli, ["--help"]) assert ( "--method [screaming_snake_case|snake_case|pascalcase|kebab-case]" in result.output ) def test_command_normalization(runner): @click.group(context_settings=CONTEXT_SETTINGS) def cli(): pass @cli.command() def foo(): click.echo("here!") result = runner.invoke(cli, ["FOO"]) assert result.output == "here!\n" asyncclick-8.3.0.5-async/tests/test_options.py000066400000000000000000002240051507140761400214010ustar00rootroot00000000000000import enum import os import re import sys import tempfile from contextlib import nullcontext from typing import Literal if sys.version_info < (3, 11): enum.StrEnum = enum.Enum # type: ignore[assignment] import pytest import asyncclick as click from asyncclick import Option from asyncclick import UNPROCESSED from asyncclick._utils import UNSET def test_prefixes(runner): @click.command() @click.option("++foo", is_flag=True, help="das foo") @click.option("--bar", is_flag=True, help="das bar") def cli(foo, bar): click.echo(f"foo={foo} bar={bar}") result = runner.invoke(cli, ["++foo", "--bar"]) assert not result.exception assert result.output == "foo=True bar=True\n" result = runner.invoke(cli, ["--help"]) assert re.search(r"\+\+foo\s+das foo", result.output) is not None assert re.search(r"--bar\s+das bar", result.output) is not None def test_invalid_option(runner): with pytest.raises(TypeError, match="name was passed") as exc_info: click.Option(["foo"]) message = str(exc_info.value) assert "name was passed (foo)" in message assert "declare an argument" in message assert "'--foo'" in message @pytest.mark.parametrize("deprecated", [True, "USE B INSTEAD"]) def test_deprecated_usage(runner, deprecated): @click.command() @click.option("--foo", default="bar", deprecated=deprecated) def cmd(foo): click.echo(foo) result = runner.invoke(cmd, ["--help"]) assert "(DEPRECATED" in result.output if isinstance(deprecated, str): assert deprecated in result.output @pytest.mark.parametrize("deprecated", [True, "USE B INSTEAD"]) def test_deprecated_warning(runner, deprecated): @click.command() @click.option( "--my-option", required=False, deprecated=deprecated, default="default option" ) def cli(my_option: str): click.echo(f"{my_option}") # defaults should not give a deprecated warning result = runner.invoke(cli, []) assert result.exit_code == 0, result.output assert "is deprecated" not in result.output result = runner.invoke(cli, ["--my-option", "hello"]) assert result.exit_code == 0, result.output assert "option 'my_option' is deprecated" in result.output if isinstance(deprecated, str): assert deprecated in result.output def test_deprecated_required(runner): with pytest.raises(ValueError, match="is deprecated and still required"): click.Option(["--a"], required=True, deprecated=True) def test_deprecated_prompt(runner): with pytest.raises(ValueError, match="`deprecated` options cannot use `prompt`"): click.Option(["--a"], prompt=True, deprecated=True) def test_invalid_nargs(runner): with pytest.raises(TypeError, match="nargs=-1 is not supported for options."): @click.command() @click.option("--foo", nargs=-1) def cli(foo): pass def test_nargs_tup_composite_mult(runner): @click.command() @click.option("--item", type=(str, int), multiple=True) def copy(item): for name, id in item: click.echo(f"name={name} id={id:d}") result = runner.invoke(copy, ["--item", "peter", "1", "--item", "max", "2"]) assert not result.exception assert result.output.splitlines() == ["name=peter id=1", "name=max id=2"] def test_counting(runner): @click.command() @click.option("-v", count=True, help="Verbosity", type=click.IntRange(0, 3)) def cli(v): click.echo(f"verbosity={v:d}") result = runner.invoke(cli, ["-vvv"]) assert not result.exception assert result.output == "verbosity=3\n" result = runner.invoke(cli, ["-vvvv"]) assert result.exception assert "Invalid value for '-v': 4 is not in the range 0<=x<=3." in result.output result = runner.invoke(cli, []) assert not result.exception assert result.output == "verbosity=0\n" result = runner.invoke(cli, ["--help"]) assert re.search(r"-v\s+Verbosity", result.output) is not None @pytest.mark.parametrize("unknown_flag", ["--foo", "-f"]) def test_unknown_options(runner, unknown_flag): @click.command() def cli(): pass result = runner.invoke(cli, [unknown_flag]) assert result.exception assert f"No such option: {unknown_flag}" in result.output @pytest.mark.parametrize( ("value", "expect"), [ ("--cat", "Did you mean --count?"), ("--bounds", "(Possible options: --bound, --count)"), ("--bount", "(Possible options: --bound, --count)"), ], ) def test_suggest_possible_options(runner, value, expect): cli = click.Command( "cli", params=[click.Option(["--bound"]), click.Option(["--count"])] ) result = runner.invoke(cli, [value]) assert expect in result.output def test_multiple_required(runner): @click.command() @click.option("-m", "--message", multiple=True, required=True) def cli(message): click.echo("\n".join(message)) result = runner.invoke(cli, ["-m", "foo", "-mbar"]) assert not result.exception assert result.output == "foo\nbar\n" result = runner.invoke(cli, []) assert result.exception assert "Error: Missing option '-m' / '--message'." in result.output @pytest.mark.parametrize( ("multiple", "nargs", "default", "expected"), [ # If multiple values are allowed, defaults should be iterable. (True, 1, [], ()), (True, 1, (), ()), (True, 1, tuple(), ()), (True, 1, set(), ()), (True, 1, frozenset(), ()), (True, 1, {}, ()), # Special values. (True, 1, None, ()), (True, 1, UNSET, ()), # Number of values are kept as-is in the default. (True, 1, [1], (1,)), (True, 1, [1, 2], (1, 2)), (True, 1, [1, 2, 3], (1, 2, 3)), (True, 1, [1.1, 2.2], (1.1, 2.2)), (True, 1, ["1", "2"], ("1", "2")), (True, 1, [None, None], (None, None)), # Contrary to list or tuples, native Python types not supported by Click are # not recognized and are converted to the default format: tuple of strings. # Refs: https://github.com/pallets/click/issues/3036 (True, 1, {1, 2}, ("1", "2")), (True, 1, frozenset([1, 2]), ("1", "2")), (True, 1, {1: "a", 2: "b"}, ("1", "2")), # Multiple values with nargs > 1. (True, 2, [], ()), (True, 2, (), ()), (True, 2, tuple(), ()), (True, 2, set(), ()), (True, 2, frozenset(), ()), (True, 2, {}, ()), (True, 2, None, ()), (True, 2, UNSET, ()), (True, 2, [[1, 2]], ((1, 2),)), (True, 2, [[1, 2], [3, 4]], ((1, 2), (3, 4))), (True, 2, [[1, 2], [3, 4], [5, 6]], ((1, 2), (3, 4), (5, 6))), (True, 2, [[1.1, 2.2], [3.3, 4.4]], ((1.1, 2.2), (3.3, 4.4))), (True, 2, [["1", "2"], ["3", "4"]], (("1", "2"), ("3", "4"))), (True, 2, [[None, None], [None, None]], ((None, None), (None, None))), (True, 2, [[1, 2.2], ["3", None]], ((1, 2.2), (3, None))), (True, 2, [[1, 2.2], None], ((1, 2.2), None)), # Default of the right length works for non-multiples. (False, 2, [1, 2], (1, 2)), ], ) def test_good_defaults_for_multiple(runner, multiple, nargs, default, expected): @click.command() @click.option("-a", multiple=multiple, nargs=nargs, default=default) def cmd(a): click.echo(repr(a), nl=False) result = runner.invoke(cmd) assert result.output == repr(expected) @pytest.mark.parametrize( ("multiple", "nargs", "default", "exception", "message"), [ # Non-iterables defaults. ( True, 1, "Yo", None, "Error: Invalid value for '-a': Value must be an iterable.", ), ( True, 1, "", None, "Error: Invalid value for '-a': Value must be an iterable.", ), ( True, 1, True, None, "Error: Invalid value for '-a': Value must be an iterable.", ), ( True, 1, False, None, "Error: Invalid value for '-a': Value must be an iterable.", ), ( True, 1, 12, None, "Error: Invalid value for '-a': Value must be an iterable.", ), ( True, 1, 7.9, None, "Error: Invalid value for '-a': Value must be an iterable.", ), # ( False, 2, 42, None, "Error: Invalid value for '-a': Value must be an iterable.", ), ( True, 2, ["test string which is not a list in the list"], None, "Error: Invalid value for '-a': Value must be an iterable.", ), # Multiple options, each with 2 args, but with wrong length. ( True, 2, (1,), None, "Error: Invalid value for '-a': Value must be an iterable.", ), ( True, 2, (1, 2, 3), None, "Error: Invalid value for '-a': Value must be an iterable.", ), ( True, 2, [tuple()], ValueError, r"'nargs' must be 0 \(or None\) for type , but it was 2\.", ), ( True, 2, [(1,)], ValueError, r"'nargs' must be 1 \(or None\) for type , but it was 2\.", ), ( True, 2, [(1, 2, 3)], ValueError, r"'nargs' must be 3 \(or None\) for type , but it was 2\.", ), # A mix of valid and invalid defaults. ( True, 2, [[1, 2.2], []], None, "Error: Invalid value for '-a': 2 values are required, but 0 were given.", ), # Default values that are iterable but not of the right length. ( False, 2, [1], None, "Error: Invalid value for '-a': Takes 2 values but 1 was given.", ), ( True, 2, [[1]], ValueError, r"'nargs' must be 1 \(or None\) for type , but it was 2\.", ), ], ) def test_bad_defaults_for_multiple( runner, multiple, nargs, default, exception, message ): if exception: assert issubclass(exception, Exception) else: assert exception is None with ( pytest.raises(exception, match=re.compile(message)) if exception else nullcontext() ): @click.command() @click.option("-a", multiple=multiple, nargs=nargs, default=default) def cmd(a): click.echo(repr(a)) result = runner.invoke(cmd) assert message in result.stderr @pytest.mark.parametrize("env_key", ["MYPATH", "AUTO_MYPATH"]) def test_empty_envvar(runner, env_key): @click.command() @click.option("--mypath", type=click.Path(exists=True), envvar="MYPATH") def cli(mypath): click.echo(f"mypath: {mypath}") result = runner.invoke(cli, env={env_key: ""}, auto_envvar_prefix="AUTO") assert result.exception is None assert result.output == "mypath: None\n" def test_multiple_envvar(runner): @click.command() @click.option("--arg", multiple=True) def cmd(arg): click.echo("|".join(arg)) result = runner.invoke( cmd, [], auto_envvar_prefix="TEST", env={"TEST_ARG": "foo bar baz"} ) assert not result.exception assert result.output == "foo|bar|baz\n" @click.command() @click.option("--arg", multiple=True, envvar="X") def cmd(arg): click.echo("|".join(arg)) result = runner.invoke(cmd, [], env={"X": "foo bar baz"}) assert not result.exception assert result.output == "foo|bar|baz\n" @click.command() @click.option("--arg", multiple=True, type=click.Path()) def cmd(arg): click.echo("|".join(arg)) result = runner.invoke( cmd, [], auto_envvar_prefix="TEST", env={"TEST_ARG": f"foo{os.path.pathsep}bar"}, ) assert not result.exception assert result.output == "foo|bar\n" @pytest.mark.parametrize( ("envvar_name", "envvar_value", "expected"), ( # Lower-cased variations of value. ("SHOUT", "true", True), ("SHOUT", "false", False), # Title-cased variations of value. ("SHOUT", "True", True), ("SHOUT", "False", False), # Upper-cased variations of value. ("SHOUT", "TRUE", True), ("SHOUT", "FALSE", False), # Random-cased variations of value. ("SHOUT", "TruE", True), ("SHOUT", "truE", True), ("SHOUT", "FaLsE", False), ("SHOUT", "falsE", False), # Extra spaces around the value. ("SHOUT", "true ", True), ("SHOUT", " true ", True), ("SHOUT", " true", True), ("SHOUT", "false ", False), ("SHOUT", " false ", False), ("SHOUT", " false", False), # Integer variations. ("SHOUT", "1", True), ("SHOUT", "0", False), # Alternative states. ("SHOUT", "t", True), ("SHOUT", "T", True), ("SHOUT", " T ", True), ("SHOUT", "f", False), ("SHOUT", "y", True), ("SHOUT", "n", False), ("SHOUT", "yes", True), ("SHOUT", "no", False), ("SHOUT", "on", True), ("SHOUT", "off", False), # Blank value variations. ("SHOUT", None, False), ("SHOUT", "", False), ("SHOUT", " ", False), ("SHOUT", " ", False), # Variable names are not stripped of spaces and so don't match the # flag, which then naturraly takes its default value. ("SHOUT ", "True", False), ("SHOUT ", "False", False), (" SHOUT ", "True", False), (" SHOUT ", "False", False), (" SHOUT", "True", False), (" SHOUT", "False", False), ("SH OUT", "True", False), ("SH OUT", "False", False), # Same for random and reverse environment variable names: they are not # recognized by the option. ("RANDOM", "True", False), ("NO_SHOUT", "True", False), ("NO_SHOUT", "False", False), ("NOSHOUT", "True", False), ("NOSHOUT", "False", False), ), ) def test_boolean_flag_envvar(runner, envvar_name, envvar_value, expected): assert isinstance(envvar_name, str) assert isinstance(envvar_value, str) or envvar_value is None @click.command() @click.option("--shout/--no-shout", envvar="SHOUT") def cli(shout): click.echo(repr(shout), nl=False) result = runner.invoke(cli, [], env={envvar_name: envvar_value}) assert result.exit_code == 0 assert result.output == repr(expected) @pytest.mark.parametrize( "value", ( # Extra spaces inside the value. "tr ue", "fa lse", # Numbers. "10", "01", "00", "11", "0.0", "1.1", # Random strings. "randomstring", "None", "'None'", "A B", " 1 2 ", "9.3", "a;n", "x:y", "i/o", ), ) def test_boolean_envvar_bad_values(runner, value): @click.command() @click.option("--shout/--no-shout", envvar="SHOUT") def cli(shout): click.echo(shout) result = runner.invoke(cli, [], env={"SHOUT": value}) assert result.exit_code == 2 assert ( f"Invalid value for '--shout': {value!r} is not a valid boolean." in result.output ) def test_multiple_default_help(runner): @click.command() @click.option("--arg1", multiple=True, default=("foo", "bar"), show_default=True) @click.option("--arg2", multiple=True, default=(1, 2), type=int, show_default=True) def cmd(arg, arg2): pass result = runner.invoke(cmd, ["--help"]) assert not result.exception assert "foo, bar" in result.output assert "1, 2" in result.output def test_show_default_default_map(runner): @click.command() @click.option("--arg", default="a", show_default=True) def cmd(arg): click.echo(arg) result = runner.invoke(cmd, ["--help"], default_map={"arg": "b"}) assert not result.exception assert "[default: b]" in result.output def test_multiple_default_type(): opt = click.Option(["-a"], multiple=True, default=(1, 2)) assert opt.nargs == 1 assert opt.multiple assert opt.type is click.INT ctx = click.Context(click.Command("test")) assert opt.get_default(ctx) == (1, 2) def test_multiple_default_composite_type(): opt = click.Option(["-a"], multiple=True, default=[(1, "a")]) assert opt.nargs == 2 assert opt.multiple assert isinstance(opt.type, click.Tuple) assert opt.type.types == [click.INT, click.STRING] ctx = click.Context(click.Command("test")) assert opt.type_cast_value(ctx, opt.get_default(ctx)) == ((1, "a"),) def test_parse_multiple_default_composite_type(runner): @click.command() @click.option("-a", multiple=True, default=("a", "b")) @click.option("-b", multiple=True, default=[(1, "a")]) def cmd(a, b): click.echo(a) click.echo(b) # result = runner.invoke(cmd, "-a c -a 1 -a d -b 2 two -b 4 four".split()) # assert result.output == "('c', '1', 'd')\n((2, 'two'), (4, 'four'))\n" result = runner.invoke(cmd) assert result.output == "('a', 'b')\n((1, 'a'),)\n" def test_dynamic_default_help_unset(runner): @click.command() @click.option( "--username", prompt=True, default=lambda: os.environ.get("USER", ""), show_default=True, ) def cmd(username): print("Hello,", username) result = runner.invoke(cmd, ["--help"]) assert result.exit_code == 0 assert "--username" in result.output assert "lambda" not in result.output assert "(dynamic)" in result.output def test_dynamic_default_help_text(runner): @click.command() @click.option( "--username", prompt=True, default=lambda: os.environ.get("USER", ""), show_default="current user", ) def cmd(username): print("Hello,", username) result = runner.invoke(cmd, ["--help"]) assert result.exit_code == 0 assert "--username" in result.output assert "lambda" not in result.output assert "(current user)" in result.output def test_dynamic_default_help_special_method(runner): class Value: def __call__(self): return 42 def __str__(self): return "special value" opt = click.Option(["-a"], default=Value(), show_default=True) ctx = click.Context(click.Command("cli")) assert opt.get_help_extra(ctx) == {"default": "special value"} assert "special value" in opt.get_help_record(ctx)[1] @pytest.mark.parametrize( ("type", "expect"), [ (click.IntRange(1, 32), "1<=x<=32"), (click.IntRange(1, 32, min_open=True, max_open=True), "1=1"), (click.IntRange(max=32), "x<=32"), ], ) def test_intrange_default_help_text(type, expect): option = click.Option(["--num"], type=type, show_default=True, default=2) context = click.Context(click.Command("test")) assert option.get_help_extra(context) == {"default": "2", "range": expect} result = option.get_help_record(context)[1] assert expect in result def test_count_default_type_help(): """A count option with the default type should not show >=0 in help.""" option = click.Option(["--count"], count=True, help="some words") context = click.Context(click.Command("test")) assert option.get_help_extra(context) == {} result = option.get_help_record(context)[1] assert result == "some words" def test_file_type_help_default(): """The default for a File type is a filename string. The string should be displayed in help, not an open file object. Type casting is only applied to defaults in processing, not when getting the default value. """ option = click.Option( ["--in"], type=click.File(), default=__file__, show_default=True ) context = click.Context(click.Command("test")) assert option.get_help_extra(context) == {"default": __file__} result = option.get_help_record(context)[1] assert __file__ in result def test_toupper_envvar_prefix(runner): @click.command() @click.option("--arg") def cmd(arg): click.echo(arg) result = runner.invoke(cmd, [], auto_envvar_prefix="test", env={"TEST_ARG": "foo"}) assert not result.exception assert result.output == "foo\n" def test_nargs_envvar(runner): @click.command() @click.option("--arg", nargs=2) def cmd(arg): click.echo("|".join(arg)) result = runner.invoke( cmd, [], auto_envvar_prefix="TEST", env={"TEST_ARG": "foo bar"} ) assert not result.exception assert result.output == "foo|bar\n" @click.command() @click.option("--arg", nargs=2, multiple=True) def cmd(arg): for item in arg: click.echo("|".join(item)) result = runner.invoke( cmd, [], auto_envvar_prefix="TEST", env={"TEST_ARG": "x 1 y 2"} ) assert not result.exception assert result.output == "x|1\ny|2\n" def test_show_envvar(runner): @click.command() @click.option("--arg1", envvar="ARG1", show_envvar=True) def cmd(arg): pass result = runner.invoke(cmd, ["--help"]) assert not result.exception assert "ARG1" in result.output def test_show_envvar_auto_prefix(runner): @click.command() @click.option("--arg1", show_envvar=True) def cmd(arg): pass result = runner.invoke(cmd, ["--help"], auto_envvar_prefix="TEST") assert not result.exception assert "TEST_ARG1" in result.output def test_show_envvar_auto_prefix_dash_in_command(runner): @click.group() def cli(): pass @cli.command() @click.option("--baz", show_envvar=True) def foo_bar(baz): pass result = runner.invoke(cli, ["foo-bar", "--help"], auto_envvar_prefix="TEST") assert not result.exception assert "TEST_FOO_BAR_BAZ" in result.output def test_custom_validation(runner): def validate_pos_int(ctx, param, value): if value < 0: raise click.BadParameter("Value needs to be positive") return value @click.command() @click.option("--foo", callback=validate_pos_int, default=1) def cmd(foo): click.echo(foo) result = runner.invoke(cmd, ["--foo", "-1"]) assert "Invalid value for '--foo': Value needs to be positive" in result.output result = runner.invoke(cmd, ["--foo", "42"]) assert result.output == "42\n" @pytest.mark.anyio async def test_callback_validates_prompt(arunner): def validate(ctx, param, value): if value < 0: raise click.BadParameter("should be positive") return value @click.command() @click.option("-a", type=int, callback=validate, prompt=True) def cli(a): click.echo(a) result = await arunner.invoke(cli, input="-12\n60\n") assert result.output == "A: -12\nError: should be positive\nA: 60\n60\n" def test_winstyle_options(runner): @click.command() @click.option("/debug;/no-debug", help="Enables or disables debug mode.") def cmd(debug): click.echo(debug) result = runner.invoke(cmd, ["/debug"], help_option_names=["/?"]) assert result.output == "True\n" result = runner.invoke(cmd, ["/no-debug"], help_option_names=["/?"]) assert result.output == "False\n" result = runner.invoke(cmd, [], help_option_names=["/?"]) assert result.output == "False\n" result = runner.invoke(cmd, ["/?"], help_option_names=["/?"]) assert "/debug; /no-debug Enables or disables debug mode." in result.output assert "/? Show this message and exit." in result.output def test_legacy_options(runner): @click.command() @click.option("-whatever") def cmd(whatever): click.echo(whatever) result = runner.invoke(cmd, ["-whatever", "42"]) assert result.output == "42\n" result = runner.invoke(cmd, ["-whatever=23"]) assert result.output == "23\n" @pytest.mark.parametrize( ("value", "expect_missing", "processed_value"), [ (UNSET, True, None), (None, False, None), # Default type of the argument is str, so everything is processed as strings. ("", False, ""), (" ", False, " "), ("foo", False, "foo"), ("12", False, "12"), (12, False, "12"), (12.1, False, "12.1"), (list(), False, "[]"), (tuple(), False, "()"), (set(), False, "set()"), (frozenset(), False, "frozenset()"), (dict(), False, "{}"), ], ) @pytest.mark.anyio async def test_required_option(value, expect_missing, processed_value): ctx = click.Context(click.Command("")) argument = click.Option(["-a"], required=True) if expect_missing: with pytest.raises(click.MissingParameter) as excinfo: await argument.process_value(ctx, value) assert str(excinfo.value) == "Missing parameter: a" else: value = await argument.process_value(ctx, value) assert value == processed_value def test_missing_required_flag(runner): cli = click.Command( "cli", params=[click.Option(["--on/--off"], is_flag=True, required=True)] ) result = runner.invoke(cli) assert result.exit_code == 2 assert "Error: Missing option '--on'." in result.output def test_missing_choice(runner): @click.command() @click.option("--foo", type=click.Choice(["foo", "bar"]), required=True) def cmd(foo): click.echo(foo) result = runner.invoke(cmd) assert result.exit_code == 2 error, separator, choices = result.output.partition("Choose from") assert "Error: Missing option '--foo'. " in error assert "Choose from" in separator assert "foo" in choices assert "bar" in choices def test_missing_envvar(runner): cli = click.Command( "cli", params=[click.Option(["--foo"], envvar="bar", required=True)] ) result = runner.invoke(cli) assert result.exit_code == 2 assert "Error: Missing option '--foo'." in result.output cli = click.Command( "cli", params=[click.Option(["--foo"], envvar="bar", show_envvar=True, required=True)], ) result = runner.invoke(cli) assert result.exit_code == 2 assert "Error: Missing option '--foo' (env var: 'bar')." in result.output cli = click.Command( "cli", params=[click.Option(["--foo"], show_envvar=True, required=True)] ) result = runner.invoke(cli) assert result.exit_code == 2 assert "Error: Missing option '--foo'." in result.output def test_case_insensitive_choice(runner): @click.command() @click.option("--foo", type=click.Choice(["Orange", "Apple"], case_sensitive=False)) def cmd(foo): click.echo(foo) result = runner.invoke(cmd, ["--foo", "apple"]) assert result.exit_code == 0 assert result.output == "Apple\n" result = runner.invoke(cmd, ["--foo", "oRANGe"]) assert result.exit_code == 0 assert result.output == "Orange\n" result = runner.invoke(cmd, ["--foo", "Apple"]) assert result.exit_code == 0 assert result.output == "Apple\n" @click.command() @click.option("--foo", type=click.Choice(["Orange", "Apple"])) def cmd2(foo): click.echo(foo) result = runner.invoke(cmd2, ["--foo", "apple"]) assert result.exit_code == 2 result = runner.invoke(cmd2, ["--foo", "oRANGe"]) assert result.exit_code == 2 result = runner.invoke(cmd2, ["--foo", "Apple"]) assert result.exit_code == 0 def test_case_insensitive_choice_returned_exactly(runner): @click.command() @click.option("--foo", type=click.Choice(["Orange", "Apple"], case_sensitive=False)) def cmd(foo): click.echo(foo) result = runner.invoke(cmd, ["--foo", "apple"]) assert result.exit_code == 0 assert result.output == "Apple\n" def test_option_help_preserve_paragraphs(runner): @click.command() @click.option( "-C", "--config", type=click.Path(), help="""Configuration file to use. If not given, the environment variable CONFIG_FILE is consulted and used if set. If neither are given, a default configuration file is loaded.""", ) def cmd(config): pass result = runner.invoke(cmd, ["--help"]) assert result.exit_code == 0 i = " " * 21 assert ( " -C, --config PATH Configuration file to use.\n" f"{i}\n" f"{i}If not given, the environment variable CONFIG_FILE is\n" f"{i}consulted and used if set. If neither are given, a default\n" f"{i}configuration file is loaded." ) in result.output def test_argument_custom_class(runner): class CustomArgument(click.Argument): def get_default(self, ctx, call=True): """a dumb override of a default value for testing""" return "I am a default" @click.command() @click.argument("testarg", cls=CustomArgument, default="you wont see me") def cmd(testarg): click.echo(testarg) result = runner.invoke(cmd) assert "I am a default" in result.output assert "you wont see me" not in result.output def test_option_custom_class(runner): class CustomOption(click.Option): def get_help_record(self, ctx): """a dumb override of a help text for testing""" return ("--help", "I am a help text") @click.command() @click.option("--testoption", cls=CustomOption, help="you wont see me") def cmd(testoption): click.echo(testoption) result = runner.invoke(cmd, ["--help"]) assert "I am a help text" in result.output assert "you wont see me" not in result.output def test_option_custom_class_reusable(runner): """Ensure we can reuse a custom class option. See Issue #926""" class CustomOption(click.Option): def get_help_record(self, ctx): """a dumb override of a help text for testing""" return ("--help", "I am a help text") # Assign to a variable to re-use the decorator. testoption = click.option("--testoption", cls=CustomOption, help="you wont see me") @click.command() @testoption def cmd1(testoption): click.echo(testoption) @click.command() @testoption def cmd2(testoption): click.echo(testoption) # Both of the commands should have the --help option now. for cmd in (cmd1, cmd2): result = runner.invoke(cmd, ["--help"]) assert "I am a help text" in result.output assert "you wont see me" not in result.output @pytest.mark.parametrize("custom_class", (True, False)) @pytest.mark.parametrize( ("name_specs", "expected"), ( ( ("-h", "--help"), " -h, --help Show this message and exit.\n", ), ( ("-h",), " -h Show this message and exit.\n" " --help Show this message and exit.\n", ), ( ("--help",), " --help Show this message and exit.\n", ), ), ) def test_help_option_custom_names_and_class(runner, custom_class, name_specs, expected): class CustomHelpOption(click.Option): pass option_attrs = {} if custom_class: option_attrs["cls"] = CustomHelpOption @click.command() @click.help_option(*name_specs, **option_attrs) def cmd(): pass for arg in name_specs: result = runner.invoke(cmd, [arg]) assert not result.exception assert result.exit_code == 0 assert expected in result.output def test_bool_flag_with_type(runner): @click.command() @click.option("--shout/--no-shout", default=False, type=bool) def cmd(shout): pass result = runner.invoke(cmd) assert not result.exception def test_aliases_for_flags(runner): @click.command() @click.option("--warnings/--no-warnings", " /-W", default=True) def cli(warnings): click.echo(warnings) result = runner.invoke(cli, ["--warnings"]) assert result.output == "True\n" result = runner.invoke(cli, ["--no-warnings"]) assert result.output == "False\n" result = runner.invoke(cli, ["-W"]) assert result.output == "False\n" @click.command() @click.option("--warnings/--no-warnings", "-w", default=True) def cli_alt(warnings): click.echo(warnings) result = runner.invoke(cli_alt, ["--warnings"]) assert result.output == "True\n" result = runner.invoke(cli_alt, ["--no-warnings"]) assert result.output == "False\n" result = runner.invoke(cli_alt, ["-w"]) assert result.output == "True\n" @pytest.mark.parametrize( "option_args,expected", [ (["--aggressive", "--all", "-a"], "aggressive"), (["--first", "--second", "--third", "-a", "-b", "-c"], "first"), (["--apple", "--banana", "--cantaloupe", "-a", "-b", "-c"], "apple"), (["--cantaloupe", "--banana", "--apple", "-c", "-b", "-a"], "cantaloupe"), (["-a", "-b", "-c"], "a"), (["-c", "-b", "-a"], "c"), (["-a", "--apple", "-b", "--banana", "-c", "--cantaloupe"], "apple"), (["-c", "-a", "--cantaloupe", "-b", "--banana", "--apple"], "cantaloupe"), (["--from", "-f", "_from"], "_from"), (["--return", "-r", "_ret"], "_ret"), ], ) def test_option_names(runner, option_args, expected): @click.command() @click.option(*option_args, is_flag=True) def cmd(**kwargs): click.echo(str(kwargs[expected])) assert cmd.params[0].name == expected for form in option_args: if form.startswith("-"): result = runner.invoke(cmd, [form]) assert result.output == "True\n" def test_flag_duplicate_names(runner): with pytest.raises(ValueError, match="cannot use the same flag for true/false"): click.Option(["--foo/--foo"], default=False) @pytest.mark.parametrize(("default", "expect"), [(False, "no-cache"), (True, "cache")]) def test_show_default_boolean_flag_name(runner, default, expect): """When a boolean flag has distinct True/False opts, it should show the default opt name instead of the default value. It should only show one name even if multiple are declared. """ opt = click.Option( ("--cache/--no-cache", "--c/--nc"), default=default, show_default=True, help="Enable/Disable the cache.", ) ctx = click.Context(click.Command("test")) assert opt.get_help_extra(ctx) == {"default": expect} message = opt.get_help_record(ctx)[1] assert f"[default: {expect}]" in message def test_show_true_default_boolean_flag_value(runner): """When a boolean flag only has one opt and its default is True, it will show the default value, not the opt name. """ opt = click.Option( ("--cache",), is_flag=True, show_default=True, default=True, help="Enable the cache.", ) ctx = click.Context(click.Command("test")) assert opt.get_help_extra(ctx) == {"default": "True"} message = opt.get_help_record(ctx)[1] assert "[default: True]" in message @pytest.mark.parametrize("default", [False, None]) def test_hide_false_default_boolean_flag_value(runner, default): """When a boolean flag only has one opt and its default is False or None, it will not show the default """ opt = click.Option( ("--cache",), is_flag=True, show_default=True, default=default, help="Enable the cache.", ) ctx = click.Context(click.Command("test")) assert opt.get_help_extra(ctx) == {} message = opt.get_help_record(ctx)[1] assert "[default: " not in message def test_show_default_string(runner): """When show_default is a string show that value as default.""" opt = click.Option(["--limit"], show_default="unlimited") ctx = click.Context(click.Command("cli")) assert opt.get_help_extra(ctx) == {"default": "(unlimited)"} message = opt.get_help_record(ctx)[1] assert "[default: (unlimited)]" in message def test_show_default_with_empty_string(runner): """When show_default is True and default is set to an empty string.""" opt = click.Option(["--limit"], default="", show_default=True) ctx = click.Context(click.Command("cli")) message = opt.get_help_record(ctx)[1] assert '[default: ""]' in message def test_do_not_show_no_default(runner): """When show_default is True and no default is set do not show None.""" opt = click.Option(["--limit"], show_default=True) ctx = click.Context(click.Command("cli")) assert opt.get_help_extra(ctx) == {} message = opt.get_help_record(ctx)[1] assert "[default: None]" not in message def test_do_not_show_default_empty_multiple(): """When show_default is True and multiple=True is set, it should not print empty default value in --help output. """ opt = click.Option(["-a"], multiple=True, help="values", show_default=True) ctx = click.Context(click.Command("cli")) assert opt.get_help_extra(ctx) == {} message = opt.get_help_record(ctx)[1] assert message == "values" @pytest.mark.parametrize( ("ctx_value", "opt_value", "extra_value", "expect"), [ (None, None, {}, False), (None, False, {}, False), (None, True, {"default": "1"}, True), (False, None, {}, False), (False, False, {}, False), (False, True, {"default": "1"}, True), (True, None, {"default": "1"}, True), (True, False, {}, False), (True, True, {"default": "1"}, True), (False, "one", {"default": "(one)"}, True), ], ) def test_show_default_precedence(ctx_value, opt_value, extra_value, expect): ctx = click.Context(click.Command("test"), show_default=ctx_value) opt = click.Option("-a", default=1, help="value", show_default=opt_value) assert opt.get_help_extra(ctx) == extra_value help = opt.get_help_record(ctx)[1] assert ("default:" in help) is expect @pytest.mark.parametrize( ("args", "expect"), [ (None, (None, None, ())), (["--opt"], ("flag", None, ())), (["--opt", "-a", 42], ("flag", "42", ())), (["--opt", "test", "-a", 42], ("test", "42", ())), (["--opt=test", "-a", 42], ("test", "42", ())), (["-o"], ("flag", None, ())), (["-o", "-a", 42], ("flag", "42", ())), (["-o", "test", "-a", 42], ("test", "42", ())), (["-otest", "-a", 42], ("test", "42", ())), (["a", "b", "c"], (None, None, ("a", "b", "c"))), (["--opt", "a", "b", "c"], ("a", None, ("b", "c"))), (["--opt", "test"], ("test", None, ())), (["-otest", "a", "b", "c"], ("test", None, ("a", "b", "c"))), (["--opt=test", "a", "b", "c"], ("test", None, ("a", "b", "c"))), ], ) def test_option_with_optional_value(runner, args, expect): @click.command() @click.option("-o", "--opt", is_flag=False, flag_value="flag") @click.option("-a") @click.argument("b", nargs=-1) def cli(opt, a, b): return opt, a, b result = runner.invoke(cli, args, standalone_mode=False, catch_exceptions=False) assert result.return_value == expect def test_multiple_option_with_optional_value(runner): cli = click.Command( "cli", params=[ click.Option(["-f"], is_flag=False, flag_value="flag", multiple=True), click.Option(["-a"]), click.Argument(["b"], nargs=-1), ], callback=lambda **kwargs: kwargs, ) result = runner.invoke( cli, ["-f", "-f", "other", "-f", "-a", "1", "a", "b"], standalone_mode=False, catch_exceptions=False, ) assert result.return_value == { "f": ("flag", "other", "flag"), "a": "1", "b": ("a", "b"), } def test_type_from_flag_value(): param = click.Option(["-a", "x"], default=True, flag_value=4) assert param.type is click.INT param = click.Option(["-b", "x"], flag_value=8) assert param.type is click.INT @pytest.mark.parametrize( ("opt_params", "args", "expected"), [ # The type passed to the option is responsible to converting the value, whether # we pass the option flag or not. ({"type": bool}, [], False), ({"type": bool}, ["--foo"], True), ({"type": click.BOOL}, [], False), ({"type": click.BOOL}, ["--foo"], True), ({"type": str}, [], None), ({"type": str}, ["--foo"], "True"), # Default value is given as-is to the --foo option when it is not passed, # whatever the type. Now if --foo is passed, the value is always True, whatever # the type. In both case the type of the option is responsible for the # conversion of the value. ({"type": bool, "default": True}, [], True), ({"type": bool, "default": True}, ["--foo"], True), ({"type": bool, "default": False}, [], False), ({"type": bool, "default": False}, ["--foo"], True), # ({"type": bool, "default": "foo"}, [], "foo"), ({"type": bool, "default": "foo"}, ["--foo"], True), ({"type": bool, "default": None}, [], None), ({"type": bool, "default": None}, ["--foo"], True), ({"type": click.BOOL, "default": True}, [], True), ({"type": click.BOOL, "default": True}, ["--foo"], True), ({"type": click.BOOL, "default": False}, [], False), ({"type": click.BOOL, "default": False}, ["--foo"], True), # ({"type": click.BOOL, "default": "foo"}, [], "foo"), ({"type": click.BOOL, "default": "foo"}, ["--foo"], True), ({"type": click.BOOL, "default": None}, [], None), ({"type": click.BOOL, "default": None}, ["--foo"], True), ({"type": str, "default": True}, [], "True"), ({"type": str, "default": True}, ["--foo"], "True"), ({"type": str, "default": False}, [], "False"), ({"type": str, "default": False}, ["--foo"], "True"), ({"type": str, "default": "foo"}, [], "foo"), ({"type": str, "default": "foo"}, ["--foo"], "True"), ({"type": str, "default": None}, [], None), ({"type": str, "default": None}, ["--foo"], "True"), # Flag value is given as-is to the --foo option when it is passed, then # converted by the option type. ({"type": bool, "flag_value": True}, [], False), ({"type": bool, "flag_value": True}, ["--foo"], True), ({"type": bool, "flag_value": False}, [], False), ({"type": bool, "flag_value": False}, ["--foo"], False), ({"type": bool, "flag_value": None}, [], False), ({"type": bool, "flag_value": None}, ["--foo"], None), ({"type": click.BOOL, "flag_value": True}, [], False), ({"type": click.BOOL, "flag_value": True}, ["--foo"], True), ({"type": click.BOOL, "flag_value": False}, [], False), ({"type": click.BOOL, "flag_value": False}, ["--foo"], False), ({"type": click.BOOL, "flag_value": None}, [], False), ({"type": click.BOOL, "flag_value": None}, ["--foo"], None), ({"type": str, "flag_value": True}, [], None), ({"type": str, "flag_value": True}, ["--foo"], "True"), ({"type": str, "flag_value": False}, [], None), ({"type": str, "flag_value": False}, ["--foo"], "False"), ({"type": str, "flag_value": "foo"}, [], None), ({"type": str, "flag_value": "foo"}, ["--foo"], "foo"), ({"type": str, "flag_value": None}, [], None), ({"type": str, "flag_value": None}, ["--foo"], None), # Not passing --foo returns the default value as-is, in its Python type, then # converted by the option type. ({"type": bool, "default": True, "flag_value": True}, [], True), ({"type": bool, "default": True, "flag_value": False}, [], False), ({"type": bool, "default": False, "flag_value": True}, [], False), ({"type": bool, "default": False, "flag_value": False}, [], False), ({"type": bool, "default": None, "flag_value": True}, [], None), ({"type": bool, "default": None, "flag_value": False}, [], None), ({"type": str, "default": True, "flag_value": True}, [], "True"), ({"type": str, "default": True, "flag_value": False}, [], "False"), ({"type": str, "default": False, "flag_value": True}, [], "False"), ({"type": str, "default": False, "flag_value": False}, [], "False"), ({"type": str, "default": "foo", "flag_value": True}, [], "foo"), ({"type": str, "default": "foo", "flag_value": False}, [], "foo"), ({"type": str, "default": "foo", "flag_value": "bar"}, [], "foo"), ({"type": str, "default": "foo", "flag_value": None}, [], "foo"), ({"type": str, "default": None, "flag_value": True}, [], None), ({"type": str, "default": None, "flag_value": False}, [], None), # Passing --foo returns the flag_value that was explicitly set by the user, # with its Python type, but still converted by the option type. ({"type": bool, "default": True, "flag_value": True}, ["--foo"], True), ({"type": bool, "default": True, "flag_value": False}, ["--foo"], False), ({"type": bool, "default": False, "flag_value": True}, ["--foo"], True), ({"type": bool, "default": False, "flag_value": False}, ["--foo"], False), ({"type": bool, "default": None, "flag_value": True}, ["--foo"], True), ({"type": bool, "default": None, "flag_value": False}, ["--foo"], False), ({"type": str, "default": True, "flag_value": True}, ["--foo"], "True"), ({"type": str, "default": True, "flag_value": False}, ["--foo"], "False"), ({"type": str, "default": False, "flag_value": True}, ["--foo"], "True"), ({"type": str, "default": False, "flag_value": False}, ["--foo"], "False"), ({"type": str, "default": "foo", "flag_value": True}, ["--foo"], "True"), ({"type": str, "default": "foo", "flag_value": False}, ["--foo"], "False"), ({"type": str, "default": "foo", "flag_value": "bar"}, ["--foo"], "bar"), ({"type": str, "default": "foo", "flag_value": None}, ["--foo"], None), ({"type": str, "default": None, "flag_value": True}, ["--foo"], "True"), ({"type": str, "default": None, "flag_value": False}, ["--foo"], "False"), ], ) def test_flag_value_and_default(runner, opt_params, args, expected): @click.command() @click.option("--foo", is_flag=True, **opt_params) def cmd(foo): click.echo(repr(foo), nl=False) result = runner.invoke(cmd, args) assert result.output == repr(expected) @pytest.mark.parametrize( ("args", "opts"), [ ([], {"type": bool, "default": "foo"}), ([], {"type": click.BOOL, "default": "foo"}), (["--foo"], {"type": bool, "flag_value": "foo"}), (["--foo"], {"type": click.BOOL, "flag_value": "foo"}), ], ) def test_invalid_flag_definition(runner, args, opts): @click.command() @click.option("--foo", is_flag=True, **opts) def cmd(foo): click.echo(foo) result = runner.invoke(cmd, args) assert ( "Error: Invalid value for '--foo': 'foo' is not a valid boolean" in result.output ) @pytest.mark.parametrize( ("default", "args", "expected"), # These test cases are similar to the ones in # tests/test_basic.py::test_flag_value_dual_options, so keep them in sync. ( # Each option is returning its own flag_value, whatever the default is. (True, ["--js"], "js"), (True, ["--xml"], "xml"), (False, ["--js"], "js"), (False, ["--xml"], "xml"), (None, ["--js"], "js"), (None, ["--xml"], "xml"), (UNSET, ["--js"], "js"), (UNSET, ["--xml"], "xml"), # Check that the last option wins when both are specified. (True, ["--js", "--xml"], "xml"), (True, ["--xml", "--js"], "js"), # Check that the default is returned as-is when no option is specified. ("js", [], "js"), ("xml", [], "xml"), ("jS", [], "jS"), ("xMl", [], "xMl"), (" ᕕ( ᐛ )ᕗ ", [], " ᕕ( ᐛ )ᕗ "), (None, [], None), # Special case: UNSET is not provided as-is to the callback, but normalized to # None. (UNSET, [], None), # Special case: if default=True and flag_value is set, the value returned is the # flag_value, not the True Python value itself. (True, [], "js"), # Non-string defaults are process as strings by the default Parameter's type. (False, [], "False"), (42, [], "42"), (12.3, [], "12.3"), ), ) def test_default_dual_option_callback(runner, default, args, expected): """Check how default is processed by the callback when options compete for the same variable name. Reproduction of the issue reported in https://github.com/pallets/click/pull/3030#discussion_r2271571819 """ def _my_func(ctx, param, value): # Print the value received by the callback as-is, so we can check for it. return f"Callback value: {value!r}" @click.command() @click.option("--js", "fmt", flag_value="js", callback=_my_func, default=default) @click.option("--xml", "fmt", flag_value="xml", callback=_my_func) def main(fmt): click.secho(fmt, nl=False) result = runner.invoke(main, args) assert result.output == f"Callback value: {expected!r}" assert result.exit_code == 0 @pytest.mark.parametrize( ("flag_value", "envvar_value", "expected"), [ # The envvar match exactly the flag value and is case-sensitive. ("bar", "bar", "bar"), ("BAR", "BAR", "BAR"), (" bar ", " bar ", " bar "), ("42", "42", "42"), ("None", "None", "None"), ("True", "True", "True"), ("False", "False", "False"), ("true", "true", "true"), ("false", "false", "false"), ("A B", "A B", "A B"), (" 1 2 ", " 1 2 ", " 1 2 "), ("9.3", "9.3", "9.3"), ("a;n", "a;n", "a;n"), ("x:y", "x:y", "x:y"), ("i/o", "i/o", "i/o"), # Empty or absent envvar is consider unset, so the flag default value is # returned, which is None in this case. ("bar", "", None), ("bar", None, None), ("BAR", "", None), ("BAR", None, None), (" bar ", "", None), (" bar ", None, None), (42, "", None), (42, None, None), ("42", "", None), ("42", None, None), (None, "", None), (None, None, None), ("None", "", None), ("None", None, None), (True, "", None), (True, None, None), ("True", "", None), ("True", None, None), ("true", "", None), ("true", None, None), (False, "", None), (False, None, None), ("False", "", None), ("False", None, None), ("false", "", None), ("false", None, None), # Activate the flag with a value recognized as True by the envvar, which # returns the flag_value. ("bar", "True", "bar"), ("bar", "true", "bar"), ("bar", "trUe", "bar"), ("bar", " TRUE ", "bar"), ("bar", "1", "bar"), ("bar", "yes", "bar"), ("bar", "on", "bar"), ("bar", "t", "bar"), ("bar", "y", "bar"), # Deactivating the flag with a value recognized as False by the envvar, which # explicitly return the 'False' as the option is explicitly declared as a # string. ("bar", "False", "False"), ("bar", "false", "False"), ("bar", "faLse", "False"), ("bar", " FALSE ", "False"), ("bar", "0", "False"), ("bar", "no", "False"), ("bar", "off", "False"), ("bar", "f", "False"), ("bar", "n", "False"), # Any other value than the flag_value, or a recogned True or False value, fails # to explicitly activate or deactivate the flag. So the flag default value is # returned, which is None in this case. ("bar", " bar ", None), ("bar", "BAR", None), ("bar", "random", None), ("bar", "bar random", None), ("bar", "random bar", None), ("BAR", "bar", None), (" bar ", "bar", None), (" bar ", "BAR", None), (42, "42", None), (42, "foo", None), (None, "foo", None), ("None", "foo", None), ], ) def test_envvar_string_flag_value(runner, flag_value, envvar_value, expected): """Ensure that flag_value is recognized by the envvar.""" @click.command() @click.option("--upper", type=str, flag_value=flag_value, envvar="UPPER") def cmd(upper): click.echo(repr(upper), nl=False) result = runner.invoke(cmd, env={"UPPER": envvar_value}) assert result.exit_code == 0 assert result.output == repr(expected) @pytest.mark.parametrize( ("opt_decls", "opt_params", "expect_is_flag", "expect_is_bool_flag"), [ # Not boolean flags. ("-a", {"type": int}, False, False), ("-a", {"type": bool}, False, False), ("-a", {"default": True}, False, False), ("-a", {"default": False}, False, False), ("-a", {"flag_value": 1}, True, False), # Boolean flags. ("-a", {"is_flag": True}, True, True), ("-a/-A", {}, True, True), ("-a", {"flag_value": True}, True, True), # Non-flag with flag_value. ("-a", {"is_flag": False, "flag_value": 1}, False, False), ], ) def test_flag_auto_detection( opt_decls, opt_params, expect_is_flag, expect_is_bool_flag ): option = Option([opt_decls], **opt_params) assert option.is_flag is expect_is_flag assert option.is_bool_flag is expect_is_bool_flag @pytest.mark.parametrize( ("kwargs", "message"), [ ({"count": True, "multiple": True}, "'count' is not valid with 'multiple'."), ({"count": True, "is_flag": True}, "'count' is not valid with 'is_flag'."), ], ) def test_invalid_flag_combinations(runner, kwargs, message): with pytest.raises(TypeError) as e: click.Option(["-a"], **kwargs) assert message in str(e.value) def test_non_flag_with_non_negatable_default(runner): class NonNegatable: def __bool__(self): raise ValueError("Cannot negate this object") @click.command() @click.option("--foo", default=NonNegatable()) def cmd(foo): pass result = runner.invoke(cmd) assert result.exit_code == 0 class HashType(enum.Enum): MD5 = "MD5" SHA1 = "SHA1" SHA256 = "SHA-256" class Number(enum.IntEnum): ONE = enum.auto() TWO = enum.auto() class Letter(enum.StrEnum): NAME_1 = "Value-1" NAME_2 = "Value_2" NAME_3 = "42_value" class Color(enum.Flag): RED = enum.auto() GREEN = enum.auto() BLUE = enum.auto() class ColorInt(enum.IntFlag): RED = enum.auto() GREEN = enum.auto() BLUE = enum.auto() @pytest.mark.parametrize( ("choices", "metavar"), [ (["foo", "bar"], "[TEXT]"), ([1, 2], "[INTEGER]"), ([1.0, 2.0], "[FLOAT]"), ([True, False], "[BOOLEAN]"), (["foo", 1], "[TEXT|INTEGER]"), (HashType, "[HASHTYPE]"), (Number, "[NUMBER]"), (Letter, "[LETTER]"), (Color, "[COLOR]"), (ColorInt, "[COLORINT]"), ], ) def test_choice_usage_rendering(runner, choices, metavar): """BY default ``--help`` prints choice's values in the usage message. But ``show_choices=False`` makes ``--help`` prints choice's METAVAR instead of values. Also check that usage error message always suggests the actual values. """ @click.command() @click.option("-g", type=click.Choice(choices)) def cli_with_choices(g): pass @click.command() @click.option("-g", type=click.Choice(choices), show_choices=False) def cli_without_choices(g): pass display_values = tuple( i.name if isinstance(i, enum.Enum) else str(i) for i in choices ) # Check that the choices values are rendered as-is in the usage message. result = runner.invoke(cli_with_choices, ["--help"]) assert f"[{'|'.join(display_values)}]" in result.stdout assert not result.stderr assert result.exit_code == 0 # Check that the metavar is rendered instead of the choices values themselves. result = runner.invoke(cli_without_choices, ["--help"]) assert metavar in result.stdout assert not result.stderr assert result.exit_code == 0 # Check the usage error message suggests the actual accepted values. for cli in (cli_with_choices, cli_without_choices): result = runner.invoke(cli, ["-g", "random"]) assert ( "\n\nError: Invalid value for '-g': 'random' is not one of " f"{', '.join(map(repr, display_values))}.\n" in result.stderr ) assert not result.stdout assert result.exit_code == 2 @pytest.mark.parametrize( ("choices", "default", "default_string"), [ (["foo", "bar"], "bar", "bar"), # The default value is not enforced to be in the choices. (["foo", "bar"], "random", "random"), # None cannot be a default value as-is: it left the default value as unset. (["foo", "bar"], None, None), ([0, 1], 0, "0"), # Values are not coerced to the type of the choice, even if equivalent. ([0, 1], 0.0, "0.0"), ([1, 2], 2, "2"), ([1.0, 2.0], 2, "2"), ([1.0, 2.0], 2.0, "2.0"), ([True, False], True, "True"), ([True, False], False, "False"), (["foo", 1], "foo", "foo"), (["foo", 1], 1, "1"), # Enum choices are rendered as their names, not values. # See: https://github.com/pallets/click/issues/2911 (HashType, HashType.SHA1, "SHA1"), # Enum choices allow defaults strings that are their names. (HashType, HashType.SHA256, "SHA256"), (HashType, "SHA256", "SHA256"), (Number, Number.TWO, "TWO"), (Number, "TWO", "TWO"), (Letter, Letter.NAME_1, "NAME_1"), (Letter, Letter.NAME_2, "NAME_2"), (Letter, Letter.NAME_3, "NAME_3"), (Letter, "NAME_1", "NAME_1"), (Letter, "NAME_2", "NAME_2"), (Letter, "NAME_3", "NAME_3"), (Color, Color.GREEN, "GREEN"), (Color, "GREEN", "GREEN"), (ColorInt, ColorInt.GREEN, "GREEN"), (ColorInt, "GREEN", "GREEN"), ], ) def test_choice_default_rendering(runner, choices, default, default_string): @click.command() @click.option("-g", type=click.Choice(choices), default=default, show_default=True) def cli_with_choices(g): pass # Check that the default value is kept normalized to the type of the choice. assert cli_with_choices.params[0].default == default result = runner.invoke(cli_with_choices, ["--help"]) extra_usage = f"[default: {default_string}]" if default_string is None: assert extra_usage not in result.output else: assert extra_usage in result.output @pytest.mark.parametrize( "opts_one,opts_two", [ # No duplicate shortnames ( ("-a", "--aardvark"), ("-a", "--avocado"), ), # No duplicate long names ( ("-a", "--aardvark"), ("-b", "--aardvark"), ), ], ) def test_duplicate_names_warning(runner, opts_one, opts_two): @click.command() @click.option(*opts_one) @click.option(*opts_two) def cli(one, two): pass with pytest.warns(UserWarning): runner.invoke(cli, []) OBJECT_SENTINEL = object() """An object-based sentinel value.""" class EnumSentinel(enum.Enum): FALSY_SENTINEL = object() def __bool__(self) -> Literal[False]: """Force the sentinel to be falsy to make sure it is not caught by Click internal implementation. Falsy sentinels have been discussed in: https://github.com/pallets/click/pull/3030#pullrequestreview-3106604795 https://github.com/pallets/click/pull/3030#pullrequestreview-3108471552 """ return False # Any kind of sentinel value is recognized by Click as a valid flag value. @pytest.mark.parametrize("sentinel", (OBJECT_SENTINEL, EnumSentinel.FALSY_SENTINEL)) @pytest.mark.parametrize( ("args", "expected"), ( # Option default to None. ([], None), # Config has no default value, and no flag value, so it requires an argument. ( ["--config"], re.compile(re.escape("Error: Option '--config' requires an argument.\n")), ), ( ["--no-config", "--config"], re.compile(re.escape("Error: Option '--config' requires an argument.\n")), ), # Passing --no-config defaults to the sentinel value because of the flag_value, # and then the custom type receives that sentinel and returns a message. (["--no-config"], "No configuration file provided."), # Passing --config with an argument returns the file path. (["--config", "foo.conf"], "foo.conf"), # An argument is not allowed for --no-config, so it raises an error. ( ["--no-config", "foo.conf"], re.compile( r"Usage: main \[OPTIONS\]\n" r"Try 'main --help' for help.\n" r"\n" r"Error: Got unexpected extra argument (.+)\n" ), ), # Passing --config with an argument that does not exist raises an error. ( ["--config", "random-file.conf"], re.compile( r"Usage: main \[OPTIONS\]\n" r"Try 'main --help' for help.\n" r"\n" r"Error: Invalid value for '-c' / '--config': " r"File 'random-file.conf' does not exist.\n" ), ), ( ["--config", "--no-config"], re.compile( r"Usage: main \[OPTIONS\]\n" r"Try 'main --help' for help.\n" r"\n" r"Error: Invalid value for '-c' / '--config': " r"File '--no-config' does not exist.\n" ), ), ( ["--config", "--no-config", "foo.conf"], re.compile( r"Usage: main \[OPTIONS\]\n" r"Try 'main --help' for help.\n" r"\n" r"Error: Invalid value for '-c' / '--config': " r"File '--no-config' does not exist.\n" ), ), # --config is passed last and overrides the --no-config option. (["--no-config", "--config", "foo.conf"], "foo.conf"), ), ) def test_dual_options_custom_type_sentinel_flag_value(runner, sentinel, args, expected): """Check that an object-based sentinel, used as a flag value, is returned as-is to a custom type that is shared by two options, competing for the same variable name. A reproduction of https://github.com/pallets/click/issues/3024#issuecomment-3146511356 """ class ConfigParamType(click.ParamType): """A custom type that accepts a file path or a sentinel value.""" def convert(self, value, param, ctx): if value is sentinel: return "No configuration file provided." else: return click.Path(exists=True, dir_okay=False).convert( value, param, ctx ) @click.command() @click.option("-c", "--config", type=ConfigParamType()) @click.option("--no-config", "config", flag_value=sentinel, type=ConfigParamType()) def main(config): click.echo(repr(config), nl=False) with tempfile.NamedTemporaryFile(mode="w") as named_tempfile: if "foo.conf" in args: named_tempfile.write("Blah blah") named_tempfile.flush() args = [named_tempfile.name if a == "foo.conf" else a for a in args] result = runner.invoke(main, args) if isinstance(expected, re.Pattern): assert re.match(expected, result.output) else: assert result.output == repr( named_tempfile.name if expected == "foo.conf" else expected ) class EngineType(enum.Enum): OSS = enum.auto() PRO = enum.auto() MAX = enum.auto() class Class1: pass class Class2: pass @pytest.mark.parametrize( ("opt_params", "args", "expected"), [ # Check that the flag value is returned as-is when the option is passed, and # not normalized to a boolean, even if it is explicitly declared as a flag. ({"type": EngineType, "flag_value": None}, ["--pro"], None), ( {"type": EngineType, "is_flag": True, "flag_value": None}, ["--pro"], None, ), ({"type": EngineType, "flag_value": EngineType.OSS}, ["--pro"], EngineType.OSS), ( {"type": EngineType, "is_flag": True, "flag_value": EngineType.OSS}, ["--pro"], EngineType.OSS, ), ( {"type": EngineType, "is_flag": True, "default": EngineType.OSS}, ["--pro"], EngineType.OSS, ), # The default value is returned as-is when the option is not passed, whatever # the flag value. ({"type": EngineType, "flag_value": None}, [], None), ({"type": EngineType, "is_flag": True, "flag_value": None}, [], None), ({"type": EngineType, "flag_value": EngineType.OSS}, [], None), ( {"type": EngineType, "is_flag": True, "flag_value": EngineType.OSS}, [], None, ), ( {"type": EngineType, "is_flag": True, "default": EngineType.OSS}, [], EngineType.OSS, ), # The option has not enough parameters to be detected as flag-like, so it # requires an argument. ( {"type": EngineType, "default": EngineType.OSS}, ["--pro"], re.compile(re.escape("Error: Option '--pro' requires an argument.\n")), ), ({"type": EngineType, "default": EngineType.OSS}, [], EngineType.OSS), # If a flag value is set, it is returned instead of the default value. ( {"type": EngineType, "flag_value": EngineType.OSS, "default": True}, ["--pro"], EngineType.OSS, ), ( {"type": EngineType, "flag_value": EngineType.OSS, "default": True}, [], EngineType.OSS, ), # Type is not specified and default to string, so the default value is # returned as a string, even if it is a boolean. Also, defaults to the # flag_value instead of the default value to support legacy behavior. ({"flag_value": "1", "default": True}, [], "1"), ({"flag_value": "1", "default": 42}, [], "42"), ({"flag_value": EngineType.OSS, "default": True}, [], "EngineType.OSS"), ({"flag_value": EngineType.OSS, "default": 42}, [], "42"), # See: the result is the same if we force the type to be str. ({"type": str, "flag_value": 1, "default": True}, [], "1"), ({"type": str, "flag_value": 1, "default": 42}, [], "42"), ({"type": str, "flag_value": "1", "default": True}, [], "1"), ({"type": str, "flag_value": "1", "default": 42}, [], "42"), ( {"type": str, "flag_value": EngineType.OSS, "default": True}, [], "EngineType.OSS", ), ({"type": str, "flag_value": EngineType.OSS, "default": 42}, [], "42"), # But having the flag value set to integer is automaticcally recognized by # Click. ({"flag_value": 1, "default": True}, [], 1), ({"flag_value": 1, "default": 42}, [], 42), ({"type": int, "flag_value": 1, "default": True}, [], 1), ({"type": int, "flag_value": 1, "default": 42}, [], 42), ({"type": int, "flag_value": "1", "default": True}, [], 1), ({"type": int, "flag_value": "1", "default": 42}, [], 42), ], ) def test_custom_type_flag_value_standalone_option(runner, opt_params, args, expected): """Test how the type and flag_value influence the returned value. Cover cases reported in: https://github.com/pallets/click/issues/3024#issuecomment-3146480714 https://github.com/pallets/click/issues/2012#issuecomment-892437060 """ @click.command() @click.option("--pro", **opt_params) def scan(pro): click.echo(repr(pro), nl=False) result = runner.invoke(scan, args) if isinstance(expected, re.Pattern): assert re.match(expected, result.output) else: assert result.output == repr(expected) @pytest.mark.parametrize( ("opt1_params", "opt2_params", "args", "expected"), [ # Dual options sharing the same variable name, are not competitive, and the # flag value is returned as-is. Especially when the type is force to be # unprocessed. ( {"flag_value": EngineType.OSS, "type": UNPROCESSED}, {"flag_value": EngineType.PRO, "type": UNPROCESSED}, [], None, ), ( {"flag_value": EngineType.OSS, "type": UNPROCESSED}, {"flag_value": EngineType.PRO, "type": UNPROCESSED}, ["--opt1"], EngineType.OSS, ), ( {"flag_value": EngineType.OSS, "type": UNPROCESSED}, {"flag_value": EngineType.PRO, "type": UNPROCESSED}, ["--opt2"], EngineType.PRO, ), # Check that passing exotic flag values like classes is supported, but are # rendered to strings when the type is not specified. ( {"flag_value": Class1, "default": True}, {"flag_value": Class2}, [], re.compile(r"''"), ), ( {"flag_value": Class1, "default": True}, {"flag_value": Class2}, ["--opt1"], "", ), ( {"flag_value": Class1, "default": True}, {"flag_value": Class2}, ["--opt2"], "", ), # Even the default is processed as a string. ({"flag_value": Class1, "default": "True"}, {"flag_value": Class2}, [], "True"), ({"flag_value": Class1, "default": None}, {"flag_value": Class2}, [], None), # To get the classes as-is, we need to specify the type as UNPROCESSED. ( {"flag_value": Class1, "type": UNPROCESSED, "default": True}, {"flag_value": Class2, "type": UNPROCESSED}, [], re.compile(r""), ), ( {"flag_value": Class1, "type": UNPROCESSED, "default": True}, {"flag_value": Class2, "type": UNPROCESSED}, ["--opt1"], Class1, ), ( {"flag_value": Class1, "type": UNPROCESSED, "default": True}, {"flag_value": Class2, "type": UNPROCESSED}, ["--opt2"], Class2, ), # Setting the default to a class, an instance of the class is returned instead # of the class itself, because the default is allowed to be callable (and # consummd). And this happens whatever the type is. ( {"flag_value": Class1, "default": Class1}, {"flag_value": Class2}, [], re.compile(r"''"), ), ( {"flag_value": Class1, "default": Class2}, {"flag_value": Class2}, [], re.compile(r"''"), ), ( {"flag_value": Class1, "type": UNPROCESSED, "default": Class1}, {"flag_value": Class2, "type": UNPROCESSED}, [], re.compile(r""), ), ( {"flag_value": Class1, "type": UNPROCESSED, "default": Class2}, {"flag_value": Class2, "type": UNPROCESSED}, [], re.compile(r""), ), # Having the flag value set to integer is automaticcally recognized by Click. ( {"flag_value": 1, "default": True}, {"flag_value": "1"}, [], 1, ), ( {"flag_value": 1, "type": int, "default": True}, {"flag_value": "1", "type": int}, [], 1, ), ], ) def test_custom_type_flag_value_dual_options( runner, opt1_params, opt2_params, args, expected ): """Test how flag values are processed with dual options competing for the same variable name. Reproduce issues reported in: https://github.com/pallets/click/issues/3024#issuecomment-3146508536 https://github.com/pallets/click/issues/2012#issue-946471049 https://github.com/pallets/click/issues/2012#issuecomment-892437060 """ @click.command() @click.option("--opt1", "dual_option", **opt1_params) @click.option("--opt2", "dual_option", **opt2_params) def cli(dual_option): click.echo(repr(dual_option), nl=False) result = runner.invoke(cli, args) if isinstance(expected, re.Pattern): assert re.match(expected, result.output) else: assert result.output == repr(expected) def test_custom_type_frozenset_flag_value(runner): """Check that frozenset is correctly handled as a type, a flag value and a default. Reproduces https://github.com/pallets/click/issues/2610 """ @click.command() @click.option( "--without-scm-ignore-files", "scm_ignore_files", is_flag=True, type=frozenset, flag_value=frozenset(), default=frozenset(["git"]), ) def rcli(scm_ignore_files): click.echo(repr(scm_ignore_files), nl=False) result = runner.invoke(rcli) assert result.stdout == "frozenset({'git'})" assert result.exit_code == 0 result = runner.invoke(rcli, ["--without-scm-ignore-files"]) assert result.stdout == "frozenset()" assert result.exit_code == 0 asyncclick-8.3.0.5-async/tests/test_parser.py000066400000000000000000000016531507140761400212040ustar00rootroot00000000000000import pytest import asyncclick as click from asyncclick.parser import _OptionParser from asyncclick.shell_completion import split_arg_string @pytest.mark.parametrize( ("value", "expect"), [ ("cli a b c", ["cli", "a", "b", "c"]), ("cli 'my file", ["cli", "my file"]), ("cli 'my file'", ["cli", "my file"]), ("cli my\\", ["cli", "my"]), ("cli my\\ file", ["cli", "my file"]), ], ) def test_split_arg_string(value, expect): assert split_arg_string(value) == expect def test_parser_default_prefixes(): parser = _OptionParser() assert parser._opt_prefixes == {"-", "--"} def test_parser_collects_prefixes(): ctx = click.Context(click.Command("test")) parser = _OptionParser(ctx) click.Option("+p", is_flag=True).add_to_parser(parser, ctx) click.Option("!e", is_flag=True).add_to_parser(parser, ctx) assert parser._opt_prefixes == {"-", "--", "+", "!"} asyncclick-8.3.0.5-async/tests/test_shell_completion.py000066400000000000000000000452761507140761400232610ustar00rootroot00000000000000import textwrap import warnings from collections.abc import Mapping import pytest import asyncclick as click import asyncclick.shell_completion from asyncclick.core import Argument from asyncclick.core import Command from asyncclick.core import Group from asyncclick.core import Option from asyncclick.shell_completion import add_completion_class from asyncclick.shell_completion import CompletionItem from asyncclick.shell_completion import ShellComplete from asyncclick.types import Choice from asyncclick.types import File from asyncclick.types import Path async def _get_completions(cli, args, incomplete): comp = ShellComplete(cli, {}, cli.name, "_CLICK_COMPLETE") return await comp.get_completions(args, incomplete) async def _get_words(cli, args, incomplete): return [c.value for c in await _get_completions(cli, args, incomplete)] @pytest.mark.anyio async def test_command(): cli = Command("cli", params=[Option(["-t", "--test"])]) assert await _get_words(cli, [], "") == [] assert await _get_words(cli, [], "-") == ["-t", "--test", "--help"] assert await _get_words(cli, [], "--") == ["--test", "--help"] assert await _get_words(cli, [], "--t") == ["--test"] # -t has been seen, so --test isn't suggested assert await _get_words(cli, ["-t", "a"], "-") == ["--help"] @pytest.mark.anyio async def test_group(): cli = Group("cli", params=[Option(["-a"])], commands=[Command("x"), Command("y")]) assert await _get_words(cli, [], "") == ["x", "y"] assert await _get_words(cli, [], "-") == ["-a", "--help"] @pytest.mark.parametrize( ("args", "word", "expect"), [ ([], "", ["get"]), (["get"], "", ["full"]), (["get", "full"], "", ["data"]), (["get", "full"], "-", ["--verbose", "--help"]), (["get", "full", "data"], "", []), (["get", "full", "data"], "-", ["-a", "--help"]), ], ) @pytest.mark.anyio async def test_nested_group(args: list[str], word: str, expect: list[str]) -> None: cli = Group( "cli", commands=[ Group( "get", commands=[ Group( "full", params=[Option(["--verbose"])], commands=[Command("data", params=[Option(["-a"])])], ) ], ) ], ) assert await _get_words(cli, args, word) == expect @pytest.mark.anyio async def test_group_command_same_option(): cli = Group( "cli", params=[Option(["-a"])], commands=[Command("x", params=[Option(["-a"])])] ) assert await _get_words(cli, [], "-") == ["-a", "--help"] assert await _get_words(cli, ["-a", "a"], "-") == ["--help"] assert await _get_words(cli, ["-a", "a", "x"], "-") == ["-a", "--help"] assert await _get_words(cli, ["-a", "a", "x", "-a", "a"], "-") == ["--help"] @pytest.mark.anyio async def test_chained(): cli = Group( "cli", chain=True, commands=[ Command("set", params=[Option(["-y"])]), Command("start"), Group("get", commands=[Command("full")]), ], ) assert await _get_words(cli, [], "") == ["get", "set", "start"] assert await _get_words(cli, [], "s") == ["set", "start"] assert await _get_words(cli, ["set", "start"], "") == ["get"] # subcommands and parent subcommands assert await _get_words(cli, ["get"], "") == ["full", "set", "start"] assert await _get_words(cli, ["get", "full"], "") == ["set", "start"] assert await _get_words(cli, ["get"], "s") == ["set", "start"] @pytest.mark.anyio async def test_help_option(): cli = Group("cli", commands=[Command("with"), Command("no", add_help_option=False)]) assert await _get_words(cli, ["with"], "--") == ["--help"] assert await _get_words(cli, ["no"], "--") == [] @pytest.mark.anyio async def test_argument_order(): cli = Command( "cli", params=[ Argument(["plain"]), Argument(["c1"], type=Choice(["a1", "a2", "b"])), Argument(["c2"], type=Choice(["c1", "c2", "d"])), ], ) # first argument has no completions assert await _get_words(cli, [], "") == [] assert await _get_words(cli, [], "a") == [] # first argument filled, now completion can happen assert await _get_words(cli, ["x"], "a") == ["a1", "a2"] assert await _get_words(cli, ["x", "b"], "d") == ["d"] @pytest.mark.anyio async def test_argument_default(): cli = Command( "cli", add_help_option=False, params=[ Argument(["a"], type=Choice(["a"]), default="a"), Argument(["b"], type=Choice(["b"]), default="b"), ], ) assert await _get_words(cli, [], "") == ["a"] assert await _get_words(cli, ["a"], "b") == ["b"] # ignore type validation assert await _get_words(cli, ["x"], "b") == ["b"] @pytest.mark.anyio async def test_type_choice(): cli = Command("cli", params=[Option(["-c"], type=Choice(["a1", "a2", "b"]))]) assert await _get_words(cli, ["-c"], "") == ["a1", "a2", "b"] assert await _get_words(cli, ["-c"], "a") == ["a1", "a2"] assert await _get_words(cli, ["-c"], "a2") == ["a2"] @pytest.mark.anyio async def test_choice_special_characters(): cli = Command("cli", params=[Option(["-c"], type=Choice(["!1", "!2", "+3"]))]) assert await _get_words(cli, ["-c"], "") == ["!1", "!2", "+3"] assert await _get_words(cli, ["-c"], "!") == ["!1", "!2"] assert await _get_words(cli, ["-c"], "!2") == ["!2"] @pytest.mark.anyio async def test_choice_conflicting_prefix(): cli = Command( "cli", params=[ Option(["-c"], type=Choice(["!1", "!2", "+3"])), Option(["+p"], is_flag=True), ], ) assert await _get_words(cli, ["-c"], "") == ["!1", "!2", "+3"] assert await _get_words(cli, ["-c"], "+") == ["+p"] @pytest.mark.anyio async def test_option_count(): cli = Command("cli", params=[Option(["-c"], count=True)]) assert await _get_words(cli, ["-c"], "") == [] assert await _get_words(cli, ["-c"], "-") == ["--help"] @pytest.mark.anyio async def test_option_optional(): cli = Command( "cli", add_help_option=False, params=[ Option(["--name"], is_flag=False, flag_value="value"), Option(["--flag"], is_flag=True), ], ) assert await _get_words(cli, ["--name"], "") == [] assert await _get_words(cli, ["--name"], "-") == ["--flag"] assert await _get_words(cli, ["--name", "--flag"], "-") == [] @pytest.mark.parametrize( ("type", "expect"), [(File(), "file"), (Path(), "file"), (Path(file_okay=False), "dir")], ) @pytest.mark.anyio async def test_path_types(type, expect): cli = Command("cli", params=[Option(["-f"], type=type)]) out = await _get_completions(cli, ["-f"], "ab") assert len(out) == 1 c = out[0] assert c.value == "ab" assert c.type == expect @pytest.mark.anyio async def test_absolute_path(): cli = Command("cli", params=[Option(["-f"], type=Path())]) out = await _get_completions(cli, ["-f"], "/ab") assert len(out) == 1 c = out[0] assert c.value == "/ab" @pytest.mark.anyio async def test_option_flag(): cli = Command( "cli", add_help_option=False, params=[ Option(["--on/--off"]), Argument(["a"], type=Choice(["a1", "a2", "b"])), ], ) assert await _get_words(cli, [], "--") == ["--on", "--off"] # flag option doesn't take value, use choice argument assert await _get_words(cli, ["--on"], "a") == ["a1", "a2"] @pytest.mark.anyio async def test_flag_option_with_nargs_option(): cli = Command( "cli", add_help_option=False, params=[ Argument(["a"], type=Choice(["a1", "a2", "b"])), Option(["--flag"], is_flag=True), Option(["-c"], type=Choice(["p", "q"]), nargs=2), ], ) assert await _get_words(cli, ["a1", "--flag", "-c"], "") == ["p", "q"] @pytest.mark.anyio async def test_option_custom(): def custom(ctx, param, incomplete): return [incomplete.upper()] cli = Command( "cli", params=[ Argument(["x"]), Argument(["y"]), Argument(["z"], shell_complete=custom), ], ) assert await _get_words(cli, ["a", "b"], "") == [""] assert await _get_words(cli, ["a", "b"], "c") == ["C"] @pytest.mark.anyio async def test_option_multiple(): cli = Command( "type", params=[Option(["-m"], type=Choice(["a", "b"]), multiple=True), Option(["-f"])], ) assert await _get_words(cli, ["-m"], "") == ["a", "b"] assert "-m" in await _get_words(cli, ["-m", "a"], "-") assert await _get_words(cli, ["-m", "a", "-m"], "") == ["a", "b"] # used single options aren't suggested again assert "-c" not in await _get_words(cli, ["-c", "f"], "-") @pytest.mark.anyio async def test_option_nargs(): cli = Command("cli", params=[Option(["-c"], type=Choice(["a", "b"]), nargs=2)]) assert await _get_words(cli, ["-c"], "") == ["a", "b"] assert await _get_words(cli, ["-c", "a"], "") == ["a", "b"] assert await _get_words(cli, ["-c", "a", "b"], "") == [] @pytest.mark.anyio async def test_argument_nargs(): cli = Command( "cli", params=[ Argument(["x"], type=Choice(["a", "b"]), nargs=2), Argument(["y"], type=Choice(["c", "d"]), nargs=-1), Option(["-z"]), ], ) assert await _get_words(cli, [], "") == ["a", "b"] assert await _get_words(cli, ["a"], "") == ["a", "b"] assert await _get_words(cli, ["a", "b"], "") == ["c", "d"] assert await _get_words(cli, ["a", "b", "c"], "") == ["c", "d"] assert await _get_words(cli, ["a", "b", "c", "d"], "") == ["c", "d"] assert await _get_words(cli, ["a", "-z", "1"], "") == ["a", "b"] assert await _get_words(cli, ["a", "-z", "1", "b"], "") == ["c", "d"] @pytest.mark.anyio async def test_double_dash(): cli = Command( "cli", add_help_option=False, params=[ Option(["--opt"]), Argument(["name"], type=Choice(["name", "--", "-o", "--opt"])), ], ) assert await _get_words(cli, [], "-") == ["--opt"] assert await _get_words(cli, ["value"], "-") == ["--opt"] assert await _get_words(cli, [], "") == ["name", "--", "-o", "--opt"] assert await _get_words(cli, ["--"], "") == ["name", "--", "-o", "--opt"] @pytest.mark.anyio async def test_hidden(): cli = Group( "cli", commands=[ Command( "hidden", add_help_option=False, hidden=True, params=[ Option(["-a"]), Option(["-b"], type=Choice(["a", "b"]), hidden=True), ], ) ], ) assert "hidden" not in await _get_words(cli, [], "") assert "hidden" not in await _get_words(cli, [], "hidden") assert await _get_words(cli, ["hidden"], "-") == ["-a"] assert await _get_words(cli, ["hidden", "-b"], "") == ["a", "b"] @pytest.mark.anyio async def test_add_different_name(): cli = Group("cli", commands={"renamed": Command("original")}) words = await _get_words(cli, [], "") assert "renamed" in words assert "original" not in words def test_completion_item_data(): c = CompletionItem("test", a=1) assert c.a == 1 assert c.b is None @pytest.fixture() def _patch_for_completion(monkeypatch): monkeypatch.setattr( "asyncclick.shell_completion.BashComplete._check_version", lambda self: True ) @pytest.mark.parametrize("shell", ["bash", "zsh", "fish"]) @pytest.mark.usefixtures("_patch_for_completion") def test_full_source(runner, shell): cli = Group("cli", commands=[Command("a"), Command("b")]) result = runner.invoke(cli, env={"_CLI_COMPLETE": f"{shell}_source"}) assert f"_CLI_COMPLETE={shell}_complete" in result.output @pytest.mark.parametrize( ("shell", "env", "expect"), [ ("bash", {"COMP_WORDS": "", "COMP_CWORD": "0"}, "plain,a\nplain,b\n"), ("bash", {"COMP_WORDS": "a b", "COMP_CWORD": "1"}, "plain,b\n"), ("zsh", {"COMP_WORDS": "", "COMP_CWORD": "0"}, "plain\na\n_\nplain\nb\nbee\n"), ("zsh", {"COMP_WORDS": "a b", "COMP_CWORD": "1"}, "plain\nb\nbee\n"), ("fish", {"COMP_WORDS": "", "COMP_CWORD": ""}, "plain,a\nplain,b\tbee\n"), ("fish", {"COMP_WORDS": "a b", "COMP_CWORD": "b"}, "plain,b\tbee\n"), ("fish", {"COMP_WORDS": 'a "b', "COMP_CWORD": '"b'}, "plain,b\tbee\n"), ], ) @pytest.mark.usefixtures("_patch_for_completion") def test_full_complete(runner, shell, env, expect): cli = Group("cli", commands=[Command("a"), Command("b", help="bee")]) env["_CLI_COMPLETE"] = f"{shell}_complete" result = runner.invoke(cli, env=env) assert result.output == expect @pytest.mark.parametrize( ("env", "expect"), [ ( {"COMP_WORDS": "", "COMP_CWORD": "0"}, textwrap.dedent( """\ plain a _ plain b bee plain c\\:d cee:dee plain c:e _ """ ), ), ( {"COMP_WORDS": "a c", "COMP_CWORD": "1"}, textwrap.dedent( """\ plain c\\:d cee:dee plain c:e _ """ ), ), ( {"COMP_WORDS": "a c:", "COMP_CWORD": "1"}, textwrap.dedent( """\ plain c\\:d cee:dee plain c:e _ """ ), ), ], ) @pytest.mark.usefixtures("_patch_for_completion") def test_zsh_full_complete_with_colons( runner, env: Mapping[str, str], expect: str ) -> None: cli = Group( "cli", commands=[ Command("a"), Command("b", help="bee"), Command("c:d", help="cee:dee"), Command("c:e"), ], ) result = runner.invoke( cli, env={ **env, "_CLI_COMPLETE": "zsh_complete", }, ) assert result.output == expect @pytest.mark.usefixtures("_patch_for_completion") def test_context_settings(runner): def complete(ctx, param, incomplete): return ctx.obj["choices"] cli = Command("cli", params=[Argument("x", shell_complete=complete)]) result = runner.invoke( cli, obj={"choices": ["a", "b"]}, env={"COMP_WORDS": "", "COMP_CWORD": "0", "_CLI_COMPLETE": "bash_complete"}, ) assert result.output == "plain,a\nplain,b\n" @pytest.mark.parametrize(("value", "expect"), [(False, ["Au", "al"]), (True, ["al"])]) @pytest.mark.anyio async def test_choice_case_sensitive(value, expect): cli = Command( "cli", params=[Option(["-a"], type=Choice(["Au", "al", "Bc"], case_sensitive=value))], ) completions = await _get_words(cli, ["-a"], "a") assert completions == expect @pytest.fixture() def _restore_available_shells(tmpdir): prev_available_shells = click.shell_completion._available_shells.copy() click.shell_completion._available_shells.clear() yield click.shell_completion._available_shells.clear() click.shell_completion._available_shells.update(prev_available_shells) @pytest.mark.usefixtures("_restore_available_shells") def test_add_completion_class(): # At first, "mysh" is not in available shells assert "mysh" not in click.shell_completion._available_shells class MyshComplete(ShellComplete): name = "mysh" source_template = "dummy source" # "mysh" still not in available shells because it is not registered assert "mysh" not in click.shell_completion._available_shells # Adding a completion class should return that class assert add_completion_class(MyshComplete) is MyshComplete # Now, "mysh" is finally in available shells assert "mysh" in click.shell_completion._available_shells assert click.shell_completion._available_shells["mysh"] is MyshComplete @pytest.mark.usefixtures("_restore_available_shells") def test_add_completion_class_with_name(): # At first, "mysh" is not in available shells assert "mysh" not in click.shell_completion._available_shells assert "not_mysh" not in click.shell_completion._available_shells class MyshComplete(ShellComplete): name = "not_mysh" source_template = "dummy source" # "mysh" and "not_mysh" are still not in available shells because # it is not registered yet assert "mysh" not in click.shell_completion._available_shells assert "not_mysh" not in click.shell_completion._available_shells # Adding a completion class should return that class. # Because we are using the "name" parameter, the name isn't taken # from the class. assert add_completion_class(MyshComplete, name="mysh") is MyshComplete # Now, "mysh" is finally in available shells assert "mysh" in click.shell_completion._available_shells assert "not_mysh" not in click.shell_completion._available_shells assert click.shell_completion._available_shells["mysh"] is MyshComplete @pytest.mark.usefixtures("_restore_available_shells") def test_add_completion_class_decorator(): # At first, "mysh" is not in available shells assert "mysh" not in click.shell_completion._available_shells @add_completion_class class MyshComplete(ShellComplete): name = "mysh" source_template = "dummy source" # Using `add_completion_class` as a decorator adds the new shell immediately assert "mysh" in click.shell_completion._available_shells assert click.shell_completion._available_shells["mysh"] is MyshComplete # Don't make the ResourceWarning give an error @pytest.mark.filterwarnings("default") @pytest.mark.anyio async def test_files_closed(runner) -> None: with runner.isolated_filesystem(): config_file = "foo.txt" with open(config_file, "w") as f: f.write("bar") @click.group() @click.option( "--config-file", default=config_file, type=click.File(mode="r"), ) @click.pass_context def cli(ctx, config_file): pass with warnings.catch_warnings(record=True) as current_warnings: assert not current_warnings, "There should be no warnings to start" await _get_completions(cli, args=[], incomplete="") assert not current_warnings, "There should be no warnings after either" asyncclick-8.3.0.5-async/tests/test_termui.py000066400000000000000000000617561507140761400212270ustar00rootroot00000000000000import platform import tempfile import time import pytest import asyncclick as click import asyncclick._termui_impl from asyncclick._compat import WIN from asyncclick.exceptions import BadParameter from asyncclick.exceptions import MissingParameter class FakeClock: def __init__(self): self.now = time.time() def advance_time(self, seconds=1): self.now += seconds def time(self): return self.now def _create_progress(length=10, **kwargs): progress = click.progressbar(tuple(range(length))) for key, value in kwargs.items(): setattr(progress, key, value) return progress def test_progressbar_strip_regression(runner, monkeypatch): label = " padded line" @click.command() def cli(): with _create_progress(label=label) as progress: for _ in progress: pass monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True) assert ( label in runner.invoke(cli, [], standalone_mode=False, catch_exceptions=False).output ) def test_progressbar_length_hint(runner, monkeypatch): class Hinted: def __init__(self, n): self.items = list(range(n)) def __length_hint__(self): return len(self.items) def __iter__(self): return self def __next__(self): if self.items: return self.items.pop() else: raise StopIteration next = __next__ @click.command() def cli(): with click.progressbar(Hinted(10), label="test") as progress: for _ in progress: pass monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True) result = runner.invoke(cli, []) assert result.exception is None def test_progressbar_no_tty(runner, monkeypatch): @click.command() def cli(): with _create_progress(label="working") as progress: for _ in progress: pass monkeypatch.setattr(click._termui_impl, "isatty", lambda _: False) assert runner.invoke(cli, []).output == "working\n" def test_progressbar_hidden_manual(runner, monkeypatch): @click.command() def cli(): with _create_progress(label="see nothing", hidden=True) as progress: for _ in progress: pass monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True) assert runner.invoke(cli, []).output == "" @pytest.mark.parametrize("avg, expected", [([], 0.0), ([1, 4], 2.5)]) def test_progressbar_time_per_iteration(runner, avg, expected): with _create_progress(2, avg=avg) as progress: assert progress.time_per_iteration == expected @pytest.mark.parametrize("finished, expected", [(False, 5), (True, 0)]) def test_progressbar_eta(runner, finished, expected): with _create_progress(2, finished=finished, avg=[1, 4]) as progress: assert progress.eta == expected @pytest.mark.parametrize( "eta, expected", [ (0, "00:00:00"), (30, "00:00:30"), (90, "00:01:30"), (900, "00:15:00"), (9000, "02:30:00"), (99999999999, "1157407d 09:46:39"), (None, ""), ], ) def test_progressbar_format_eta(runner, eta, expected): with _create_progress(1, eta_known=eta is not None, avg=[eta]) as progress: assert progress.format_eta() == expected @pytest.mark.parametrize("pos, length", [(0, 5), (-1, 1), (5, 5), (6, 5), (4, 0)]) def test_progressbar_format_pos(runner, pos, length): with _create_progress(length, pos=pos) as progress: result = progress.format_pos() assert result == f"{pos}/{length}" @pytest.mark.parametrize( "length, finished, pos, avg, expected", [ (8, False, 7, 0, "#######-"), (0, True, 8, 0, "########"), ], ) def test_progressbar_format_bar(runner, length, finished, pos, avg, expected): with _create_progress( length, width=8, pos=pos, finished=finished, avg=[avg] ) as progress: assert progress.format_bar() == expected @pytest.mark.parametrize( "length, show_percent, show_pos, pos, expected", [ (0, True, True, 0, " [--------] 0/0 0%"), (0, False, True, 0, " [--------] 0/0"), (0, False, False, 0, " [--------]"), (0, False, False, 0, " [--------]"), (8, True, True, 8, " [########] 8/8 100%"), ], ) def test_progressbar_format_progress_line( runner, length, show_percent, show_pos, pos, expected ): with _create_progress( length, width=8, show_percent=show_percent, pos=pos, show_pos=show_pos, ) as progress: assert progress.format_progress_line() == expected @pytest.mark.parametrize("test_item", ["test", None]) def test_progressbar_format_progress_line_with_show_func(runner, test_item): def item_show_func(item): return item with _create_progress( item_show_func=item_show_func, current_item=test_item ) as progress: if test_item: assert progress.format_progress_line().endswith(test_item) else: assert progress.format_progress_line().endswith(progress.format_pct()) def test_progressbar_init_exceptions(runner): with pytest.raises(TypeError, match="iterable or length is required"): click.progressbar() def test_progressbar_iter_outside_with_exceptions(runner): progress = click.progressbar(length=2) with pytest.raises(RuntimeError, match="with block"): iter(progress) def test_progressbar_is_iterator(runner, monkeypatch): @click.command() def cli(): with click.progressbar(range(10), label="test") as progress: while True: try: next(progress) except StopIteration: break monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True) result = runner.invoke(cli, []) assert result.exception is None def test_choices_list_in_prompt(runner, monkeypatch): @click.command() @click.option( "-g", type=click.Choice(["none", "day", "week", "month"]), prompt=True ) def cli_with_choices(g): pass @click.command() @click.option( "-g", type=click.Choice(["none", "day", "week", "month"]), prompt=True, show_choices=False, ) def cli_without_choices(g): pass result = runner.invoke(cli_with_choices, [], input="none") assert "(none, day, week, month)" in result.output result = runner.invoke(cli_without_choices, [], input="none") assert "(none, day, week, month)" not in result.output @pytest.mark.parametrize( "file_kwargs", [{"mode": "rt"}, {"mode": "rb"}, {"lazy": True}] ) def test_file_prompt_default_format(runner, file_kwargs): @click.command() @click.option("-f", default=__file__, prompt="file", type=click.File(**file_kwargs)) def cli(f): click.echo(f.name) result = runner.invoke(cli, input="\n") assert result.output == f"file [{__file__}]: \n{__file__}\n" def test_secho(runner): with runner.isolation() as outstreams: click.secho(None, nl=False) bytes = outstreams[0].getvalue() assert bytes == b"" @pytest.mark.skipif(platform.system() == "Windows", reason="No style on Windows.") @pytest.mark.parametrize( ("value", "expect"), [(123, b"\x1b[45m123\x1b[0m"), (b"test", b"test")] ) def test_secho_non_text(runner, value, expect): with runner.isolation() as (out, _, _): click.secho(value, nl=False, color=True, bg="magenta") result = out.getvalue() assert result == expect def test_progressbar_yields_all_items(runner): with click.progressbar(range(3)) as progress: assert len(list(progress)) == 3 def test_progressbar_update(runner, monkeypatch): fake_clock = FakeClock() @click.command() def cli(): with click.progressbar(range(4)) as progress: for _ in progress: fake_clock.advance_time() print("") monkeypatch.setattr(time, "time", fake_clock.time) monkeypatch.setattr(asyncclick._termui_impl, "isatty", lambda _: True) output = runner.invoke(cli, []).output lines = [line for line in output.split("\n") if "[" in line] assert " 0%" in lines[0] assert " 25% 00:00:03" in lines[1] assert " 50% 00:00:02" in lines[2] assert " 75% 00:00:01" in lines[3] assert "100% " in lines[4] def test_progressbar_item_show_func(runner, monkeypatch): """item_show_func should show the current item being yielded.""" @click.command() def cli(): with click.progressbar(range(3), item_show_func=lambda x: str(x)) as progress: for item in progress: click.echo(f" item {item}") monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True) lines = runner.invoke(cli).output.splitlines() for i, line in enumerate(x for x in lines if "item" in x): assert f"{i} item {i}" in line def test_progressbar_update_with_item_show_func(runner, monkeypatch): @click.command() def cli(): with click.progressbar( length=6, item_show_func=lambda x: f"Custom {x}" ) as progress: while not progress.finished: progress.update(2, progress.pos) click.echo() monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True) output = runner.invoke(cli, []).output lines = [line for line in output.split("\n") if "[" in line] assert "Custom 0" in lines[0] assert "Custom 2" in lines[1] assert "Custom 4" in lines[2] def test_progress_bar_update_min_steps(runner): bar = _create_progress(update_min_steps=5) bar.update(3) assert bar._completed_intervals == 3 assert bar.pos == 0 bar.update(2) assert bar._completed_intervals == 0 assert bar.pos == 5 @pytest.mark.parametrize("key_char", ("h", "H", "é", "À", " ", "字", "àH", "àR")) @pytest.mark.parametrize("echo", [True, False]) @pytest.mark.skipif(not WIN, reason="Tests user-input using the msvcrt module.") def test_getchar_windows(runner, monkeypatch, key_char, echo): monkeypatch.setattr(asyncclick._termui_impl.msvcrt, "getwche", lambda: key_char) monkeypatch.setattr(asyncclick._termui_impl.msvcrt, "getwch", lambda: key_char) monkeypatch.setattr(click.termui, "_getchar", None) assert click.getchar(echo) == key_char @pytest.mark.parametrize( "special_key_char, key_char", [("\x00", "a"), ("\x00", "b"), ("\xe0", "c")] ) @pytest.mark.skipif( not WIN, reason="Tests special character inputs using the msvcrt module." ) def test_getchar_special_key_windows(runner, monkeypatch, special_key_char, key_char): ordered_inputs = [key_char, special_key_char] monkeypatch.setattr( asyncclick._termui_impl.msvcrt, "getwch", lambda: ordered_inputs.pop() ) monkeypatch.setattr(click.termui, "_getchar", None) assert click.getchar() == f"{special_key_char}{key_char}" @pytest.mark.parametrize( ("key_char", "exc"), [("\x03", KeyboardInterrupt), ("\x1a", EOFError)] ) @pytest.mark.skipif(not WIN, reason="Tests user-input using the msvcrt module.") def test_getchar_windows_exceptions(runner, monkeypatch, key_char, exc): monkeypatch.setattr(asyncclick._termui_impl.msvcrt, "getwch", lambda: key_char) monkeypatch.setattr(click.termui, "_getchar", None) with pytest.raises(exc): click.getchar() @pytest.mark.skipif(platform.system() == "Windows", reason="No sed on Windows.") def test_fast_edit(runner): result = click.edit("a\nb", editor="sed -i~ 's/$/Test/'") assert result == "aTest\nbTest\n" @pytest.mark.skipif(platform.system() == "Windows", reason="No sed on Windows.") def test_edit(runner): with tempfile.NamedTemporaryFile(mode="w") as named_tempfile: named_tempfile.write("a\nb") named_tempfile.flush() result = click.edit(filename=named_tempfile.name, editor="sed -i~ 's/$/Test/'") assert result is None # We need ot reopen the file as it becomes unreadable after the edit. with open(named_tempfile.name) as reopened_file: assert reopened_file.read() == "aTest\nbTest" @pytest.mark.parametrize( ("prompt_required", "required", "args", "expect"), [ (True, False, None, "prompt"), (True, False, ["-v"], "Option '-v' requires an argument."), (False, True, None, "prompt"), (False, True, ["-v"], "prompt"), ], ) def test_prompt_required_with_required(runner, prompt_required, required, args, expect): @click.command() @click.option("-v", prompt=True, prompt_required=prompt_required, required=required) def cli(v): click.echo(str(v)) result = runner.invoke(cli, args, input="prompt") assert expect in result.output @pytest.mark.parametrize( ("args", "expect"), [ # Flag not passed, don't prompt. pytest.param(None, None, id="no flag"), # Flag and value passed, don't prompt. pytest.param(["-v", "value"], "value", id="short sep value"), pytest.param(["--value", "value"], "value", id="long sep value"), pytest.param(["-vvalue"], "value", id="short join value"), pytest.param(["--value=value"], "value", id="long join value"), # Flag without value passed, prompt. pytest.param(["-v"], "prompt", id="short no value"), pytest.param(["--value"], "prompt", id="long no value"), # Don't use next option flag as value. pytest.param(["-v", "-o", "42"], ("prompt", "42"), id="no value opt"), ], ) def test_prompt_required_false(runner, args, expect): @click.command() @click.option("-v", "--value", prompt=True, prompt_required=False) @click.option("-o") def cli(value, o): if o is not None: return value, o return value result = runner.invoke(cli, args=args, input="prompt", standalone_mode=False) assert result.exception is None assert result.return_value == expect @pytest.mark.parametrize( ("prompt", "input", "default", "expect"), [ (True, "password\npassword", None, "password"), ("Confirm Password", "password\npassword\n", None, "password"), (True, "\n\n", "", ""), (False, None, None, None), ], ) def test_confirmation_prompt(runner, prompt, input, default, expect): @click.command() @click.option( "--password", prompt=prompt, hide_input=True, default=default, confirmation_prompt=prompt, ) def cli(password): return password result = runner.invoke(cli, input=input, standalone_mode=False) assert result.exception is None assert result.return_value == expect if prompt == "Confirm Password": assert "Confirm Password: " in result.output def test_false_show_default_cause_no_default_display_in_prompt(runner): @click.command() @click.option("--arg1", show_default=False, prompt=True, default="my-default-value") def cmd(arg1): pass # Confirm that the default value is not included in the output when `show_default` # is False result = runner.invoke(cmd, input="my-input", standalone_mode=False) assert "my-default-value" not in result.output REPEAT = object() """Sentinel value to indicate that the prompt is expected to be repeated. I.e. the value provided by the user is not satisfactory and need to be re-prompted. """ INVALID = object() """Sentinel value to indicate that the prompt is expected to be invalid. On invalid input, Click will output an error message and re-prompt the user. """ BOOLEAN_FLAG_PROMPT_CASES = [ ### ### Test cases with prompt=True explicitly enabled for the flag. ### # Prompt is allowed and the flag has no default, so it prompts. ({"prompt": True}, [], "[y/N]", "y", True), ({"prompt": True}, [], "[y/N]", "n", False), # Empty input default to False. ({"prompt": True}, [], "[y/N]", "", False), # Changing the default to True, makes the prompt change to [Y/n]. ({"prompt": True, "default": True}, [], "[Y/n]", "", True), ({"prompt": True, "default": True}, [], "[Y/n]", "y", True), ({"prompt": True, "default": True}, [], "[Y/n]", "n", False), # False is the default's default, so it prompts with [y/N]. ({"prompt": True, "default": False}, [], "[y/N]", "", False), ({"prompt": True, "default": False}, [], "[y/N]", "y", True), ({"prompt": True, "default": False}, [], "[y/N]", "n", False), # Defaulting to None, prompts with [y/n], which makes the user explicitly choose # between True or False. ({"prompt": True, "default": None}, [], "[y/n]", "y", True), ({"prompt": True, "default": None}, [], "[y/n]", "n", False), # Random string default is treated as a truthy value, so it prompts with [Y/n]. ({"prompt": True, "default": "foo"}, [], "[Y/n]", "", True), ({"prompt": True, "default": "foo"}, [], "[Y/n]", "y", True), ({"prompt": True, "default": "foo"}, [], "[Y/n]", "n", False), ### ### Test cases with required=True explicitly enabled for the flag. ### # A required flag just raises an error unless a default is set. ({"required": True}, [], None, None, MissingParameter), ({"required": True, "default": True}, [], None, None, True), ({"required": True, "default": False}, [], None, None, False), ({"required": True, "default": None}, [], None, None, None), ({"required": True, "default": "on"}, [], None, None, True), ({"required": True, "default": "off"}, [], None, None, False), ({"required": True, "default": "foo"}, [], None, None, BadParameter), ### ### Explicitly passing the flag to the CLI bypass any prompt, whatever the ### configuration of the flag. ### # Flag allowing a prompt. ({"prompt": True}, ["--flag"], None, None, True), ({"prompt": True}, ["--no-flag"], None, None, False), ({"prompt": True, "default": None}, ["--flag"], None, None, True), ({"prompt": True, "default": None}, ["--no-flag"], None, None, False), ({"prompt": True, "default": True}, ["--flag"], None, None, True), ({"prompt": True, "default": True}, ["--no-flag"], None, None, False), ({"prompt": True, "default": False}, ["--flag"], None, None, True), ({"prompt": True, "default": False}, ["--no-flag"], None, None, False), ({"prompt": True, "default": "foo"}, ["--flag"], None, None, True), ({"prompt": True, "default": "foo"}, ["--no-flag"], None, None, False), # Required flag. ({"required": True}, ["--flag"], None, None, True), ({"required": True}, ["--no-flag"], None, None, False), ({"required": True, "default": None}, ["--flag"], None, None, True), ({"required": True, "default": None}, ["--no-flag"], None, None, False), ({"required": True, "default": True}, ["--flag"], None, None, True), ({"required": True, "default": True}, ["--no-flag"], None, None, False), ({"required": True, "default": False}, ["--flag"], None, None, True), ({"required": True, "default": False}, ["--no-flag"], None, None, False), ({"required": True, "default": "foo"}, ["--flag"], None, None, True), ({"required": True, "default": "foo"}, ["--no-flag"], None, None, False), ] FLAG_VALUE_PROMPT_CASES = [ ### ### Test cases with prompt=True explicitly enabled for the flag. ### # Prompt is allowed and the flag has no default, so it prompts. # But the flag_value is not set, so it defaults to a string. ({"prompt": True}, [], "", "", REPEAT), ({"prompt": True}, [], "", "y", "y"), ({"prompt": True}, [], "", "n", "n"), ({"prompt": True}, [], "", "foo", "foo"), # This time we provide a boolean flag_value, which makes the flag behave like a # boolean flag, and use the appropriate variation of [y/n]. ({"prompt": True, "flag_value": True}, [], "[y/N]", "", False), ({"prompt": True, "flag_value": True}, [], "[y/N]", "y", True), ({"prompt": True, "flag_value": True}, [], "[y/N]", "n", False), ({"prompt": True, "flag_value": False}, [], "[y/N]", "", False), ({"prompt": True, "flag_value": False}, [], "[y/N]", "y", True), ({"prompt": True, "flag_value": False}, [], "[y/N]", "n", False), # Other flag values changes the auto-detection of the flag type. ({"prompt": True, "flag_value": None}, [], "", "", REPEAT), ({"prompt": True, "flag_value": None}, [], "", "y", "y"), ({"prompt": True, "flag_value": None}, [], "", "n", "n"), ({"prompt": True, "flag_value": "foo"}, [], "", "", REPEAT), ({"prompt": True, "flag_value": "foo"}, [], "", "y", "y"), ({"prompt": True, "flag_value": "foo"}, [], "", "n", "n"), ### ### Test cases with a flag_value and a default. ### # default=True ({"prompt": True, "default": True, "flag_value": True}, [], "[Y/n]", "", True), ({"prompt": True, "default": True, "flag_value": True}, [], "[Y/n]", "y", True), ({"prompt": True, "default": True, "flag_value": True}, [], "[Y/n]", "n", False), ({"prompt": True, "default": True, "flag_value": False}, [], "[y/N]", "", False), ({"prompt": True, "default": True, "flag_value": False}, [], "[y/N]", "y", True), ({"prompt": True, "default": True, "flag_value": False}, [], "[y/N]", "n", False), # default=False ({"prompt": True, "default": False, "flag_value": True}, [], "[y/N]", "", False), ({"prompt": True, "default": False, "flag_value": True}, [], "[y/N]", "y", True), ({"prompt": True, "default": False, "flag_value": True}, [], "[y/N]", "n", False), ({"prompt": True, "default": False, "flag_value": False}, [], "[y/N]", "", False), ({"prompt": True, "default": False, "flag_value": False}, [], "[y/N]", "y", True), ({"prompt": True, "default": False, "flag_value": False}, [], "[y/N]", "n", False), # default=None ( {"prompt": True, "default": None, "flag_value": True}, [], "[y/n]", "", INVALID, ), ({"prompt": True, "default": None, "flag_value": True}, [], "[y/n]", "y", True), ({"prompt": True, "default": None, "flag_value": True}, [], "[y/n]", "n", False), ( {"prompt": True, "default": None, "flag_value": False}, [], "[y/n]", "", INVALID, ), ({"prompt": True, "default": None, "flag_value": False}, [], "[y/n]", "y", True), ({"prompt": True, "default": None, "flag_value": False}, [], "[y/n]", "n", False), # If the flag_value is None, the flag behave like a string flag, whatever the # default is. ({"prompt": True, "default": True, "flag_value": None}, [], "", "", REPEAT), ({"prompt": True, "default": True, "flag_value": None}, [], "", "y", "y"), ({"prompt": True, "default": True, "flag_value": None}, [], "", "n", "n"), ( {"prompt": True, "default": False, "flag_value": None}, [], "[False]", "", "False", ), ({"prompt": True, "default": False, "flag_value": None}, [], "[False]", "y", "y"), ({"prompt": True, "default": False, "flag_value": None}, [], "[False]", "n", "n"), ({"prompt": True, "default": None, "flag_value": None}, [], "", "", REPEAT), ({"prompt": True, "default": None, "flag_value": None}, [], "", "y", "y"), ({"prompt": True, "default": None, "flag_value": None}, [], "", "n", "n"), ] @pytest.mark.parametrize( ("opt_decls", "opt_params", "args", "prompt", "input", "expected"), # Boolean flag prompt cases. [("--flag/--no-flag", *case_params) for case_params in BOOLEAN_FLAG_PROMPT_CASES] # Non-boolean flag prompt cases. + [("--flag", *case_params) for case_params in FLAG_VALUE_PROMPT_CASES], ) def test_flag_value_prompt( runner, opt_decls, opt_params, args, prompt, input, expected ): """Check how flag value are prompted and handled by all combinations of ``prompt``, ``default``, and ``flag_value`` parameters. Covers concerns raised in issue https://github.com/pallets/click/issues/1992. """ @click.command() @click.option(opt_decls, **opt_params) def cli(flag): click.echo(repr(flag)) invoke_options = {"standalone_mode": False} if input is not None: assert isinstance(input, str) invoke_options["input"] = f"{input}\n" result = runner.invoke(cli, args, **invoke_options) if expected in (MissingParameter, BadParameter): assert isinstance(result.exception, expected) assert not result.output assert result.exit_code == 1 else: expected_output = "" if prompt is not None: # Build the expected prompt. assert isinstance(prompt, str) expected_prompt = f"Flag {prompt}: " if prompt else "Flag: " # Add the user input to the expected output. assert isinstance(input, str) expected_output += f"{expected_prompt}{input}\n" if expected is INVALID: expected_output += "Error: invalid input\n" # The prompt is expected to be repeated. if expected in (REPEAT, INVALID): expected_output += expected_prompt if expected not in (REPEAT, INVALID): expected_output += f"{expected!r}\n" assert result.output == expected_output assert not result.stderr assert result.exit_code == 0 if expected not in (REPEAT, INVALID) else 1 asyncclick-8.3.0.5-async/tests/test_testing.py000066400000000000000000000323561507140761400213710ustar00rootroot00000000000000import os import sys from io import BytesIO import pytest import asyncclick as click from asyncclick.exceptions import ClickException from asyncclick.testing import CliRunner @pytest.mark.anyio async def test_runner(): @click.command() def test(): i = click.get_binary_stream("stdin") o = click.get_binary_stream("stdout") while True: chunk = i.read(4096) if not chunk: break o.write(chunk) o.flush() runner = CliRunner() result = await runner.invoke(test, input="Hello World!\n") if result.exception: raise result.exception assert result.output == "Hello World!\n" @pytest.mark.anyio async def test_echo_stdin_stream(): @click.command() def test(): i = click.get_binary_stream("stdin") o = click.get_binary_stream("stdout") while True: chunk = i.read(4096) if not chunk: break o.write(chunk) o.flush() runner = CliRunner(echo_stdin=True) result = await runner.invoke(test, input="Hello World!\n") if result.exception: raise result.exception assert result.output == "Hello World!\nHello World!\n" @pytest.mark.anyio async def test_echo_stdin_prompts(): @click.command() def test_python_input(): foo = input("Foo: ") click.echo(f"foo={foo}") runner = CliRunner(echo_stdin=True) result = await runner.invoke(test_python_input, input="bar bar\n") if result.exception: raise result.exception assert result.output == "Foo: bar bar\nfoo=bar bar\n" @click.command() @click.option("--foo", prompt=True) def test_prompt(foo): click.echo(f"foo={foo}") result = await runner.invoke(test_prompt, input="bar bar\n") if result.exception: raise result.exception assert result.output == "Foo: bar bar\nfoo=bar bar\n" @click.command() @click.option("--foo", prompt=True, hide_input=True) def test_hidden_prompt(foo): click.echo(f"foo={foo}") result = await runner.invoke(test_hidden_prompt, input="bar bar\n") if result.exception: raise result.exception assert result.output == "Foo: \nfoo=bar bar\n" @click.command() @click.option("--foo", prompt=True) @click.option("--bar", prompt=True) def test_multiple_prompts(foo, bar): click.echo(f"foo={foo}, bar={bar}") result = await runner.invoke(test_multiple_prompts, input="one\ntwo\n") if result.exception: raise result.exception assert result.output == "Foo: one\nBar: two\nfoo=one, bar=two\n" @pytest.mark.anyio async def test_runner_with_stream(): @click.command() def test(): i = click.get_binary_stream("stdin") o = click.get_binary_stream("stdout") while True: chunk = i.read(4096) if not chunk: break o.write(chunk) o.flush() runner = CliRunner() result = await runner.invoke(test, input=BytesIO(b"Hello World!\n")) if result.exception: raise result.exception assert result.output == "Hello World!\n" runner = CliRunner(echo_stdin=True) result = await runner.invoke(test, input=BytesIO(b"Hello World!\n")) if result.exception: raise result.exception assert result.output == "Hello World!\nHello World!\n" @pytest.mark.anyio async def test_prompts(): @click.command() @click.option("--foo", prompt=True) def test(foo): click.echo(f"foo={foo}") runner = CliRunner() result = await runner.invoke(test, input="wau wau\n") if result.exception: raise result.exception assert result.output == "Foo: wau wau\nfoo=wau wau\n" @click.command() @click.option("--foo", prompt=True, hide_input=True) def test(foo): click.echo(f"foo={foo}") runner = CliRunner() result = await runner.invoke(test, input="wau wau\n") if result.exception: raise result.exception assert result.output == "Foo: \nfoo=wau wau\n" @pytest.mark.anyio async def test_getchar(): @click.command() def continue_it(): click.echo(click.getchar()) runner = CliRunner() result = await runner.invoke(continue_it, input="y") if result.exception: raise result.exception assert result.output == "y\n" runner = CliRunner(echo_stdin=True) result = await runner.invoke(continue_it, input="y") if result.exception: raise result.exception assert result.output == "y\n" @click.command() def getchar_echo(): click.echo(click.getchar(echo=True)) runner = CliRunner() result = await runner.invoke(getchar_echo, input="y") if result.exception: raise result.exception assert result.output == "yy\n" runner = CliRunner(echo_stdin=True) result = await runner.invoke(getchar_echo, input="y") if result.exception: raise result.exception assert result.output == "yy\n" @pytest.mark.anyio async def test_catch_exceptions(): class CustomError(Exception): pass @click.command() def cli(): raise CustomError(1) runner = CliRunner() result = await runner.invoke(cli) assert isinstance(result.exception, CustomError) assert type(result.exc_info) is tuple assert len(result.exc_info) == 3 with pytest.raises(CustomError): await runner.invoke(cli, catch_exceptions=False) CustomError = SystemExit result = await runner.invoke(cli) assert result.exit_code == 1 @pytest.mark.anyio async def test_catch_exceptions_cli_runner(): """Test that invoke `catch_exceptions` takes the value from CliRunner if not set explicitly.""" class CustomError(Exception): pass @click.command() async def cli(): raise CustomError(1) runner = CliRunner(catch_exceptions=False) result = await runner.invoke(cli, catch_exceptions=True) assert isinstance(result.exception, CustomError) assert type(result.exc_info) is tuple assert len(result.exc_info) == 3 with pytest.raises(CustomError): await runner.invoke(cli) @pytest.mark.anyio async def test_with_color(): @click.command() def cli(): click.secho("hello world", fg="blue") runner = CliRunner() result = await runner.invoke(cli) assert result.output == "hello world\n" if result.exception: raise result.exception result = await runner.invoke(cli, color=True) assert result.output == f"{click.style('hello world', fg='blue')}\n" if result.exception: raise result.exception @pytest.mark.anyio async def test_with_color_errors(): class CLIError(ClickException): def format_message(self) -> str: return click.style(self.message, fg="red") @click.command() def cli(): raise CLIError("Red error") runner = CliRunner() result = await runner.invoke(cli) assert result.output == "Error: Red error\n" assert result.exception result = await runner.invoke(cli, color=True) assert result.output == f"Error: {click.style('Red error', fg='red')}\n" assert result.exception @pytest.mark.anyio async def test_with_color_but_pause_not_blocking(): @click.command() def cli(): click.pause() runner = CliRunner() result = await runner.invoke(cli, color=True) if result.exception: raise result.exception assert result.output == "" @pytest.mark.anyio async def test_exit_code_and_output_from_sys_exit(): # See issue #362 @click.command() def cli_string(): click.echo("hello world") sys.exit("error") @click.command() @click.pass_context async def cli_string_ctx_exit(ctx): click.echo("hello world") await ctx.aexit("error") @click.command() def cli_int(): click.echo("hello world") sys.exit(1) @click.command() @click.pass_context async def cli_int_ctx_exit(ctx): click.echo("hello world") await ctx.aexit(1) @click.command() def cli_float(): click.echo("hello world") sys.exit(1.0) @click.command() @click.pass_context async def cli_float_ctx_exit(ctx): click.echo("hello world") await ctx.aexit(1.0) @click.command() def cli_no_error(): click.echo("hello world") runner = CliRunner() result = await runner.invoke(cli_string) assert result.exit_code == 1 assert result.output == "hello world\nerror\n" result = await runner.invoke(cli_string_ctx_exit) assert result.exit_code == 1 assert result.output == "hello world\nerror\n" result = await runner.invoke(cli_int) assert result.exit_code == 1 assert result.output == "hello world\n" result = await runner.invoke(cli_int_ctx_exit) assert result.exit_code == 1 assert result.output == "hello world\n" result = await runner.invoke(cli_float) assert result.exit_code == 1 assert result.output == "hello world\n1.0\n" result = await runner.invoke(cli_float_ctx_exit) assert result.exit_code == 1 assert result.output == "hello world\n1.0\n" result = await runner.invoke(cli_no_error) assert result.exit_code == 0 assert result.output == "hello world\n" @pytest.mark.anyio async def test_env(): @click.command() def cli_env(): click.echo(f"ENV={os.environ['TEST_CLICK_ENV']}") runner = CliRunner() env_orig = dict(os.environ) env = dict(env_orig) assert "TEST_CLICK_ENV" not in env env["TEST_CLICK_ENV"] = "some_value" result = await runner.invoke(cli_env, env=env) assert result.exit_code == 0 assert result.output == "ENV=some_value\n" assert os.environ == env_orig @pytest.mark.anyio async def test_stderr(): @click.command() def cli_stderr(): click.echo("1 - stdout") click.echo("2 - stderr", err=True) click.echo("3 - stdout") click.echo("4 - stderr", err=True) runner_mix = CliRunner() result_mix = await runner_mix.invoke(cli_stderr) assert result_mix.output == "1 - stdout\n2 - stderr\n3 - stdout\n4 - stderr\n" assert result_mix.stdout == "1 - stdout\n3 - stdout\n" assert result_mix.stderr == "2 - stderr\n4 - stderr\n" @click.command() def cli_empty_stderr(): click.echo("stdout") runner = CliRunner() result = await runner.invoke(cli_empty_stderr) assert result.output == "stdout\n" assert result.stdout == "stdout\n" assert result.stderr == "" @pytest.mark.parametrize( "args, expected_output", [ (None, "bar\n"), ([], "bar\n"), ("", "bar\n"), (["--foo", "one two"], "one two\n"), ('--foo "one two"', "one two\n"), ], ) @pytest.mark.anyio async def test_args(args, expected_output): @click.command() @click.option("--foo", default="bar") def cli_args(foo): click.echo(foo) runner = CliRunner() result = await runner.invoke(cli_args, args=args) assert result.exit_code == 0 assert result.output == expected_output @pytest.mark.anyio async def test_setting_prog_name_in_extra(): @click.command() def cli(): click.echo("ok") runner = CliRunner() result = await runner.invoke(cli, prog_name="foobar") if result.exception: raise result.exception assert result.output == "ok\n" @pytest.mark.anyio async def test_command_standalone_mode_returns_value(): @click.command() def cli(): click.echo("ok") return "Hello, World!" runner = CliRunner() result = await runner.invoke(cli, standalone_mode=False) assert result.output == "ok\n" assert result.return_value == "Hello, World!" assert result.exit_code == 0 @pytest.mark.anyio async def test_file_stdin_attrs(runner): @click.command() @click.argument("f", type=click.File()) def cli(f): click.echo(f.name) click.echo(f.mode, nl=False) result = runner.invoke(cli, ["-"]) assert result.output == "\nr" def test_isolated_runner(runner): with runner.isolated_filesystem() as d: assert os.path.exists(d) assert not os.path.exists(d) def test_isolated_runner_custom_tempdir(runner, tmp_path): with runner.isolated_filesystem(temp_dir=tmp_path) as d: assert os.path.exists(d) assert os.path.exists(d) os.rmdir(d) def test_isolation_stderr_errors(): """Writing to stderr should escape invalid characters instead of raising a UnicodeEncodeError. """ runner = CliRunner() with runner.isolation() as (_, err, _): click.echo("\udce2", err=True, nl=False) assert err.getvalue() == b"\\udce2" @pytest.mark.anyio async def test_isolation_flushes_unflushed_stderr(): """An un-flushed write to stderr, as with `print(..., file=sys.stderr)`, will end up flushed by the runner at end of invocation. """ runner = CliRunner() with runner.isolation() as (_, err, _): click.echo("\udce2", err=True, nl=False) assert err.getvalue() == b"\\udce2" @click.command() def cli(): # set end="", flush=False so that it's totally clear that we won't get any # auto-flush behaviors print("gyarados gyarados gyarados", file=sys.stderr, end="", flush=False) result = await runner.invoke(cli) assert result.stderr == "gyarados gyarados gyarados" asyncclick-8.3.0.5-async/tests/test_types.py000066400000000000000000000176721507140761400210640ustar00rootroot00000000000000import os.path import pathlib import platform import tempfile import pytest import asyncclick as click from asyncclick import FileError @pytest.mark.parametrize( ("type", "value", "expect"), [ (click.IntRange(0, 5), "3", 3), (click.IntRange(5), "5", 5), (click.IntRange(5), "100", 100), (click.IntRange(max=5), "5", 5), (click.IntRange(max=5), "-100", -100), (click.IntRange(0, clamp=True), "-1", 0), (click.IntRange(max=5, clamp=True), "6", 5), (click.IntRange(0, min_open=True, clamp=True), "0", 1), (click.IntRange(max=5, max_open=True, clamp=True), "5", 4), (click.FloatRange(0.5, 1.5), "1.2", 1.2), (click.FloatRange(0.5, min_open=True), "0.51", 0.51), (click.FloatRange(max=1.5, max_open=True), "1.49", 1.49), (click.FloatRange(0.5, clamp=True), "-0.0", 0.5), (click.FloatRange(max=1.5, clamp=True), "inf", 1.5), ], ) def test_range(type, value, expect): assert type.convert(value, None, None) == expect @pytest.mark.parametrize( ("type", "value", "expect"), [ (click.IntRange(0, 5), "6", "6 is not in the range 0<=x<=5."), (click.IntRange(5), "4", "4 is not in the range x>=5."), (click.IntRange(max=5), "6", "6 is not in the range x<=5."), (click.IntRange(0, 5, min_open=True), 0, "00.5"), (click.FloatRange(max=1.5, max_open=True), 1.5, "x<1.5"), ], ) def test_range_fail(type, value, expect): with pytest.raises(click.BadParameter) as exc_info: type.convert(value, None, None) assert expect in exc_info.value.message def test_float_range_no_clamp_open(): with pytest.raises(TypeError): click.FloatRange(0, 1, max_open=True, clamp=True) sneaky = click.FloatRange(0, 1, max_open=True) sneaky.clamp = True with pytest.raises(RuntimeError): sneaky.convert("1.5", None, None) @pytest.mark.parametrize( ("nargs", "multiple", "default", "expect"), [ (2, False, None, None), (2, False, (None, None), (None, None)), (None, True, None, ()), (None, True, (None, None), (None, None)), (2, True, None, ()), (2, True, [(None, None)], ((None, None),)), (-1, None, None, ()), ], ) def test_cast_multi_default(runner, nargs, multiple, default, expect): if nargs == -1: param = click.Argument(["a"], nargs=nargs, default=default) else: param = click.Option(["-a"], nargs=nargs, multiple=multiple, default=default) cli = click.Command("cli", params=[param], callback=lambda a: a) result = runner.invoke(cli, standalone_mode=False) assert result.exception is None assert result.return_value == expect @pytest.mark.parametrize( ("cls", "expect"), [ (None, "a/b/c.txt"), (str, "a/b/c.txt"), (bytes, b"a/b/c.txt"), (pathlib.Path, pathlib.Path("a", "b", "c.txt")), ], ) def test_path_type(runner, cls, expect): cli = click.Command( "cli", params=[click.Argument(["p"], type=click.Path(path_type=cls))], callback=lambda p: p, ) result = runner.invoke(cli, ["a/b/c.txt"], standalone_mode=False) assert result.exception is None assert result.return_value == expect def _symlinks_supported(): with tempfile.TemporaryDirectory(prefix="click-pytest-") as tempdir: target = os.path.join(tempdir, "target") open(target, "w").close() link = os.path.join(tempdir, "link") try: os.symlink(target, link) return True except OSError: return False @pytest.mark.skipif( not _symlinks_supported(), reason="The current OS or FS doesn't support symlinks." ) def test_path_resolve_symlink(tmp_path, runner): test_file = tmp_path / "file" test_file_str = os.fspath(test_file) test_file.write_text("") path_type = click.Path(resolve_path=True) param = click.Argument(["a"], type=path_type) ctx = click.Context(click.Command("cli", params=[param])) test_dir = tmp_path / "dir" test_dir.mkdir() abs_link = test_dir / "abs" abs_link.symlink_to(test_file) abs_rv = path_type.convert(os.fspath(abs_link), param, ctx) assert abs_rv == test_file_str rel_link = test_dir / "rel" rel_link.symlink_to(pathlib.Path("..") / "file") rel_rv = path_type.convert(os.fspath(rel_link), param, ctx) assert rel_rv == test_file_str def _non_utf8_filenames_supported(): with tempfile.TemporaryDirectory(prefix="click-pytest-") as tempdir: try: f = open(os.path.join(tempdir, "\udcff"), "w") except OSError: return False f.close() return True @pytest.mark.skipif( not _non_utf8_filenames_supported(), reason="The current OS or FS doesn't support non-UTF-8 filenames.", ) def test_path_surrogates(tmp_path, monkeypatch): monkeypatch.chdir(tmp_path) type = click.Path(exists=True) path = pathlib.Path("\udcff") with pytest.raises(click.BadParameter, match="'�' does not exist"): type.convert(path, None, None) type = click.Path(file_okay=False) path.touch() with pytest.raises(click.BadParameter, match="'�' is a file"): type.convert(path, None, None) path.unlink() type = click.Path(dir_okay=False) path.mkdir() with pytest.raises(click.BadParameter, match="'�' is a directory"): type.convert(path, None, None) path.rmdir() def no_access(*args, **kwargs): """Test environments may be running as root, so we have to fake the result of the access tests that use os.access """ p = args[0] assert p == path, f"unexpected os.access call on file not under test: {p!r}" return False path.touch() type = click.Path(readable=True) with pytest.raises(click.BadParameter, match="'�' is not readable"): with monkeypatch.context() as m: m.setattr(os, "access", no_access) type.convert(path, None, None) type = click.Path(readable=False, writable=True) with pytest.raises(click.BadParameter, match="'�' is not writable"): with monkeypatch.context() as m: m.setattr(os, "access", no_access) type.convert(path, None, None) type = click.Path(readable=False, executable=True) with pytest.raises(click.BadParameter, match="'�' is not executable"): with monkeypatch.context() as m: m.setattr(os, "access", no_access) type.convert(path, None, None) path.unlink() @pytest.mark.parametrize( "type", [ click.File(mode="r"), click.File(mode="r", lazy=True), ], ) def test_file_surrogates(type, tmp_path): path = tmp_path / "\udcff" # - common case: �': No such file or directory # - special case: Illegal byte sequence # The spacial case is seen with rootless Podman. The root cause is most # likely that the path is handled by a user-space program (FUSE). match = r"(�': No such file or directory|Illegal byte sequence)" with pytest.raises(click.BadParameter, match=match): type.convert(path, None, None) def test_file_error_surrogates(): message = FileError(filename="\udcff").format_message() assert message == "Could not open file '�': unknown error" @pytest.mark.skipif( platform.system() == "Windows", reason="Filepath syntax differences." ) def test_invalid_path_with_esc_sequence(): with pytest.raises(click.BadParameter) as exc_info: with tempfile.TemporaryDirectory(prefix="my\ndir") as tempdir: click.Path(dir_okay=False).convert(tempdir, None, None) assert "my\\ndir" in exc_info.value.message def test_choice_get_invalid_choice_message(): choice = click.Choice(["a", "b", "c"]) message = choice.get_invalid_choice_message("d", ctx=None) assert message == "'d' is not one of 'a', 'b', 'c'." asyncclick-8.3.0.5-async/tests/test_utils.py000066400000000000000000000551451507140761400210550ustar00rootroot00000000000000import os import pathlib import stat import subprocess import sys from collections import namedtuple from contextlib import nullcontext from decimal import Decimal from fractions import Fraction from functools import partial from io import StringIO from pathlib import Path from tempfile import tempdir from unittest.mock import patch import pytest import asyncclick as click import asyncclick._termui_impl import asyncclick.utils from asyncclick._compat import WIN from asyncclick._utils import UNSET def test_unset_sentinel(): value = UNSET assert value assert value is UNSET assert value == UNSET assert repr(value) == "Sentinel.UNSET" assert str(value) == "Sentinel.UNSET" assert bool(value) is True # Try all native Python values that can be falsy or truthy. # See: https://docs.python.org/3/library/stdtypes.html#truth-value-testing real_values = ( None, True, False, 0, 1, 0.0, 1.0, 0j, 1j, Decimal(0), Decimal(1), Fraction(0, 1), Fraction(1, 1), "", "a", "UNSET", "Sentinel.UNSET", [1], (1), {1: "a"}, set(), set([1]), frozenset(), frozenset([1]), range(0), range(1), ) for real_value in real_values: assert value != real_value assert value is not real_value assert value not in real_values def test_echo(runner): with runner.isolation() as outstreams: click.echo("\N{SNOWMAN}") click.echo(b"\x44\x44") click.echo(42, nl=False) click.echo(b"a", nl=False) click.echo("\x1b[31mx\x1b[39m", nl=False) bytes = outstreams[0].getvalue().replace(b"\r\n", b"\n") assert bytes == b"\xe2\x98\x83\nDD\n42ax" # if wrapped, we expect bytes to survive. @click.command() def cli(): click.echo(b"\xf6") result = runner.invoke(cli, []) assert result.stdout_bytes == b"\xf6\n" # Ensure we do not strip for bytes. with runner.isolation() as outstreams: click.echo(bytearray(b"\x1b[31mx\x1b[39m"), nl=False) assert outstreams[0].getvalue() == b"\x1b[31mx\x1b[39m" def test_echo_custom_file(): f = StringIO() click.echo("hello", file=f) assert f.getvalue() == "hello\n" def test_echo_no_streams(monkeypatch, runner): """echo should not fail when stdout and stderr are None with pythonw on Windows.""" with runner.isolation(): sys.stdout = None sys.stderr = None click.echo("test") click.echo("test", err=True) @pytest.mark.parametrize( ("styles", "ref"), [ ({"fg": "black"}, "\x1b[30mx y\x1b[0m"), ({"fg": "red"}, "\x1b[31mx y\x1b[0m"), ({"fg": "green"}, "\x1b[32mx y\x1b[0m"), ({"fg": "yellow"}, "\x1b[33mx y\x1b[0m"), ({"fg": "blue"}, "\x1b[34mx y\x1b[0m"), ({"fg": "magenta"}, "\x1b[35mx y\x1b[0m"), ({"fg": "cyan"}, "\x1b[36mx y\x1b[0m"), ({"fg": "white"}, "\x1b[37mx y\x1b[0m"), ({"bg": "black"}, "\x1b[40mx y\x1b[0m"), ({"bg": "red"}, "\x1b[41mx y\x1b[0m"), ({"bg": "green"}, "\x1b[42mx y\x1b[0m"), ({"bg": "yellow"}, "\x1b[43mx y\x1b[0m"), ({"bg": "blue"}, "\x1b[44mx y\x1b[0m"), ({"bg": "magenta"}, "\x1b[45mx y\x1b[0m"), ({"bg": "cyan"}, "\x1b[46mx y\x1b[0m"), ({"bg": "white"}, "\x1b[47mx y\x1b[0m"), ({"bg": 91}, "\x1b[48;5;91mx y\x1b[0m"), ({"bg": (135, 0, 175)}, "\x1b[48;2;135;0;175mx y\x1b[0m"), ({"bold": True}, "\x1b[1mx y\x1b[0m"), ({"dim": True}, "\x1b[2mx y\x1b[0m"), ({"underline": True}, "\x1b[4mx y\x1b[0m"), ({"overline": True}, "\x1b[53mx y\x1b[0m"), ({"italic": True}, "\x1b[3mx y\x1b[0m"), ({"blink": True}, "\x1b[5mx y\x1b[0m"), ({"reverse": True}, "\x1b[7mx y\x1b[0m"), ({"strikethrough": True}, "\x1b[9mx y\x1b[0m"), ({"bold": False}, "\x1b[22mx y\x1b[0m"), ({"dim": False}, "\x1b[22mx y\x1b[0m"), ({"underline": False}, "\x1b[24mx y\x1b[0m"), ({"overline": False}, "\x1b[55mx y\x1b[0m"), ({"italic": False}, "\x1b[23mx y\x1b[0m"), ({"blink": False}, "\x1b[25mx y\x1b[0m"), ({"reverse": False}, "\x1b[27mx y\x1b[0m"), ({"strikethrough": False}, "\x1b[29mx y\x1b[0m"), ({"fg": "black", "reset": False}, "\x1b[30mx y"), ], ) def test_styling(styles, ref): assert click.style("x y", **styles) == ref assert click.unstyle(ref) == "x y" @pytest.mark.parametrize(("text", "expect"), [("\x1b[?25lx y\x1b[?25h", "x y")]) def test_unstyle_other_ansi(text, expect): assert click.unstyle(text) == expect def test_filename_formatting(): assert click.format_filename(b"foo.txt") == "foo.txt" assert click.format_filename(b"/x/foo.txt") == "/x/foo.txt" assert click.format_filename("/x/foo.txt") == "/x/foo.txt" assert click.format_filename("/x/foo.txt", shorten=True) == "foo.txt" assert click.format_filename("/x/\ufffd.txt", shorten=True) == "�.txt" def test_prompts(runner): @click.command() def test(): if click.confirm("Foo"): click.echo("yes!") else: click.echo("no :(") result = runner.invoke(test, input="y\n") assert not result.exception assert result.output == "Foo [y/N]: y\nyes!\n" result = runner.invoke(test, input="\n") assert not result.exception assert result.output == "Foo [y/N]: \nno :(\n" result = runner.invoke(test, input="n\n") assert not result.exception assert result.output == "Foo [y/N]: n\nno :(\n" @click.command() def test_no(): if click.confirm("Foo", default=True): click.echo("yes!") else: click.echo("no :(") result = runner.invoke(test_no, input="y\n") assert not result.exception assert result.output == "Foo [Y/n]: y\nyes!\n" result = runner.invoke(test_no, input="\n") assert not result.exception assert result.output == "Foo [Y/n]: \nyes!\n" result = runner.invoke(test_no, input="n\n") assert not result.exception assert result.output == "Foo [Y/n]: n\nno :(\n" def test_confirm_repeat(runner): cli = click.Command( "cli", params=[click.Option(["--a/--no-a"], default=None, prompt=True)] ) result = runner.invoke(cli, input="\ny\n") assert result.output == "A [y/n]: \nError: invalid input\nA [y/n]: y\n" @pytest.mark.skipif(WIN, reason="Different behavior on windows.") @pytest.mark.anyio async def test_prompts_abort(monkeypatch, capsys): def f(_): raise KeyboardInterrupt() monkeypatch.setattr("asyncclick.termui.hidden_prompt_func", f) try: await click.prompt("Password", hide_input=True) except click.Abort: click.echo("interrupted") out, err = capsys.readouterr() assert out == "Password:\ninterrupted\n" def test_prompts_eof(runner): """If too few lines of input are given, prompt should exit, not hang.""" @click.command async def echo(): for _ in range(3): click.echo(await click.prompt("", type=int)) # only provide two lines of input for three prompts result = runner.invoke(echo, input="1\n2\n") assert result.exit_code == 1 def _test_gen_func(): yield "a" yield "b" yield "c" yield "abc" def _test_gen_func_fails(): yield "test" raise RuntimeError("This is a test.") def _test_gen_func_echo(file=None): yield "test" click.echo("hello", file=file) yield "test" def _test_simulate_keyboard_interrupt(file=None): yield "output_before_keyboard_interrupt" raise KeyboardInterrupt() EchoViaPagerTest = namedtuple( "EchoViaPagerTest", ( "description", "test_input", "expected_pager", "expected_stdout", "expected_stderr", "expected_error", ), ) @pytest.mark.skipif(WIN, reason="Different behavior on windows.") @pytest.mark.parametrize( "pager_cmd", ["cat", "cat ", " cat ", "less", " less", " less "] ) @pytest.mark.parametrize( "test", [ # We need to pass a parameter function instead of a plain param # as pytest.mark.parametrize will reuse the parameters causing the # generators to be used up so they will not yield anymore EchoViaPagerTest( description="Plain string argument", test_input=lambda: "just text", expected_pager="just text\n", expected_stdout="", expected_stderr="", expected_error=None, ), EchoViaPagerTest( description="Iterable argument", test_input=lambda: ["itera", "ble"], expected_pager="iterable\n", expected_stdout="", expected_stderr="", expected_error=None, ), EchoViaPagerTest( description="Generator function argument", test_input=lambda: _test_gen_func, expected_pager="abcabc\n", expected_stdout="", expected_stderr="", expected_error=None, ), EchoViaPagerTest( description="String generator argument", test_input=lambda: _test_gen_func(), expected_pager="abcabc\n", expected_stdout="", expected_stderr="", expected_error=None, ), EchoViaPagerTest( description="Number generator expression argument", test_input=lambda: (c for c in range(6)), expected_pager="012345\n", expected_stdout="", expected_stderr="", expected_error=None, ), EchoViaPagerTest( description="Exception in generator function argument", test_input=lambda: _test_gen_func_fails, # Because generator throws early on, the pager did not have # a chance yet to write the file. expected_pager="", expected_stdout="", expected_stderr="", expected_error=RuntimeError, ), EchoViaPagerTest( description="Exception in generator argument", test_input=lambda: _test_gen_func_fails, # Because generator throws early on, the pager did not have a # chance yet to write the file. expected_pager="", expected_stdout="", expected_stderr="", expected_error=RuntimeError, ), EchoViaPagerTest( description="Keyboard interrupt should not terminate the pager", test_input=lambda: _test_simulate_keyboard_interrupt(), # Due to the keyboard interrupt during pager execution, click program # should abort, but the pager should stay open. # This allows users to cancel the program and search in the pager # output, before they decide to terminate the pager. expected_pager="output_before_keyboard_interrupt", expected_stdout="", expected_stderr="", expected_error=KeyboardInterrupt, ), EchoViaPagerTest( description="Writing to stdout during generator execution", test_input=lambda: _test_gen_func_echo(), expected_pager="testtest\n", expected_stdout="hello\n", expected_stderr="", expected_error=None, ), EchoViaPagerTest( description="Writing to stderr during generator execution", test_input=lambda: _test_gen_func_echo(file=sys.stderr), expected_pager="testtest\n", expected_stdout="", expected_stderr="hello\n", expected_error=None, ), ], ) def test_echo_via_pager(monkeypatch, capfd, pager_cmd, test): monkeypatch.setitem(os.environ, "PAGER", pager_cmd) monkeypatch.setattr(asyncclick._termui_impl, "isatty", lambda x: True) test_input = test.test_input() expected_pager = test.expected_pager expected_stdout = test.expected_stdout expected_stderr = test.expected_stderr expected_error = test.expected_error check_raise = pytest.raises(expected_error) if expected_error else nullcontext() pager_out_tmp = Path(tempdir) / "pager_out.txt" pager_out_tmp.unlink(missing_ok=True) with pager_out_tmp.open("w") as f: force_subprocess_stdout = patch.object( subprocess, "Popen", partial(subprocess.Popen, stdout=f), ) with force_subprocess_stdout: with check_raise: click.echo_via_pager(test_input) out, err = capfd.readouterr() pager = pager_out_tmp.read_text() assert pager == expected_pager, ( f"Unexpected pager output in test case '{test.description}'" ) assert out == expected_stdout, ( f"Unexpected stdout in test case '{test.description}'" ) assert err == expected_stderr, ( f"Unexpected stderr in test case '{test.description}'" ) def test_echo_color_flag(monkeypatch, capfd): isatty = True monkeypatch.setattr(click._compat, "isatty", lambda x: isatty) text = "foo" styled_text = click.style(text, fg="red") assert styled_text == "\x1b[31mfoo\x1b[0m" click.echo(styled_text, color=False) out, err = capfd.readouterr() assert out == f"{text}\n" click.echo(styled_text, color=True) out, err = capfd.readouterr() assert out == f"{styled_text}\n" isatty = True click.echo(styled_text) out, err = capfd.readouterr() assert out == f"{styled_text}\n" isatty = False # Faking isatty() is not enough on Windows; # the implementation caches the colorama wrapped stream # so we have to use a new stream for each test stream = StringIO() click.echo(styled_text, file=stream) assert stream.getvalue() == f"{text}\n" stream = StringIO() click.echo(styled_text, file=stream, color=True) assert stream.getvalue() == f"{styled_text}\n" @pytest.mark.anyio async def test_prompt_cast_default(capfd, monkeypatch): monkeypatch.setattr(sys, "stdin", StringIO("\n")) value = await click.prompt("value", default="100", type=int) capfd.readouterr() assert isinstance(value, int) @pytest.mark.skipif(WIN, reason="Test too complex to make work windows.") @pytest.mark.anyio async def test_echo_writing_to_standard_error(capfd, monkeypatch): def emulate_input(text): """Emulate keyboard input.""" monkeypatch.setattr(sys, "stdin", StringIO(text)) click.echo("Echo to standard output") out, err = capfd.readouterr() assert out == "Echo to standard output\n" assert err == "" click.echo("Echo to standard error", err=True) out, err = capfd.readouterr() assert out == "" assert err == "Echo to standard error\n" emulate_input("asdlkj\n") await click.prompt("Prompt to stdin") out, err = capfd.readouterr() assert out == "Prompt to stdin: " assert err == "" emulate_input("asdlkj\n") await click.prompt("Prompt to stderr", err=True) out, err = capfd.readouterr() assert out == " " assert err == "Prompt to stderr:" emulate_input("y\n") click.confirm("Prompt to stdin") out, err = capfd.readouterr() assert out == "Prompt to stdin [y/N]: " assert err == "" emulate_input("y\n") click.confirm("Prompt to stderr", err=True) out, err = capfd.readouterr() assert out == " " assert err == "Prompt to stderr [y/N]:" monkeypatch.setattr(click.termui, "isatty", lambda x: True) monkeypatch.setattr(click.termui, "getchar", lambda: " ") click.pause("Pause to stdout") out, err = capfd.readouterr() assert out == "Pause to stdout\n" assert err == "" click.pause("Pause to stderr", err=True) out, err = capfd.readouterr() assert out == "" assert err == "Pause to stderr\n" def test_echo_with_capsys(capsys): click.echo("Capture me.") out, err = capsys.readouterr() assert out == "Capture me.\n" def test_open_file(runner): @click.command() @click.argument("filename") def cli(filename): with click.open_file(filename) as f: click.echo(f.read()) click.echo("meep") with runner.isolated_filesystem(): with open("hello.txt", "w") as f: f.write("Cool stuff") result = runner.invoke(cli, ["hello.txt"]) assert result.exception is None assert result.output == "Cool stuff\nmeep\n" result = runner.invoke(cli, ["-"], input="foobar") assert result.exception is None assert result.output == "foobar\nmeep\n" def test_open_file_pathlib_dash(runner): @click.command() @click.argument( "filename", type=click.Path(allow_dash=True, path_type=pathlib.Path) ) def cli(filename): click.echo(str(type(filename))) with click.open_file(filename) as f: click.echo(f.read()) result = runner.invoke(cli, ["-"], input="value") assert result.exception is None assert result.output == "pathlib.Path\nvalue\n" def test_open_file_ignore_errors_stdin(runner): @click.command() @click.argument("filename") def cli(filename): with click.open_file(filename, errors="ignore") as f: click.echo(f.read()) result = runner.invoke(cli, ["-"], input=os.urandom(16)) assert result.exception is None def test_open_file_respects_ignore(runner): with runner.isolated_filesystem(): with open("test.txt", "w") as f: f.write("Hello world!") with click.open_file("test.txt", encoding="utf8", errors="ignore") as f: assert f.errors == "ignore" def test_open_file_ignore_invalid_utf8(runner): with runner.isolated_filesystem(): with open("test.txt", "wb") as f: f.write(b"\xe2\x28\xa1") with click.open_file("test.txt", encoding="utf8", errors="ignore") as f: f.read() def test_open_file_ignore_no_encoding(runner): with runner.isolated_filesystem(): with open("test.bin", "wb") as f: f.write(os.urandom(16)) with click.open_file("test.bin", errors="ignore") as f: f.read() @pytest.mark.skipif(WIN, reason="os.chmod() is not fully supported on Windows.") @pytest.mark.parametrize("permissions", [0o400, 0o444, 0o600, 0o644]) def test_open_file_atomic_permissions_existing_file(runner, permissions): with runner.isolated_filesystem(): with open("existing.txt", "w") as f: f.write("content") os.chmod("existing.txt", permissions) @click.command() @click.argument("filename") def cli(filename): click.open_file(filename, "w", atomic=True).close() result = runner.invoke(cli, ["existing.txt"]) assert result.exception is None assert stat.S_IMODE(os.stat("existing.txt").st_mode) == permissions @pytest.mark.skipif(WIN, reason="os.stat() is not fully supported on Windows.") def test_open_file_atomic_permissions_new_file(runner): with runner.isolated_filesystem(): @click.command() @click.argument("filename") def cli(filename): click.open_file(filename, "w", atomic=True).close() # Create a test file to get the expected permissions for new files # according to the current umask. with open("test.txt", "w"): pass permissions = stat.S_IMODE(os.stat("test.txt").st_mode) result = runner.invoke(cli, ["new.txt"]) assert result.exception is None assert stat.S_IMODE(os.stat("new.txt").st_mode) == permissions def test_iter_keepopenfile(tmpdir): expected = list(map(str, range(10))) p = tmpdir.mkdir("testdir").join("testfile") p.write("\n".join(expected)) with p.open() as f: for e_line, a_line in zip( expected, asyncclick.utils.KeepOpenFile(f), strict=False ): assert e_line == a_line.strip() def test_iter_lazyfile(tmpdir): expected = list(map(str, range(10))) p = tmpdir.mkdir("testdir").join("testfile") p.write("\n".join(expected)) with p.open() as f: with asyncclick.utils.LazyFile(f.name) as lf: for e_line, a_line in zip(expected, lf, strict=False): assert e_line == a_line.strip() class MockMain: __slots__ = "__package__" def __init__(self, package_name): self.__package__ = package_name @pytest.mark.parametrize( ("path", "main", "expected"), [ ("example.py", None, "example.py"), (str(pathlib.Path("/foo/bar/example.py")), None, "example.py"), ("example", None, "example"), (str(pathlib.Path("example/__main__.py")), "example", "python -m example"), (str(pathlib.Path("example/cli.py")), "example", "python -m example.cli"), (str(pathlib.Path("./example")), "", "example"), ], ) def test_detect_program_name(path, main, expected): assert asyncclick.utils._detect_program_name(path, _main=MockMain(main)) == expected def test_expand_args(monkeypatch): user = os.path.expanduser("~") assert user in asyncclick.utils._expand_args(["~"]) monkeypatch.setenv("CLICK_TEST", "hello") assert "hello" in asyncclick.utils._expand_args(["$CLICK_TEST"]) assert "pyproject.toml" in asyncclick.utils._expand_args(["*.toml"]) assert os.path.join("tests", "conftest.py") in asyncclick.utils._expand_args( ["**/conftest.py"] ) assert "*.not-found" in asyncclick.utils._expand_args(["*.not-found"]) # a bad glob pattern, such as a pytest identifier, should return itself assert ( asyncclick.utils._expand_args(["test.py::test_bad"])[0] == "test.py::test_bad" ) @pytest.mark.parametrize( ("value", "max_length", "expect"), [ pytest.param("", 10, "", id="empty"), pytest.param("123 567 90", 10, "123 567 90", id="equal length, no dot"), pytest.param("123 567 9. aaaa bbb", 10, "123 567 9.", id="sentence < max"), pytest.param("123 567\n\n 9. aaaa bbb", 10, "123 567", id="paragraph < max"), pytest.param("123 567 90123.", 10, "123 567...", id="truncate"), pytest.param("123 5678 xxxxxx", 10, "123...", id="length includes suffix"), pytest.param( "token in ~/.netrc ciao ciao", 20, "token in ~/.netrc...", id="ignore dot in word", ), ], ) @pytest.mark.parametrize( "alter", [ pytest.param(None, id=""), pytest.param( lambda text: "\n\b\n" + " ".join(text.split(" ")) + "\n", id="no-wrap mark" ), ], ) def test_make_default_short_help(value, max_length, alter, expect): assert len(expect) <= max_length if alter: value = alter(value) out = asyncclick.utils.make_default_short_help(value, max_length) assert out == expect asyncclick-8.3.0.5-async/tests/typing/000077500000000000000000000000001507140761400176045ustar00rootroot00000000000000asyncclick-8.3.0.5-async/tests/typing/typing_aliased_group.py000066400000000000000000000023021507140761400243630ustar00rootroot00000000000000"""Example from https://click.palletsprojects.com/en/stable/advanced/#command-aliases""" from __future__ import annotations from typing_extensions import assert_type import asyncclick as click class AliasedGroup(click.Group): def get_command(self, ctx: click.Context, cmd_name: str) -> click.Command | None: rv = click.Group.get_command(self, ctx, cmd_name) if rv is not None: return rv matches = [x for x in self.list_commands(ctx) if x.startswith(cmd_name)] if not matches: return None elif len(matches) == 1: return click.Group.get_command(self, ctx, matches[0]) ctx.fail(f"Too many matches: {', '.join(sorted(matches))}") async def resolve_command( self, ctx: click.Context, args: list[str] ) -> tuple[str | None, click.Command, list[str]]: # always return the full command name _, cmd, args = await super().resolve_command(ctx, args) assert cmd is not None return cmd.name, cmd, args @click.command(cls=AliasedGroup) def cli() -> None: pass assert_type(cli, AliasedGroup) @cli.command() def push() -> None: pass @cli.command() def pop() -> None: pass asyncclick-8.3.0.5-async/tests/typing/typing_confirmation_option.py000066400000000000000000000005251507140761400256320ustar00rootroot00000000000000"""From https://click.palletsprojects.com/en/stable/options/#yes-parameters""" from typing_extensions import assert_type import asyncclick as click @click.command() @click.confirmation_option(prompt="Are you sure you want to drop the db?") def dropdb() -> None: click.echo("Dropped all tables!") assert_type(dropdb, click.Command) asyncclick-8.3.0.5-async/tests/typing/typing_group_kw_options.py000066400000000000000000000002521507140761400251570ustar00rootroot00000000000000from typing_extensions import assert_type import asyncclick as click @click.group(context_settings={}) def hello() -> None: pass assert_type(hello, click.Group) asyncclick-8.3.0.5-async/tests/typing/typing_help_option.py000066400000000000000000000004241507140761400240700ustar00rootroot00000000000000from typing_extensions import assert_type import asyncclick as click @click.command() @click.help_option("-h", "--help") def hello() -> None: """Simple program that greets NAME for a total of COUNT times.""" click.echo("Hello!") assert_type(hello, click.Command) asyncclick-8.3.0.5-async/tests/typing/typing_options.py000066400000000000000000000006251507140761400232460ustar00rootroot00000000000000"""From https://click.palletsprojects.com/en/stable/quickstart/#adding-parameters""" from typing_extensions import assert_type import asyncclick as click @click.command() @click.option("--count", default=1, help="number of greetings") @click.argument("name") def hello(count: int, name: str) -> None: for _ in range(count): click.echo(f"Hello {name}!") assert_type(hello, click.Command) asyncclick-8.3.0.5-async/tests/typing/typing_password_option.py000066400000000000000000000004151507140761400250020ustar00rootroot00000000000000import codecs from typing_extensions import assert_type import asyncclick as click @click.command() @click.password_option() def encrypt(password: str) -> None: click.echo(f"encoded: to {codecs.encode(password, 'rot13')}") assert_type(encrypt, click.Command) asyncclick-8.3.0.5-async/tests/typing/typing_progressbar.py000066400000000000000000000010711507140761400241000ustar00rootroot00000000000000from __future__ import annotations from typing_extensions import assert_type from asyncclick import progressbar from asyncclick._termui_impl import ProgressBar def test_length_is_int() -> None: with progressbar(length=5) as bar: assert_type(bar, ProgressBar[int]) for i in bar: assert_type(i, int) def it() -> tuple[str, ...]: return ("hello", "world") def test_generic_on_iterable() -> None: with progressbar(it()) as bar: assert_type(bar, ProgressBar[str]) for s in bar: assert_type(s, str) asyncclick-8.3.0.5-async/tests/typing/typing_simple_example.py000066400000000000000000000010121507140761400245460ustar00rootroot00000000000000"""The simple example from https://github.com/pallets/click#a-simple-example.""" from typing_extensions import assert_type import asyncclick as click @click.command() @click.option("--count", default=1, help="Number of greetings.") @click.option("--name", prompt="Your name", help="The person to greet.") def hello(count: int, name: str) -> None: """Simple program that greets NAME for a total of COUNT times.""" for _ in range(count): click.echo(f"Hello, {name}!") assert_type(hello, click.Command) asyncclick-8.3.0.5-async/tests/typing/typing_version_option.py000066400000000000000000000004561507140761400246320ustar00rootroot00000000000000""" From https://click.palletsprojects.com/en/stable/options/#callbacks-and-eager-options. """ from typing_extensions import assert_type import asyncclick as click @click.command() @click.version_option("0.1") def hello() -> None: click.echo("Hello World!") assert_type(hello, click.Command) asyncclick-8.3.0.5-async/tox.ini000066400000000000000000000026601507140761400164470ustar00rootroot00000000000000[tox] envlist = py3{13,12,11,10,9} pypy310 style typing docs skip_missing_interpreters = true [testenv] package = wheel wheel_build_env = .pkg constrain_package_deps = true use_frozen_constraints = true deps = -r requirements/tests.txt commands = pytest -v --tb=short --basetemp={envtmpdir} {posargs} [testenv:py37,py3.7] deps = -r requirements/tests37.txt [testenv:style] deps = pre-commit skip_install = true commands = pre-commit run --all-files [testenv:typing] deps = -r requirements/typing.txt commands = mypy pyright tests/typing pyright --verifytypes asyncclick --ignoreexternal [testenv:docs] deps = -r requirements/docs.txt commands = sphinx-build -E -W -b dirhtml docs docs/_build/dirhtml [testenv:update-actions] labels = update deps = gha-update commands = gha-update [testenv:update-pre_commit] labels = update deps = pre-commit skip_install = true commands = pre-commit autoupdate -j4 [testenv:update-requirements] labels = update deps = pip-tools skip_install = true change_dir = requirements commands = pip-compile build.in -q {posargs:-U} pip-compile docs.in -q {posargs:-U} pip-compile tests.in -q {posargs:-U} pip-compile typing.in -q {posargs:-U} pip-compile dev.in -q {posargs:-U} [testenv:update-requirements37] base_python = 3.7 labels = update deps = pip-tools skip_install = true change_dir = requirements commands = pip-compile tests.in -q -o tests37.txt {posargs:-U} asyncclick-8.3.0.5-async/uv.lock000066400000000000000000004076221507140761400164470ustar00rootroot00000000000000version = 1 revision = 2 requires-python = ">=3.11" resolution-markers = [ "python_full_version >= '3.12'", "python_full_version < '3.12'", ] [[package]] name = "alabaster" version = "1.0.0" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/a6/f8/d9c74d0daf3f742840fd818d69cfae176fa332022fd44e3469487d5a9420/alabaster-1.0.0.tar.gz", hash = "sha256:c00dca57bca26fa62a6d7d0a9fcce65f3e026e9bfe33e9c538fd3fbb2144fd9e", size = 24210, upload-time = "2024-07-26T18:15:03.762Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/7e/b3/6b4067be973ae96ba0d615946e314c5ae35f9f993eca561b356540bb0c2b/alabaster-1.0.0-py3-none-any.whl", hash = "sha256:fc6786402dc3fcb2de3cabd5fe455a2db534b371124f1f21de8731783dec828b", size = 13929, upload-time = "2024-07-26T18:15:02.05Z" }, ] [[package]] name = "anyio" version = "4.9.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "idna" }, { name = "sniffio" }, { name = "typing-extensions", marker = "python_full_version < '3.13'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/95/7d/4c1bd541d4dffa1b52bd83fb8527089e097a106fc90b467a7313b105f840/anyio-4.9.0.tar.gz", hash = "sha256:673c0c244e15788651a4ff38710fea9675823028a6f08a5eda409e0c9840a028", size = 190949, upload-time = "2025-03-17T00:02:54.77Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/a1/ee/48ca1a7c89ffec8b6a0c5d02b89c305671d5ffd8d3c94acf8b8c408575bb/anyio-4.9.0-py3-none-any.whl", hash = "sha256:9f76d541cad6e36af7beb62e978876f3b41e3e04f2c1fbf0884604c0a9c4d93c", size = 100916, upload-time = "2025-03-17T00:02:52.713Z" }, ] [[package]] name = "asyncclick" version = "8.3.0.5" source = { editable = "." } dependencies = [ { name = "colorama", marker = "sys_platform == 'win32'" }, ] [package.dev-dependencies] anyio = [ { name = "anyio" }, ] dev = [ { name = "anyio" }, { name = "ruff" }, { name = "tox" }, { name = "tox-uv" }, { name = "trio" }, ] docs = [ { name = "myst-parser" }, { name = "pallets-sphinx-themes" }, { name = "sphinx" }, { name = "sphinx-tabs" }, { name = "sphinxcontrib-log-cabinet" }, ] docs-auto = [ { name = "sphinx-autobuild" }, ] gha-update = [ { name = "gha-update", marker = "python_full_version >= '3.12'" }, ] pre-commit = [ { name = "pre-commit" }, { name = "pre-commit-uv" }, ] tests = [ { name = "anyio" }, { name = "pytest" }, { name = "trio" }, ] trio = [ { name = "trio" }, ] typing = [ { name = "anyio" }, { name = "mypy" }, { name = "pyright" }, { name = "pytest" }, ] [package.metadata] requires-dist = [{ name = "colorama", marker = "sys_platform == 'win32'" }] [package.metadata.requires-dev] anyio = [{ name = "anyio", specifier = "~=4.0" }] dev = [ { name = "anyio" }, { name = "ruff" }, { name = "tox" }, { name = "tox-uv" }, { name = "trio" }, ] docs = [ { name = "myst-parser" }, { name = "pallets-sphinx-themes" }, { name = "sphinx" }, { name = "sphinx-tabs" }, { name = "sphinxcontrib-log-cabinet" }, ] docs-auto = [{ name = "sphinx-autobuild" }] gha-update = [{ name = "gha-update", marker = "python_full_version >= '3.12'" }] pre-commit = [ { name = "pre-commit" }, { name = "pre-commit-uv" }, ] tests = [ { name = "anyio" }, { name = "pytest" }, { name = "trio" }, ] trio = [{ name = "trio", specifier = "~=0.22" }] typing = [ { name = "anyio" }, { name = "mypy" }, { name = "pyright" }, { name = "pytest" }, ] [[package]] name = "attrs" version = "25.3.0" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/5a/b0/1367933a8532ee6ff8d63537de4f1177af4bff9f3e829baf7331f595bb24/attrs-25.3.0.tar.gz", hash = "sha256:75d7cefc7fb576747b2c81b4442d4d4a1ce0900973527c011d1030fd3bf4af1b", size = 812032, upload-time = "2025-03-13T11:10:22.779Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/77/06/bb80f5f86020c4551da315d78b3ab75e8228f89f0162f2c3a819e407941a/attrs-25.3.0-py3-none-any.whl", hash = "sha256:427318ce031701fea540783410126f03899a97ffc6f61596ad581ac2e40e3bc3", size = 63815, upload-time = "2025-03-13T11:10:21.14Z" }, ] [[package]] name = "babel" version = "2.17.0" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/7d/6b/d52e42361e1aa00709585ecc30b3f9684b3ab62530771402248b1b1d6240/babel-2.17.0.tar.gz", hash = "sha256:0c54cffb19f690cdcc52a3b50bcbf71e07a808d1c80d549f2459b9d2cf0afb9d", size = 9951852, upload-time = "2025-02-01T15:17:41.026Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/b7/b8/3fe70c75fe32afc4bb507f75563d39bc5642255d1d94f1f23604725780bf/babel-2.17.0-py3-none-any.whl", hash = "sha256:4d0b53093fdfb4b21c92b5213dba5a1b23885afa8383709427046b21c366e5f2", size = 10182537, upload-time = "2025-02-01T15:17:37.39Z" }, ] [[package]] name = "cachetools" version = "6.0.0" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/c0/b0/f539a1ddff36644c28a61490056e5bae43bd7386d9f9c69beae2d7e7d6d1/cachetools-6.0.0.tar.gz", hash = "sha256:f225782b84438f828328fc2ad74346522f27e5b1440f4e9fd18b20ebfd1aa2cf", size = 30160, upload-time = "2025-05-23T20:01:13.076Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/6a/c3/8bb087c903c95a570015ce84e0c23ae1d79f528c349cbc141b5c4e250293/cachetools-6.0.0-py3-none-any.whl", hash = "sha256:82e73ba88f7b30228b5507dce1a1f878498fc669d972aef2dde4f3a3c24f103e", size = 10964, upload-time = "2025-05-23T20:01:11.323Z" }, ] [[package]] name = "certifi" version = "2025.4.26" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/e8/9e/c05b3920a3b7d20d3d3310465f50348e5b3694f4f88c6daf736eef3024c4/certifi-2025.4.26.tar.gz", hash = "sha256:0a816057ea3cdefcef70270d2c515e4506bbc954f417fa5ade2021213bb8f0c6", size = 160705, upload-time = "2025-04-26T02:12:29.51Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/4a/7e/3db2bd1b1f9e95f7cddca6d6e75e2f2bd9f51b1246e546d88addca0106bd/certifi-2025.4.26-py3-none-any.whl", hash = "sha256:30350364dfe371162649852c63336a15c70c6510c2ad5015b21c2345311805f3", size = 159618, upload-time = "2025-04-26T02:12:27.662Z" }, ] [[package]] name = "cffi" version = "2.0.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "pycparser", marker = "implementation_name != 'PyPy'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/eb/56/b1ba7935a17738ae8453301356628e8147c79dbb825bcbc73dc7401f9846/cffi-2.0.0.tar.gz", hash = "sha256:44d1b5909021139fe36001ae048dbdde8214afa20200eda0f64c068cac5d5529", size = 523588, upload-time = "2025-09-08T23:24:04.541Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/2b/c0/015b25184413d7ab0a410775fdb4a50fca20f5589b5dab1dbbfa3baad8ce/cffi-2.0.0-cp311-cp311-win32.whl", hash = "sha256:c649e3a33450ec82378822b3dad03cc228b8f5963c0c12fc3b1e0ab940f768a5", size = 172076, upload-time = "2025-09-08T23:22:40.95Z" }, { url = "https://files.pythonhosted.org/packages/ae/8f/dc5531155e7070361eb1b7e4c1a9d896d0cb21c49f807a6c03fd63fc877e/cffi-2.0.0-cp311-cp311-win_amd64.whl", hash = "sha256:66f011380d0e49ed280c789fbd08ff0d40968ee7b665575489afa95c98196ab5", size = 182820, upload-time = "2025-09-08T23:22:42.463Z" }, { url = "https://files.pythonhosted.org/packages/95/5c/1b493356429f9aecfd56bc171285a4c4ac8697f76e9bbbbb105e537853a1/cffi-2.0.0-cp311-cp311-win_arm64.whl", hash = "sha256:c6638687455baf640e37344fe26d37c404db8b80d037c3d29f58fe8d1c3b194d", size = 177635, upload-time = "2025-09-08T23:22:43.623Z" }, { url = "https://files.pythonhosted.org/packages/7b/2b/2b6435f76bfeb6bbf055596976da087377ede68df465419d192acf00c437/cffi-2.0.0-cp312-cp312-win32.whl", hash = "sha256:da902562c3e9c550df360bfa53c035b2f241fed6d9aef119048073680ace4a18", size = 172932, upload-time = "2025-09-08T23:22:57.188Z" }, { url = "https://files.pythonhosted.org/packages/f8/ed/13bd4418627013bec4ed6e54283b1959cf6db888048c7cf4b4c3b5b36002/cffi-2.0.0-cp312-cp312-win_amd64.whl", hash = "sha256:da68248800ad6320861f129cd9c1bf96ca849a2771a59e0344e88681905916f5", size = 183557, upload-time = "2025-09-08T23:22:58.351Z" }, { url = "https://files.pythonhosted.org/packages/95/31/9f7f93ad2f8eff1dbc1c3656d7ca5bfd8fb52c9d786b4dcf19b2d02217fa/cffi-2.0.0-cp312-cp312-win_arm64.whl", hash = "sha256:4671d9dd5ec934cb9a73e7ee9676f9362aba54f7f34910956b84d727b0d73fb6", size = 177762, upload-time = "2025-09-08T23:22:59.668Z" }, { url = "https://files.pythonhosted.org/packages/eb/6d/bf9bda840d5f1dfdbf0feca87fbdb64a918a69bca42cfa0ba7b137c48cb8/cffi-2.0.0-cp313-cp313-win32.whl", hash = "sha256:74a03b9698e198d47562765773b4a8309919089150a0bb17d829ad7b44b60d27", size = 172909, upload-time = "2025-09-08T23:23:14.32Z" }, { url = "https://files.pythonhosted.org/packages/37/18/6519e1ee6f5a1e579e04b9ddb6f1676c17368a7aba48299c3759bbc3c8b3/cffi-2.0.0-cp313-cp313-win_amd64.whl", hash = "sha256:19f705ada2530c1167abacb171925dd886168931e0a7b78f5bffcae5c6b5be75", size = 183402, upload-time = "2025-09-08T23:23:15.535Z" }, { url = "https://files.pythonhosted.org/packages/cb/0e/02ceeec9a7d6ee63bb596121c2c8e9b3a9e150936f4fbef6ca1943e6137c/cffi-2.0.0-cp313-cp313-win_arm64.whl", hash = "sha256:256f80b80ca3853f90c21b23ee78cd008713787b1b1e93eae9f3d6a7134abd91", size = 177780, upload-time = "2025-09-08T23:23:16.761Z" }, { url = "https://files.pythonhosted.org/packages/3e/aa/df335faa45b395396fcbc03de2dfcab242cd61a9900e914fe682a59170b1/cffi-2.0.0-cp314-cp314-win32.whl", hash = "sha256:087067fa8953339c723661eda6b54bc98c5625757ea62e95eb4898ad5e776e9f", size = 175328, upload-time = "2025-09-08T23:23:44.61Z" }, { url = "https://files.pythonhosted.org/packages/bb/92/882c2d30831744296ce713f0feb4c1cd30f346ef747b530b5318715cc367/cffi-2.0.0-cp314-cp314-win_amd64.whl", hash = "sha256:203a48d1fb583fc7d78a4c6655692963b860a417c0528492a6bc21f1aaefab25", size = 185650, upload-time = "2025-09-08T23:23:45.848Z" }, { url = "https://files.pythonhosted.org/packages/9f/2c/98ece204b9d35a7366b5b2c6539c350313ca13932143e79dc133ba757104/cffi-2.0.0-cp314-cp314-win_arm64.whl", hash = "sha256:dbd5c7a25a7cb98f5ca55d258b103a2054f859a46ae11aaf23134f9cc0d356ad", size = 180687, upload-time = "2025-09-08T23:23:47.105Z" }, { url = "https://files.pythonhosted.org/packages/a0/1d/ec1a60bd1a10daa292d3cd6bb0b359a81607154fb8165f3ec95fe003b85c/cffi-2.0.0-cp314-cp314t-win32.whl", hash = "sha256:1fc9ea04857caf665289b7a75923f2c6ed559b8298a1b8c49e59f7dd95c8481e", size = 180487, upload-time = "2025-09-08T23:23:40.423Z" }, { url = "https://files.pythonhosted.org/packages/bf/41/4c1168c74fac325c0c8156f04b6749c8b6a8f405bbf91413ba088359f60d/cffi-2.0.0-cp314-cp314t-win_amd64.whl", hash = "sha256:d68b6cef7827e8641e8ef16f4494edda8b36104d79773a334beaa1e3521430f6", size = 191726, upload-time = "2025-09-08T23:23:41.742Z" }, { url = "https://files.pythonhosted.org/packages/ae/3a/dbeec9d1ee0844c679f6bb5d6ad4e9f198b1224f4e7a32825f47f6192b0c/cffi-2.0.0-cp314-cp314t-win_arm64.whl", hash = "sha256:0a1527a803f0a659de1af2e1fd700213caba79377e27e4693648c2923da066f9", size = 184195, upload-time = "2025-09-08T23:23:43.004Z" }, ] [[package]] name = "cfgv" version = "3.4.0" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/11/74/539e56497d9bd1d484fd863dd69cbbfa653cd2aa27abfe35653494d85e94/cfgv-3.4.0.tar.gz", hash = "sha256:e52591d4c5f5dead8e0f673fb16db7949d2cfb3f7da4582893288f0ded8fe560", size = 7114, upload-time = "2023-08-12T20:38:17.776Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/c5/55/51844dd50c4fc7a33b653bfaba4c2456f06955289ca770a5dbd5fd267374/cfgv-3.4.0-py2.py3-none-any.whl", hash = "sha256:b7265b1f29fd3316bfcd2b330d63d024f2bfd8bcb8b0272f8e19a504856c48f9", size = 7249, upload-time = "2023-08-12T20:38:16.269Z" }, ] [[package]] name = "chardet" version = "5.2.0" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/f3/0d/f7b6ab21ec75897ed80c17d79b15951a719226b9fababf1e40ea74d69079/chardet-5.2.0.tar.gz", hash = "sha256:1b3b6ff479a8c414bc3fa2c0852995695c4a026dcd6d0633b2dd092ca39c1cf7", size = 2069618, upload-time = "2023-08-01T19:23:02.662Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/38/6f/f5fbc992a329ee4e0f288c1fe0e2ad9485ed064cac731ed2fe47dcc38cbf/chardet-5.2.0-py3-none-any.whl", hash = "sha256:e1cf59446890a00105fe7b7912492ea04b6e6f06d4b742b2c788469e34c82970", size = 199385, upload-time = "2023-08-01T19:23:00.661Z" }, ] [[package]] name = "charset-normalizer" version = "3.4.2" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/e4/33/89c2ced2b67d1c2a61c19c6751aa8902d46ce3dacb23600a283619f5a12d/charset_normalizer-3.4.2.tar.gz", hash = "sha256:5baececa9ecba31eff645232d59845c07aa030f0c81ee70184a90d35099a0e63", size = 126367, upload-time = "2025-05-02T08:34:42.01Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/05/85/4c40d00dcc6284a1c1ad5de5e0996b06f39d8232f1031cd23c2f5c07ee86/charset_normalizer-3.4.2-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:be1e352acbe3c78727a16a455126d9ff83ea2dfdcbc83148d2982305a04714c2", size = 198794, upload-time = "2025-05-02T08:32:11.945Z" }, { url = "https://files.pythonhosted.org/packages/41/d9/7a6c0b9db952598e97e93cbdfcb91bacd89b9b88c7c983250a77c008703c/charset_normalizer-3.4.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:aa88ca0b1932e93f2d961bf3addbb2db902198dca337d88c89e1559e066e7645", size = 142846, upload-time = "2025-05-02T08:32:13.946Z" }, { url = "https://files.pythonhosted.org/packages/66/82/a37989cda2ace7e37f36c1a8ed16c58cf48965a79c2142713244bf945c89/charset_normalizer-3.4.2-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:d524ba3f1581b35c03cb42beebab4a13e6cdad7b36246bd22541fa585a56cccd", size = 153350, upload-time = "2025-05-02T08:32:15.873Z" }, { url = "https://files.pythonhosted.org/packages/df/68/a576b31b694d07b53807269d05ec3f6f1093e9545e8607121995ba7a8313/charset_normalizer-3.4.2-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:28a1005facc94196e1fb3e82a3d442a9d9110b8434fc1ded7a24a2983c9888d8", size = 145657, upload-time = "2025-05-02T08:32:17.283Z" }, { url = "https://files.pythonhosted.org/packages/92/9b/ad67f03d74554bed3aefd56fe836e1623a50780f7c998d00ca128924a499/charset_normalizer-3.4.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fdb20a30fe1175ecabed17cbf7812f7b804b8a315a25f24678bcdf120a90077f", size = 147260, upload-time = "2025-05-02T08:32:18.807Z" }, { url = "https://files.pythonhosted.org/packages/a6/e6/8aebae25e328160b20e31a7e9929b1578bbdc7f42e66f46595a432f8539e/charset_normalizer-3.4.2-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:0f5d9ed7f254402c9e7d35d2f5972c9bbea9040e99cd2861bd77dc68263277c7", size = 149164, upload-time = "2025-05-02T08:32:20.333Z" }, { url = "https://files.pythonhosted.org/packages/8b/f2/b3c2f07dbcc248805f10e67a0262c93308cfa149a4cd3d1fe01f593e5fd2/charset_normalizer-3.4.2-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:efd387a49825780ff861998cd959767800d54f8308936b21025326de4b5a42b9", size = 144571, upload-time = "2025-05-02T08:32:21.86Z" }, { url = "https://files.pythonhosted.org/packages/60/5b/c3f3a94bc345bc211622ea59b4bed9ae63c00920e2e8f11824aa5708e8b7/charset_normalizer-3.4.2-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:f0aa37f3c979cf2546b73e8222bbfa3dc07a641585340179d768068e3455e544", size = 151952, upload-time = "2025-05-02T08:32:23.434Z" }, { url = "https://files.pythonhosted.org/packages/e2/4d/ff460c8b474122334c2fa394a3f99a04cf11c646da895f81402ae54f5c42/charset_normalizer-3.4.2-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:e70e990b2137b29dc5564715de1e12701815dacc1d056308e2b17e9095372a82", size = 155959, upload-time = "2025-05-02T08:32:24.993Z" }, { url = "https://files.pythonhosted.org/packages/a2/2b/b964c6a2fda88611a1fe3d4c400d39c66a42d6c169c924818c848f922415/charset_normalizer-3.4.2-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:0c8c57f84ccfc871a48a47321cfa49ae1df56cd1d965a09abe84066f6853b9c0", size = 153030, upload-time = "2025-05-02T08:32:26.435Z" }, { url = "https://files.pythonhosted.org/packages/59/2e/d3b9811db26a5ebf444bc0fa4f4be5aa6d76fc6e1c0fd537b16c14e849b6/charset_normalizer-3.4.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:6b66f92b17849b85cad91259efc341dce9c1af48e2173bf38a85c6329f1033e5", size = 148015, upload-time = "2025-05-02T08:32:28.376Z" }, { url = "https://files.pythonhosted.org/packages/90/07/c5fd7c11eafd561bb51220d600a788f1c8d77c5eef37ee49454cc5c35575/charset_normalizer-3.4.2-cp311-cp311-win32.whl", hash = "sha256:daac4765328a919a805fa5e2720f3e94767abd632ae410a9062dff5412bae65a", size = 98106, upload-time = "2025-05-02T08:32:30.281Z" }, { url = "https://files.pythonhosted.org/packages/a8/05/5e33dbef7e2f773d672b6d79f10ec633d4a71cd96db6673625838a4fd532/charset_normalizer-3.4.2-cp311-cp311-win_amd64.whl", hash = "sha256:e53efc7c7cee4c1e70661e2e112ca46a575f90ed9ae3fef200f2a25e954f4b28", size = 105402, upload-time = "2025-05-02T08:32:32.191Z" }, { url = "https://files.pythonhosted.org/packages/d7/a4/37f4d6035c89cac7930395a35cc0f1b872e652eaafb76a6075943754f095/charset_normalizer-3.4.2-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:0c29de6a1a95f24b9a1aa7aefd27d2487263f00dfd55a77719b530788f75cff7", size = 199936, upload-time = "2025-05-02T08:32:33.712Z" }, { url = "https://files.pythonhosted.org/packages/ee/8a/1a5e33b73e0d9287274f899d967907cd0bf9c343e651755d9307e0dbf2b3/charset_normalizer-3.4.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:cddf7bd982eaa998934a91f69d182aec997c6c468898efe6679af88283b498d3", size = 143790, upload-time = "2025-05-02T08:32:35.768Z" }, { url = "https://files.pythonhosted.org/packages/66/52/59521f1d8e6ab1482164fa21409c5ef44da3e9f653c13ba71becdd98dec3/charset_normalizer-3.4.2-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:fcbe676a55d7445b22c10967bceaaf0ee69407fbe0ece4d032b6eb8d4565982a", size = 153924, upload-time = "2025-05-02T08:32:37.284Z" }, { url = "https://files.pythonhosted.org/packages/86/2d/fb55fdf41964ec782febbf33cb64be480a6b8f16ded2dbe8db27a405c09f/charset_normalizer-3.4.2-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:d41c4d287cfc69060fa91cae9683eacffad989f1a10811995fa309df656ec214", size = 146626, upload-time = "2025-05-02T08:32:38.803Z" }, { url = "https://files.pythonhosted.org/packages/8c/73/6ede2ec59bce19b3edf4209d70004253ec5f4e319f9a2e3f2f15601ed5f7/charset_normalizer-3.4.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4e594135de17ab3866138f496755f302b72157d115086d100c3f19370839dd3a", size = 148567, upload-time = "2025-05-02T08:32:40.251Z" }, { url = "https://files.pythonhosted.org/packages/09/14/957d03c6dc343c04904530b6bef4e5efae5ec7d7990a7cbb868e4595ee30/charset_normalizer-3.4.2-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:cf713fe9a71ef6fd5adf7a79670135081cd4431c2943864757f0fa3a65b1fafd", size = 150957, upload-time = "2025-05-02T08:32:41.705Z" }, { url = "https://files.pythonhosted.org/packages/0d/c8/8174d0e5c10ccebdcb1b53cc959591c4c722a3ad92461a273e86b9f5a302/charset_normalizer-3.4.2-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:a370b3e078e418187da8c3674eddb9d983ec09445c99a3a263c2011993522981", size = 145408, upload-time = "2025-05-02T08:32:43.709Z" }, { url = "https://files.pythonhosted.org/packages/58/aa/8904b84bc8084ac19dc52feb4f5952c6df03ffb460a887b42615ee1382e8/charset_normalizer-3.4.2-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:a955b438e62efdf7e0b7b52a64dc5c3396e2634baa62471768a64bc2adb73d5c", size = 153399, upload-time = "2025-05-02T08:32:46.197Z" }, { url = "https://files.pythonhosted.org/packages/c2/26/89ee1f0e264d201cb65cf054aca6038c03b1a0c6b4ae998070392a3ce605/charset_normalizer-3.4.2-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:7222ffd5e4de8e57e03ce2cef95a4c43c98fcb72ad86909abdfc2c17d227fc1b", size = 156815, upload-time = "2025-05-02T08:32:48.105Z" }, { url = "https://files.pythonhosted.org/packages/fd/07/68e95b4b345bad3dbbd3a8681737b4338ff2c9df29856a6d6d23ac4c73cb/charset_normalizer-3.4.2-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:bee093bf902e1d8fc0ac143c88902c3dfc8941f7ea1d6a8dd2bcb786d33db03d", size = 154537, upload-time = "2025-05-02T08:32:49.719Z" }, { url = "https://files.pythonhosted.org/packages/77/1a/5eefc0ce04affb98af07bc05f3bac9094513c0e23b0562d64af46a06aae4/charset_normalizer-3.4.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:dedb8adb91d11846ee08bec4c8236c8549ac721c245678282dcb06b221aab59f", size = 149565, upload-time = "2025-05-02T08:32:51.404Z" }, { url = "https://files.pythonhosted.org/packages/37/a0/2410e5e6032a174c95e0806b1a6585eb21e12f445ebe239fac441995226a/charset_normalizer-3.4.2-cp312-cp312-win32.whl", hash = "sha256:db4c7bf0e07fc3b7d89ac2a5880a6a8062056801b83ff56d8464b70f65482b6c", size = 98357, upload-time = "2025-05-02T08:32:53.079Z" }, { url = "https://files.pythonhosted.org/packages/6c/4f/c02d5c493967af3eda9c771ad4d2bbc8df6f99ddbeb37ceea6e8716a32bc/charset_normalizer-3.4.2-cp312-cp312-win_amd64.whl", hash = "sha256:5a9979887252a82fefd3d3ed2a8e3b937a7a809f65dcb1e068b090e165bbe99e", size = 105776, upload-time = "2025-05-02T08:32:54.573Z" }, { url = "https://files.pythonhosted.org/packages/ea/12/a93df3366ed32db1d907d7593a94f1fe6293903e3e92967bebd6950ed12c/charset_normalizer-3.4.2-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:926ca93accd5d36ccdabd803392ddc3e03e6d4cd1cf17deff3b989ab8e9dbcf0", size = 199622, upload-time = "2025-05-02T08:32:56.363Z" }, { url = "https://files.pythonhosted.org/packages/04/93/bf204e6f344c39d9937d3c13c8cd5bbfc266472e51fc8c07cb7f64fcd2de/charset_normalizer-3.4.2-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:eba9904b0f38a143592d9fc0e19e2df0fa2e41c3c3745554761c5f6447eedabf", size = 143435, upload-time = "2025-05-02T08:32:58.551Z" }, { url = "https://files.pythonhosted.org/packages/22/2a/ea8a2095b0bafa6c5b5a55ffdc2f924455233ee7b91c69b7edfcc9e02284/charset_normalizer-3.4.2-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:3fddb7e2c84ac87ac3a947cb4e66d143ca5863ef48e4a5ecb83bd48619e4634e", size = 153653, upload-time = "2025-05-02T08:33:00.342Z" }, { url = "https://files.pythonhosted.org/packages/b6/57/1b090ff183d13cef485dfbe272e2fe57622a76694061353c59da52c9a659/charset_normalizer-3.4.2-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:98f862da73774290f251b9df8d11161b6cf25b599a66baf087c1ffe340e9bfd1", size = 146231, upload-time = "2025-05-02T08:33:02.081Z" }, { url = "https://files.pythonhosted.org/packages/e2/28/ffc026b26f441fc67bd21ab7f03b313ab3fe46714a14b516f931abe1a2d8/charset_normalizer-3.4.2-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6c9379d65defcab82d07b2a9dfbfc2e95bc8fe0ebb1b176a3190230a3ef0e07c", size = 148243, upload-time = "2025-05-02T08:33:04.063Z" }, { url = "https://files.pythonhosted.org/packages/c0/0f/9abe9bd191629c33e69e47c6ef45ef99773320e9ad8e9cb08b8ab4a8d4cb/charset_normalizer-3.4.2-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:e635b87f01ebc977342e2697d05b56632f5f879a4f15955dfe8cef2448b51691", size = 150442, upload-time = "2025-05-02T08:33:06.418Z" }, { url = "https://files.pythonhosted.org/packages/67/7c/a123bbcedca91d5916c056407f89a7f5e8fdfce12ba825d7d6b9954a1a3c/charset_normalizer-3.4.2-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:1c95a1e2902a8b722868587c0e1184ad5c55631de5afc0eb96bc4b0d738092c0", size = 145147, upload-time = "2025-05-02T08:33:08.183Z" }, { url = "https://files.pythonhosted.org/packages/ec/fe/1ac556fa4899d967b83e9893788e86b6af4d83e4726511eaaad035e36595/charset_normalizer-3.4.2-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:ef8de666d6179b009dce7bcb2ad4c4a779f113f12caf8dc77f0162c29d20490b", size = 153057, upload-time = "2025-05-02T08:33:09.986Z" }, { url = "https://files.pythonhosted.org/packages/2b/ff/acfc0b0a70b19e3e54febdd5301a98b72fa07635e56f24f60502e954c461/charset_normalizer-3.4.2-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:32fc0341d72e0f73f80acb0a2c94216bd704f4f0bce10aedea38f30502b271ff", size = 156454, upload-time = "2025-05-02T08:33:11.814Z" }, { url = "https://files.pythonhosted.org/packages/92/08/95b458ce9c740d0645feb0e96cea1f5ec946ea9c580a94adfe0b617f3573/charset_normalizer-3.4.2-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:289200a18fa698949d2b39c671c2cc7a24d44096784e76614899a7ccf2574b7b", size = 154174, upload-time = "2025-05-02T08:33:13.707Z" }, { url = "https://files.pythonhosted.org/packages/78/be/8392efc43487ac051eee6c36d5fbd63032d78f7728cb37aebcc98191f1ff/charset_normalizer-3.4.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:4a476b06fbcf359ad25d34a057b7219281286ae2477cc5ff5e3f70a246971148", size = 149166, upload-time = "2025-05-02T08:33:15.458Z" }, { url = "https://files.pythonhosted.org/packages/44/96/392abd49b094d30b91d9fbda6a69519e95802250b777841cf3bda8fe136c/charset_normalizer-3.4.2-cp313-cp313-win32.whl", hash = "sha256:aaeeb6a479c7667fbe1099af9617c83aaca22182d6cf8c53966491a0f1b7ffb7", size = 98064, upload-time = "2025-05-02T08:33:17.06Z" }, { url = "https://files.pythonhosted.org/packages/e9/b0/0200da600134e001d91851ddc797809e2fe0ea72de90e09bec5a2fbdaccb/charset_normalizer-3.4.2-cp313-cp313-win_amd64.whl", hash = "sha256:aa6af9e7d59f9c12b33ae4e9450619cf2488e2bbe9b44030905877f0b2324980", size = 105641, upload-time = "2025-05-02T08:33:18.753Z" }, { url = "https://files.pythonhosted.org/packages/20/94/c5790835a017658cbfabd07f3bfb549140c3ac458cfc196323996b10095a/charset_normalizer-3.4.2-py3-none-any.whl", hash = "sha256:7f56930ab0abd1c45cd15be65cc741c28b1c9a34876ce8c17a2fa107810c0af0", size = 52626, upload-time = "2025-05-02T08:34:40.053Z" }, ] [[package]] name = "click" version = "8.3.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "colorama", marker = "sys_platform == 'win32'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/46/61/de6cd827efad202d7057d93e0fed9294b96952e188f7384832791c7b2254/click-8.3.0.tar.gz", hash = "sha256:e7b8232224eba16f4ebe410c25ced9f7875cb5f3263ffc93cc3e8da705e229c4", size = 276943, upload-time = "2025-09-18T17:32:23.696Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/db/d3/9dcc0f5797f070ec8edf30fbadfb200e71d9db6b84d211e3b2085a7589a0/click-8.3.0-py3-none-any.whl", hash = "sha256:9b9f285302c6e3064f4330c05f05b81945b2a39544279343e6e7c5f27a9baddc", size = 107295, upload-time = "2025-09-18T17:32:22.42Z" }, ] [[package]] name = "colorama" version = "0.4.6" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/d8/53/6f443c9a4a8358a93a6792e2acffb9d9d5cb0a5cfd8802644b7b1c9a02e4/colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44", size = 27697, upload-time = "2022-10-25T02:36:22.414Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" }, ] [[package]] name = "distlib" version = "0.3.9" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/0d/dd/1bec4c5ddb504ca60fc29472f3d27e8d4da1257a854e1d96742f15c1d02d/distlib-0.3.9.tar.gz", hash = "sha256:a60f20dea646b8a33f3e7772f74dc0b2d0772d2837ee1342a00645c81edf9403", size = 613923, upload-time = "2024-10-09T18:35:47.551Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/91/a1/cf2472db20f7ce4a6be1253a81cfdf85ad9c7885ffbed7047fb72c24cf87/distlib-0.3.9-py2.py3-none-any.whl", hash = "sha256:47f8c22fd27c27e25a65601af709b38e4f0a45ea4fc2e710f65755fa8caaaf87", size = 468973, upload-time = "2024-10-09T18:35:44.272Z" }, ] [[package]] name = "docutils" version = "0.21.2" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/ae/ed/aefcc8cd0ba62a0560c3c18c33925362d46c6075480bfa4df87b28e169a9/docutils-0.21.2.tar.gz", hash = "sha256:3a6b18732edf182daa3cd12775bbb338cf5691468f91eeeb109deff6ebfa986f", size = 2204444, upload-time = "2024-04-23T18:57:18.24Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/8f/d7/9322c609343d929e75e7e5e6255e614fcc67572cfd083959cdef3b7aad79/docutils-0.21.2-py3-none-any.whl", hash = "sha256:dafca5b9e384f0e419294eb4d2ff9fa826435bf15f15b7bd45723e8ad76811b2", size = 587408, upload-time = "2024-04-23T18:57:14.835Z" }, ] [[package]] name = "filelock" version = "3.18.0" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/0a/10/c23352565a6544bdc5353e0b15fc1c563352101f30e24bf500207a54df9a/filelock-3.18.0.tar.gz", hash = "sha256:adbc88eabb99d2fec8c9c1b229b171f18afa655400173ddc653d5d01501fb9f2", size = 18075, upload-time = "2025-03-14T07:11:40.47Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/4d/36/2a115987e2d8c300a974597416d9de88f2444426de9571f4b59b2cca3acc/filelock-3.18.0-py3-none-any.whl", hash = "sha256:c401f4f8377c4464e6db25fff06205fd89bdd83b65eb0488ed1b160f780e21de", size = 16215, upload-time = "2025-03-14T07:11:39.145Z" }, ] [[package]] name = "gha-update" version = "0.1.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "click", marker = "python_full_version >= '3.12'" }, { name = "httpx", marker = "python_full_version >= '3.12'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/d5/ac/f1b6699a529bd298a777199861a8232590bb612eac92e15bf1033134f123/gha_update-0.1.0.tar.gz", hash = "sha256:8c0f55ed7bdc11fb061d67984814fd642bd3a1872028e34c15c913cd59202d53", size = 3345, upload-time = "2024-08-23T20:58:42.478Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/98/06/832338d1b5f82f17e1f4985146d81050cd2709ea54dab3f15b343ad227cc/gha_update-0.1.0-py3-none-any.whl", hash = "sha256:ec110088749eed66b5f55cc7f15f41a6af037446a5ac6a435b0768a57d52e087", size = 4513, upload-time = "2024-08-23T20:58:41.364Z" }, ] [[package]] name = "h11" version = "0.16.0" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/01/ee/02a2c011bdab74c6fb3c75474d40b3052059d95df7e73351460c8588d963/h11-0.16.0.tar.gz", hash = "sha256:4e35b956cf45792e4caa5885e69fba00bdbc6ffafbfa020300e549b208ee5ff1", size = 101250, upload-time = "2025-04-24T03:35:25.427Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/04/4b/29cac41a4d98d144bf5f6d33995617b185d14b22401f75ca86f384e87ff1/h11-0.16.0-py3-none-any.whl", hash = "sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86", size = 37515, upload-time = "2025-04-24T03:35:24.344Z" }, ] [[package]] name = "httpcore" version = "1.0.9" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "certifi", marker = "python_full_version >= '3.12'" }, { name = "h11", marker = "python_full_version >= '3.12'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/06/94/82699a10bca87a5556c9c59b5963f2d039dbd239f25bc2a63907a05a14cb/httpcore-1.0.9.tar.gz", hash = "sha256:6e34463af53fd2ab5d807f399a9b45ea31c3dfa2276f15a2c3f00afff6e176e8", size = 85484, upload-time = "2025-04-24T22:06:22.219Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/7e/f5/f66802a942d491edb555dd61e3a9961140fd64c90bce1eafd741609d334d/httpcore-1.0.9-py3-none-any.whl", hash = "sha256:2d400746a40668fc9dec9810239072b40b4484b640a8c38fd654a024c7a1bf55", size = 78784, upload-time = "2025-04-24T22:06:20.566Z" }, ] [[package]] name = "httpx" version = "0.28.1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "anyio", marker = "python_full_version >= '3.12'" }, { name = "certifi", marker = "python_full_version >= '3.12'" }, { name = "httpcore", marker = "python_full_version >= '3.12'" }, { name = "idna", marker = "python_full_version >= '3.12'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/b1/df/48c586a5fe32a0f01324ee087459e112ebb7224f646c0b5023f5e79e9956/httpx-0.28.1.tar.gz", hash = "sha256:75e98c5f16b0f35b567856f597f06ff2270a374470a5c2392242528e3e3e42fc", size = 141406, upload-time = "2024-12-06T15:37:23.222Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/2a/39/e50c7c3a983047577ee07d2a9e53faf5a69493943ec3f6a384bdc792deb2/httpx-0.28.1-py3-none-any.whl", hash = "sha256:d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59ad", size = 73517, upload-time = "2024-12-06T15:37:21.509Z" }, ] [[package]] name = "identify" version = "2.6.12" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/a2/88/d193a27416618628a5eea64e3223acd800b40749a96ffb322a9b55a49ed1/identify-2.6.12.tar.gz", hash = "sha256:d8de45749f1efb108badef65ee8386f0f7bb19a7f26185f74de6367bffbaf0e6", size = 99254, upload-time = "2025-05-23T20:37:53.3Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/7a/cd/18f8da995b658420625f7ef13f037be53ae04ec5ad33f9b718240dcfd48c/identify-2.6.12-py2.py3-none-any.whl", hash = "sha256:ad9672d5a72e0d2ff7c5c8809b62dfa60458626352fb0eb7b55e69bdc45334a2", size = 99145, upload-time = "2025-05-23T20:37:51.495Z" }, ] [[package]] name = "idna" version = "3.10" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/f1/70/7703c29685631f5a7590aa73f1f1d3fa9a380e654b86af429e0934a32f7d/idna-3.10.tar.gz", hash = "sha256:12f65c9b470abda6dc35cf8e63cc574b1c52b11df2c86030af0ac09b01b13ea9", size = 190490, upload-time = "2024-09-15T18:07:39.745Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/76/c6/c88e154df9c4e1a2a66ccf0005a88dfb2650c1dffb6f5ce603dfbd452ce3/idna-3.10-py3-none-any.whl", hash = "sha256:946d195a0d259cbba61165e88e65941f16e9b36ea6ddb97f00452bae8b1287d3", size = 70442, upload-time = "2024-09-15T18:07:37.964Z" }, ] [[package]] name = "imagesize" version = "1.4.1" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/a7/84/62473fb57d61e31fef6e36d64a179c8781605429fd927b5dd608c997be31/imagesize-1.4.1.tar.gz", hash = "sha256:69150444affb9cb0d5cc5a92b3676f0b2fb7cd9ae39e947a5e11a36b4497cd4a", size = 1280026, upload-time = "2022-07-01T12:21:05.687Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/ff/62/85c4c919272577931d407be5ba5d71c20f0b616d31a0befe0ae45bb79abd/imagesize-1.4.1-py2.py3-none-any.whl", hash = "sha256:0d8d18d08f840c19d0ee7ca1fd82490fdc3729b7ac93f49870406ddde8ef8d8b", size = 8769, upload-time = "2022-07-01T12:21:02.467Z" }, ] [[package]] name = "iniconfig" version = "2.1.0" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/f2/97/ebf4da567aa6827c909642694d71c9fcf53e5b504f2d96afea02718862f3/iniconfig-2.1.0.tar.gz", hash = "sha256:3abbd2e30b36733fee78f9c7f7308f2d0050e88f0087fd25c2645f63c773e1c7", size = 4793, upload-time = "2025-03-19T20:09:59.721Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/2c/e1/e6716421ea10d38022b952c159d5161ca1193197fb744506875fbb87ea7b/iniconfig-2.1.0-py3-none-any.whl", hash = "sha256:9deba5723312380e77435581c6bf4935c94cbfab9b1ed33ef8d238ea168eb760", size = 6050, upload-time = "2025-03-19T20:10:01.071Z" }, ] [[package]] name = "jinja2" version = "3.1.6" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "markupsafe" }, ] sdist = { url = "https://files.pythonhosted.org/packages/df/bf/f7da0350254c0ed7c72f3e33cef02e048281fec7ecec5f032d4aac52226b/jinja2-3.1.6.tar.gz", hash = "sha256:0137fb05990d35f1275a587e9aee6d56da821fc83491a0fb838183be43f66d6d", size = 245115, upload-time = "2025-03-05T20:05:02.478Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/62/a1/3d680cbfd5f4b8f15abc1d571870c5fc3e594bb582bc3b64ea099db13e56/jinja2-3.1.6-py3-none-any.whl", hash = "sha256:85ece4451f492d0c13c5dd7c13a64681a86afae63a5f347908daf103ce6d2f67", size = 134899, upload-time = "2025-03-05T20:05:00.369Z" }, ] [[package]] name = "markdown-it-py" version = "3.0.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "mdurl" }, ] sdist = { url = "https://files.pythonhosted.org/packages/38/71/3b932df36c1a044d397a1f92d1cf91ee0a503d91e470cbd670aa66b07ed0/markdown-it-py-3.0.0.tar.gz", hash = "sha256:e3f60a94fa066dc52ec76661e37c851cb232d92f9886b15cb560aaada2df8feb", size = 74596, upload-time = "2023-06-03T06:41:14.443Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/42/d7/1ec15b46af6af88f19b8e5ffea08fa375d433c998b8a7639e76935c14f1f/markdown_it_py-3.0.0-py3-none-any.whl", hash = "sha256:355216845c60bd96232cd8d8c40e8f9765cc86f46880e43a8fd22dc1a1a8cab1", size = 87528, upload-time = "2023-06-03T06:41:11.019Z" }, ] [[package]] name = "markupsafe" version = "3.0.2" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/b2/97/5d42485e71dfc078108a86d6de8fa46db44a1a9295e89c5d6d4a06e23a62/markupsafe-3.0.2.tar.gz", hash = "sha256:ee55d3edf80167e48ea11a923c7386f4669df67d7994554387f84e7d8b0a2bf0", size = 20537, upload-time = "2024-10-18T15:21:54.129Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/6b/28/bbf83e3f76936960b850435576dd5e67034e200469571be53f69174a2dfd/MarkupSafe-3.0.2-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:9025b4018f3a1314059769c7bf15441064b2207cb3f065e6ea1e7359cb46db9d", size = 14353, upload-time = "2024-10-18T15:21:02.187Z" }, { url = "https://files.pythonhosted.org/packages/6c/30/316d194b093cde57d448a4c3209f22e3046c5bb2fb0820b118292b334be7/MarkupSafe-3.0.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:93335ca3812df2f366e80509ae119189886b0f3c2b81325d39efdb84a1e2ae93", size = 12392, upload-time = "2024-10-18T15:21:02.941Z" }, { url = "https://files.pythonhosted.org/packages/f2/96/9cdafba8445d3a53cae530aaf83c38ec64c4d5427d975c974084af5bc5d2/MarkupSafe-3.0.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2cb8438c3cbb25e220c2ab33bb226559e7afb3baec11c4f218ffa7308603c832", size = 23984, upload-time = "2024-10-18T15:21:03.953Z" }, { url = "https://files.pythonhosted.org/packages/f1/a4/aefb044a2cd8d7334c8a47d3fb2c9f328ac48cb349468cc31c20b539305f/MarkupSafe-3.0.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a123e330ef0853c6e822384873bef7507557d8e4a082961e1defa947aa59ba84", size = 23120, upload-time = "2024-10-18T15:21:06.495Z" }, { url = "https://files.pythonhosted.org/packages/8d/21/5e4851379f88f3fad1de30361db501300d4f07bcad047d3cb0449fc51f8c/MarkupSafe-3.0.2-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:1e084f686b92e5b83186b07e8a17fc09e38fff551f3602b249881fec658d3eca", size = 23032, upload-time = "2024-10-18T15:21:07.295Z" }, { url = "https://files.pythonhosted.org/packages/00/7b/e92c64e079b2d0d7ddf69899c98842f3f9a60a1ae72657c89ce2655c999d/MarkupSafe-3.0.2-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:d8213e09c917a951de9d09ecee036d5c7d36cb6cb7dbaece4c71a60d79fb9798", size = 24057, upload-time = "2024-10-18T15:21:08.073Z" }, { url = "https://files.pythonhosted.org/packages/f9/ac/46f960ca323037caa0a10662ef97d0a4728e890334fc156b9f9e52bcc4ca/MarkupSafe-3.0.2-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:5b02fb34468b6aaa40dfc198d813a641e3a63b98c2b05a16b9f80b7ec314185e", size = 23359, upload-time = "2024-10-18T15:21:09.318Z" }, { url = "https://files.pythonhosted.org/packages/69/84/83439e16197337b8b14b6a5b9c2105fff81d42c2a7c5b58ac7b62ee2c3b1/MarkupSafe-3.0.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:0bff5e0ae4ef2e1ae4fdf2dfd5b76c75e5c2fa4132d05fc1b0dabcd20c7e28c4", size = 23306, upload-time = "2024-10-18T15:21:10.185Z" }, { url = "https://files.pythonhosted.org/packages/9a/34/a15aa69f01e2181ed8d2b685c0d2f6655d5cca2c4db0ddea775e631918cd/MarkupSafe-3.0.2-cp311-cp311-win32.whl", hash = "sha256:6c89876f41da747c8d3677a2b540fb32ef5715f97b66eeb0c6b66f5e3ef6f59d", size = 15094, upload-time = "2024-10-18T15:21:11.005Z" }, { url = "https://files.pythonhosted.org/packages/da/b8/3a3bd761922d416f3dc5d00bfbed11f66b1ab89a0c2b6e887240a30b0f6b/MarkupSafe-3.0.2-cp311-cp311-win_amd64.whl", hash = "sha256:70a87b411535ccad5ef2f1df5136506a10775d267e197e4cf531ced10537bd6b", size = 15521, upload-time = "2024-10-18T15:21:12.911Z" }, { url = "https://files.pythonhosted.org/packages/22/09/d1f21434c97fc42f09d290cbb6350d44eb12f09cc62c9476effdb33a18aa/MarkupSafe-3.0.2-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:9778bd8ab0a994ebf6f84c2b949e65736d5575320a17ae8984a77fab08db94cf", size = 14274, upload-time = "2024-10-18T15:21:13.777Z" }, { url = "https://files.pythonhosted.org/packages/6b/b0/18f76bba336fa5aecf79d45dcd6c806c280ec44538b3c13671d49099fdd0/MarkupSafe-3.0.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:846ade7b71e3536c4e56b386c2a47adf5741d2d8b94ec9dc3e92e5e1ee1e2225", size = 12348, upload-time = "2024-10-18T15:21:14.822Z" }, { url = "https://files.pythonhosted.org/packages/e0/25/dd5c0f6ac1311e9b40f4af06c78efde0f3b5cbf02502f8ef9501294c425b/MarkupSafe-3.0.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1c99d261bd2d5f6b59325c92c73df481e05e57f19837bdca8413b9eac4bd8028", size = 24149, upload-time = "2024-10-18T15:21:15.642Z" }, { url = "https://files.pythonhosted.org/packages/f3/f0/89e7aadfb3749d0f52234a0c8c7867877876e0a20b60e2188e9850794c17/MarkupSafe-3.0.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e17c96c14e19278594aa4841ec148115f9c7615a47382ecb6b82bd8fea3ab0c8", size = 23118, upload-time = "2024-10-18T15:21:17.133Z" }, { url = "https://files.pythonhosted.org/packages/d5/da/f2eeb64c723f5e3777bc081da884b414671982008c47dcc1873d81f625b6/MarkupSafe-3.0.2-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:88416bd1e65dcea10bc7569faacb2c20ce071dd1f87539ca2ab364bf6231393c", size = 22993, upload-time = "2024-10-18T15:21:18.064Z" }, { url = "https://files.pythonhosted.org/packages/da/0e/1f32af846df486dce7c227fe0f2398dc7e2e51d4a370508281f3c1c5cddc/MarkupSafe-3.0.2-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:2181e67807fc2fa785d0592dc2d6206c019b9502410671cc905d132a92866557", size = 24178, upload-time = "2024-10-18T15:21:18.859Z" }, { url = "https://files.pythonhosted.org/packages/c4/f6/bb3ca0532de8086cbff5f06d137064c8410d10779c4c127e0e47d17c0b71/MarkupSafe-3.0.2-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:52305740fe773d09cffb16f8ed0427942901f00adedac82ec8b67752f58a1b22", size = 23319, upload-time = "2024-10-18T15:21:19.671Z" }, { url = "https://files.pythonhosted.org/packages/a2/82/8be4c96ffee03c5b4a034e60a31294daf481e12c7c43ab8e34a1453ee48b/MarkupSafe-3.0.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:ad10d3ded218f1039f11a75f8091880239651b52e9bb592ca27de44eed242a48", size = 23352, upload-time = "2024-10-18T15:21:20.971Z" }, { url = "https://files.pythonhosted.org/packages/51/ae/97827349d3fcffee7e184bdf7f41cd6b88d9919c80f0263ba7acd1bbcb18/MarkupSafe-3.0.2-cp312-cp312-win32.whl", hash = "sha256:0f4ca02bea9a23221c0182836703cbf8930c5e9454bacce27e767509fa286a30", size = 15097, upload-time = "2024-10-18T15:21:22.646Z" }, { url = "https://files.pythonhosted.org/packages/c1/80/a61f99dc3a936413c3ee4e1eecac96c0da5ed07ad56fd975f1a9da5bc630/MarkupSafe-3.0.2-cp312-cp312-win_amd64.whl", hash = "sha256:8e06879fc22a25ca47312fbe7c8264eb0b662f6db27cb2d3bbbc74b1df4b9b87", size = 15601, upload-time = "2024-10-18T15:21:23.499Z" }, { url = "https://files.pythonhosted.org/packages/83/0e/67eb10a7ecc77a0c2bbe2b0235765b98d164d81600746914bebada795e97/MarkupSafe-3.0.2-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:ba9527cdd4c926ed0760bc301f6728ef34d841f405abf9d4f959c478421e4efd", size = 14274, upload-time = "2024-10-18T15:21:24.577Z" }, { url = "https://files.pythonhosted.org/packages/2b/6d/9409f3684d3335375d04e5f05744dfe7e9f120062c9857df4ab490a1031a/MarkupSafe-3.0.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:f8b3d067f2e40fe93e1ccdd6b2e1d16c43140e76f02fb1319a05cf2b79d99430", size = 12352, upload-time = "2024-10-18T15:21:25.382Z" }, { url = "https://files.pythonhosted.org/packages/d2/f5/6eadfcd3885ea85fe2a7c128315cc1bb7241e1987443d78c8fe712d03091/MarkupSafe-3.0.2-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:569511d3b58c8791ab4c2e1285575265991e6d8f8700c7be0e88f86cb0672094", size = 24122, upload-time = "2024-10-18T15:21:26.199Z" }, { url = "https://files.pythonhosted.org/packages/0c/91/96cf928db8236f1bfab6ce15ad070dfdd02ed88261c2afafd4b43575e9e9/MarkupSafe-3.0.2-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:15ab75ef81add55874e7ab7055e9c397312385bd9ced94920f2802310c930396", size = 23085, upload-time = "2024-10-18T15:21:27.029Z" }, { url = "https://files.pythonhosted.org/packages/c2/cf/c9d56af24d56ea04daae7ac0940232d31d5a8354f2b457c6d856b2057d69/MarkupSafe-3.0.2-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:f3818cb119498c0678015754eba762e0d61e5b52d34c8b13d770f0719f7b1d79", size = 22978, upload-time = "2024-10-18T15:21:27.846Z" }, { url = "https://files.pythonhosted.org/packages/2a/9f/8619835cd6a711d6272d62abb78c033bda638fdc54c4e7f4272cf1c0962b/MarkupSafe-3.0.2-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:cdb82a876c47801bb54a690c5ae105a46b392ac6099881cdfb9f6e95e4014c6a", size = 24208, upload-time = "2024-10-18T15:21:28.744Z" }, { url = "https://files.pythonhosted.org/packages/f9/bf/176950a1792b2cd2102b8ffeb5133e1ed984547b75db47c25a67d3359f77/MarkupSafe-3.0.2-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:cabc348d87e913db6ab4aa100f01b08f481097838bdddf7c7a84b7575b7309ca", size = 23357, upload-time = "2024-10-18T15:21:29.545Z" }, { url = "https://files.pythonhosted.org/packages/ce/4f/9a02c1d335caabe5c4efb90e1b6e8ee944aa245c1aaaab8e8a618987d816/MarkupSafe-3.0.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:444dcda765c8a838eaae23112db52f1efaf750daddb2d9ca300bcae1039adc5c", size = 23344, upload-time = "2024-10-18T15:21:30.366Z" }, { url = "https://files.pythonhosted.org/packages/ee/55/c271b57db36f748f0e04a759ace9f8f759ccf22b4960c270c78a394f58be/MarkupSafe-3.0.2-cp313-cp313-win32.whl", hash = "sha256:bcf3e58998965654fdaff38e58584d8937aa3096ab5354d493c77d1fdd66d7a1", size = 15101, upload-time = "2024-10-18T15:21:31.207Z" }, { url = "https://files.pythonhosted.org/packages/29/88/07df22d2dd4df40aba9f3e402e6dc1b8ee86297dddbad4872bd5e7b0094f/MarkupSafe-3.0.2-cp313-cp313-win_amd64.whl", hash = "sha256:e6a2a455bd412959b57a172ce6328d2dd1f01cb2135efda2e4576e8a23fa3b0f", size = 15603, upload-time = "2024-10-18T15:21:32.032Z" }, { url = "https://files.pythonhosted.org/packages/62/6a/8b89d24db2d32d433dffcd6a8779159da109842434f1dd2f6e71f32f738c/MarkupSafe-3.0.2-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:b5a6b3ada725cea8a5e634536b1b01c30bcdcd7f9c6fff4151548d5bf6b3a36c", size = 14510, upload-time = "2024-10-18T15:21:33.625Z" }, { url = "https://files.pythonhosted.org/packages/7a/06/a10f955f70a2e5a9bf78d11a161029d278eeacbd35ef806c3fd17b13060d/MarkupSafe-3.0.2-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:a904af0a6162c73e3edcb969eeeb53a63ceeb5d8cf642fade7d39e7963a22ddb", size = 12486, upload-time = "2024-10-18T15:21:34.611Z" }, { url = "https://files.pythonhosted.org/packages/34/cf/65d4a571869a1a9078198ca28f39fba5fbb910f952f9dbc5220afff9f5e6/MarkupSafe-3.0.2-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4aa4e5faecf353ed117801a068ebab7b7e09ffb6e1d5e412dc852e0da018126c", size = 25480, upload-time = "2024-10-18T15:21:35.398Z" }, { url = "https://files.pythonhosted.org/packages/0c/e3/90e9651924c430b885468b56b3d597cabf6d72be4b24a0acd1fa0e12af67/MarkupSafe-3.0.2-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c0ef13eaeee5b615fb07c9a7dadb38eac06a0608b41570d8ade51c56539e509d", size = 23914, upload-time = "2024-10-18T15:21:36.231Z" }, { url = "https://files.pythonhosted.org/packages/66/8c/6c7cf61f95d63bb866db39085150df1f2a5bd3335298f14a66b48e92659c/MarkupSafe-3.0.2-cp313-cp313t-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:d16a81a06776313e817c951135cf7340a3e91e8c1ff2fac444cfd75fffa04afe", size = 23796, upload-time = "2024-10-18T15:21:37.073Z" }, { url = "https://files.pythonhosted.org/packages/bb/35/cbe9238ec3f47ac9a7c8b3df7a808e7cb50fe149dc7039f5f454b3fba218/MarkupSafe-3.0.2-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:6381026f158fdb7c72a168278597a5e3a5222e83ea18f543112b2662a9b699c5", size = 25473, upload-time = "2024-10-18T15:21:37.932Z" }, { url = "https://files.pythonhosted.org/packages/e6/32/7621a4382488aa283cc05e8984a9c219abad3bca087be9ec77e89939ded9/MarkupSafe-3.0.2-cp313-cp313t-musllinux_1_2_i686.whl", hash = "sha256:3d79d162e7be8f996986c064d1c7c817f6df3a77fe3d6859f6f9e7be4b8c213a", size = 24114, upload-time = "2024-10-18T15:21:39.799Z" }, { url = "https://files.pythonhosted.org/packages/0d/80/0985960e4b89922cb5a0bac0ed39c5b96cbc1a536a99f30e8c220a996ed9/MarkupSafe-3.0.2-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:131a3c7689c85f5ad20f9f6fb1b866f402c445b220c19fe4308c0b147ccd2ad9", size = 24098, upload-time = "2024-10-18T15:21:40.813Z" }, { url = "https://files.pythonhosted.org/packages/82/78/fedb03c7d5380df2427038ec8d973587e90561b2d90cd472ce9254cf348b/MarkupSafe-3.0.2-cp313-cp313t-win32.whl", hash = "sha256:ba8062ed2cf21c07a9e295d5b8a2a5ce678b913b45fdf68c32d95d6c1291e0b6", size = 15208, upload-time = "2024-10-18T15:21:41.814Z" }, { url = "https://files.pythonhosted.org/packages/4f/65/6079a46068dfceaeabb5dcad6d674f5f5c61a6fa5673746f42a9f4c233b3/MarkupSafe-3.0.2-cp313-cp313t-win_amd64.whl", hash = "sha256:e444a31f8db13eb18ada366ab3cf45fd4b31e4db1236a4448f68778c1d1a5a2f", size = 15739, upload-time = "2024-10-18T15:21:42.784Z" }, ] [[package]] name = "mdit-py-plugins" version = "0.4.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "markdown-it-py" }, ] sdist = { url = "https://files.pythonhosted.org/packages/19/03/a2ecab526543b152300717cf232bb4bb8605b6edb946c845016fa9c9c9fd/mdit_py_plugins-0.4.2.tar.gz", hash = "sha256:5f2cd1fdb606ddf152d37ec30e46101a60512bc0e5fa1a7002c36647b09e26b5", size = 43542, upload-time = "2024-09-09T20:27:49.564Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/a7/f7/7782a043553ee469c1ff49cfa1cdace2d6bf99a1f333cf38676b3ddf30da/mdit_py_plugins-0.4.2-py3-none-any.whl", hash = "sha256:0c673c3f889399a33b95e88d2f0d111b4447bdfea7f237dab2d488f459835636", size = 55316, upload-time = "2024-09-09T20:27:48.397Z" }, ] [[package]] name = "mdurl" version = "0.1.2" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/d6/54/cfe61301667036ec958cb99bd3efefba235e65cdeb9c84d24a8293ba1d90/mdurl-0.1.2.tar.gz", hash = "sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba", size = 8729, upload-time = "2022-08-14T12:40:10.846Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/b3/38/89ba8ad64ae25be8de66a6d463314cf1eb366222074cfda9ee839c56a4b4/mdurl-0.1.2-py3-none-any.whl", hash = "sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8", size = 9979, upload-time = "2022-08-14T12:40:09.779Z" }, ] [[package]] name = "mypy" version = "1.16.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "mypy-extensions" }, { name = "pathspec" }, { name = "typing-extensions" }, ] sdist = { url = "https://files.pythonhosted.org/packages/d4/38/13c2f1abae94d5ea0354e146b95a1be9b2137a0d506728e0da037c4276f6/mypy-1.16.0.tar.gz", hash = "sha256:84b94283f817e2aa6350a14b4a8fb2a35a53c286f97c9d30f53b63620e7af8ab", size = 3323139, upload-time = "2025-05-29T13:46:12.532Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/24/c4/ff2f79db7075c274fe85b5fff8797d29c6b61b8854c39e3b7feb556aa377/mypy-1.16.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:9f826aaa7ff8443bac6a494cf743f591488ea940dd360e7dd330e30dd772a5ab", size = 10884498, upload-time = "2025-05-29T13:18:54.066Z" }, { url = "https://files.pythonhosted.org/packages/02/07/12198e83006235f10f6a7808917376b5d6240a2fd5dce740fe5d2ebf3247/mypy-1.16.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:82d056e6faa508501af333a6af192c700b33e15865bda49611e3d7d8358ebea2", size = 10011755, upload-time = "2025-05-29T13:34:00.851Z" }, { url = "https://files.pythonhosted.org/packages/f1/9b/5fd5801a72b5d6fb6ec0105ea1d0e01ab2d4971893076e558d4b6d6b5f80/mypy-1.16.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:089bedc02307c2548eb51f426e085546db1fa7dd87fbb7c9fa561575cf6eb1ff", size = 11800138, upload-time = "2025-05-29T13:32:55.082Z" }, { url = "https://files.pythonhosted.org/packages/2e/81/a117441ea5dfc3746431e51d78a4aca569c677aa225bca2cc05a7c239b61/mypy-1.16.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6a2322896003ba66bbd1318c10d3afdfe24e78ef12ea10e2acd985e9d684a666", size = 12533156, upload-time = "2025-05-29T13:19:12.963Z" }, { url = "https://files.pythonhosted.org/packages/3f/38/88ec57c6c86014d3f06251e00f397b5a7daa6888884d0abf187e4f5f587f/mypy-1.16.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:021a68568082c5b36e977d54e8f1de978baf401a33884ffcea09bd8e88a98f4c", size = 12742426, upload-time = "2025-05-29T13:20:22.72Z" }, { url = "https://files.pythonhosted.org/packages/bd/53/7e9d528433d56e6f6f77ccf24af6ce570986c2d98a5839e4c2009ef47283/mypy-1.16.0-cp311-cp311-win_amd64.whl", hash = "sha256:54066fed302d83bf5128632d05b4ec68412e1f03ef2c300434057d66866cea4b", size = 9478319, upload-time = "2025-05-29T13:21:17.582Z" }, { url = "https://files.pythonhosted.org/packages/70/cf/158e5055e60ca2be23aec54a3010f89dcffd788732634b344fc9cb1e85a0/mypy-1.16.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:c5436d11e89a3ad16ce8afe752f0f373ae9620841c50883dc96f8b8805620b13", size = 11062927, upload-time = "2025-05-29T13:35:52.328Z" }, { url = "https://files.pythonhosted.org/packages/94/34/cfff7a56be1609f5d10ef386342ce3494158e4d506516890142007e6472c/mypy-1.16.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:f2622af30bf01d8fc36466231bdd203d120d7a599a6d88fb22bdcb9dbff84090", size = 10083082, upload-time = "2025-05-29T13:35:33.378Z" }, { url = "https://files.pythonhosted.org/packages/b3/7f/7242062ec6288c33d8ad89574df87c3903d394870e5e6ba1699317a65075/mypy-1.16.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d045d33c284e10a038f5e29faca055b90eee87da3fc63b8889085744ebabb5a1", size = 11828306, upload-time = "2025-05-29T13:21:02.164Z" }, { url = "https://files.pythonhosted.org/packages/6f/5f/b392f7b4f659f5b619ce5994c5c43caab3d80df2296ae54fa888b3d17f5a/mypy-1.16.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b4968f14f44c62e2ec4a038c8797a87315be8df7740dc3ee8d3bfe1c6bf5dba8", size = 12702764, upload-time = "2025-05-29T13:20:42.826Z" }, { url = "https://files.pythonhosted.org/packages/9b/c0/7646ef3a00fa39ac9bc0938626d9ff29d19d733011be929cfea59d82d136/mypy-1.16.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:eb14a4a871bb8efb1e4a50360d4e3c8d6c601e7a31028a2c79f9bb659b63d730", size = 12896233, upload-time = "2025-05-29T13:18:37.446Z" }, { url = "https://files.pythonhosted.org/packages/6d/38/52f4b808b3fef7f0ef840ee8ff6ce5b5d77381e65425758d515cdd4f5bb5/mypy-1.16.0-cp312-cp312-win_amd64.whl", hash = "sha256:bd4e1ebe126152a7bbaa4daedd781c90c8f9643c79b9748caa270ad542f12bec", size = 9565547, upload-time = "2025-05-29T13:20:02.836Z" }, { url = "https://files.pythonhosted.org/packages/97/9c/ca03bdbefbaa03b264b9318a98950a9c683e06472226b55472f96ebbc53d/mypy-1.16.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:a9e056237c89f1587a3be1a3a70a06a698d25e2479b9a2f57325ddaaffc3567b", size = 11059753, upload-time = "2025-05-29T13:18:18.167Z" }, { url = "https://files.pythonhosted.org/packages/36/92/79a969b8302cfe316027c88f7dc6fee70129490a370b3f6eb11d777749d0/mypy-1.16.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:0b07e107affb9ee6ce1f342c07f51552d126c32cd62955f59a7db94a51ad12c0", size = 10073338, upload-time = "2025-05-29T13:19:48.079Z" }, { url = "https://files.pythonhosted.org/packages/14/9b/a943f09319167da0552d5cd722104096a9c99270719b1afeea60d11610aa/mypy-1.16.0-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c6fb60cbd85dc65d4d63d37cb5c86f4e3a301ec605f606ae3a9173e5cf34997b", size = 11827764, upload-time = "2025-05-29T13:46:04.47Z" }, { url = "https://files.pythonhosted.org/packages/ec/64/ff75e71c65a0cb6ee737287c7913ea155845a556c64144c65b811afdb9c7/mypy-1.16.0-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a7e32297a437cc915599e0578fa6bc68ae6a8dc059c9e009c628e1c47f91495d", size = 12701356, upload-time = "2025-05-29T13:35:13.553Z" }, { url = "https://files.pythonhosted.org/packages/0a/ad/0e93c18987a1182c350f7a5fab70550852f9fabe30ecb63bfbe51b602074/mypy-1.16.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:afe420c9380ccec31e744e8baff0d406c846683681025db3531b32db56962d52", size = 12900745, upload-time = "2025-05-29T13:17:24.409Z" }, { url = "https://files.pythonhosted.org/packages/28/5d/036c278d7a013e97e33f08c047fe5583ab4f1fc47c9a49f985f1cdd2a2d7/mypy-1.16.0-cp313-cp313-win_amd64.whl", hash = "sha256:55f9076c6ce55dd3f8cd0c6fff26a008ca8e5131b89d5ba6d86bd3f47e736eeb", size = 9572200, upload-time = "2025-05-29T13:33:44.92Z" }, { url = "https://files.pythonhosted.org/packages/99/a3/6ed10530dec8e0fdc890d81361260c9ef1f5e5c217ad8c9b21ecb2b8366b/mypy-1.16.0-py3-none-any.whl", hash = "sha256:29e1499864a3888bca5c1542f2d7232c6e586295183320caa95758fc84034031", size = 2265773, upload-time = "2025-05-29T13:35:18.762Z" }, ] [[package]] name = "mypy-extensions" version = "1.1.0" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/a2/6e/371856a3fb9d31ca8dac321cda606860fa4548858c0cc45d9d1d4ca2628b/mypy_extensions-1.1.0.tar.gz", hash = "sha256:52e68efc3284861e772bbcd66823fde5ae21fd2fdb51c62a211403730b916558", size = 6343, upload-time = "2025-04-22T14:54:24.164Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/79/7b/2c79738432f5c924bef5071f933bcc9efd0473bac3b4aa584a6f7c1c8df8/mypy_extensions-1.1.0-py3-none-any.whl", hash = "sha256:1be4cccdb0f2482337c4743e60421de3a356cd97508abadd57d47403e94f5505", size = 4963, upload-time = "2025-04-22T14:54:22.983Z" }, ] [[package]] name = "myst-parser" version = "4.0.1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "docutils" }, { name = "jinja2" }, { name = "markdown-it-py" }, { name = "mdit-py-plugins" }, { name = "pyyaml" }, { name = "sphinx" }, ] sdist = { url = "https://files.pythonhosted.org/packages/66/a5/9626ba4f73555b3735ad86247a8077d4603aa8628537687c839ab08bfe44/myst_parser-4.0.1.tar.gz", hash = "sha256:5cfea715e4f3574138aecbf7d54132296bfd72bb614d31168f48c477a830a7c4", size = 93985, upload-time = "2025-02-12T10:53:03.833Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/5f/df/76d0321c3797b54b60fef9ec3bd6f4cfd124b9e422182156a1dd418722cf/myst_parser-4.0.1-py3-none-any.whl", hash = "sha256:9134e88959ec3b5780aedf8a99680ea242869d012e8821db3126d427edc9c95d", size = 84579, upload-time = "2025-02-12T10:53:02.078Z" }, ] [[package]] name = "nodeenv" version = "1.9.1" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/43/16/fc88b08840de0e0a72a2f9d8c6bae36be573e475a6326ae854bcc549fc45/nodeenv-1.9.1.tar.gz", hash = "sha256:6ec12890a2dab7946721edbfbcd91f3319c6ccc9aec47be7c7e6b7011ee6645f", size = 47437, upload-time = "2024-06-04T18:44:11.171Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/d2/1d/1b658dbd2b9fa9c4c9f32accbfc0205d532c8c6194dc0f2a4c0428e7128a/nodeenv-1.9.1-py2.py3-none-any.whl", hash = "sha256:ba11c9782d29c27c70ffbdda2d7415098754709be8a7056d79a737cd901155c9", size = 22314, upload-time = "2024-06-04T18:44:08.352Z" }, ] [[package]] name = "outcome" version = "1.3.0.post0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "attrs" }, ] sdist = { url = "https://files.pythonhosted.org/packages/98/df/77698abfac98571e65ffeb0c1fba8ffd692ab8458d617a0eed7d9a8d38f2/outcome-1.3.0.post0.tar.gz", hash = "sha256:9dcf02e65f2971b80047b377468e72a268e15c0af3cf1238e6ff14f7f91143b8", size = 21060, upload-time = "2023-10-26T04:26:04.361Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/55/8b/5ab7257531a5d830fc8000c476e63c935488d74609b50f9384a643ec0a62/outcome-1.3.0.post0-py2.py3-none-any.whl", hash = "sha256:e771c5ce06d1415e356078d3bdd68523f284b4ce5419828922b6871e65eda82b", size = 10692, upload-time = "2023-10-26T04:26:02.532Z" }, ] [[package]] name = "packaging" version = "25.0" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/a1/d4/1fc4078c65507b51b96ca8f8c3ba19e6a61c8253c72794544580a7b6c24d/packaging-25.0.tar.gz", hash = "sha256:d443872c98d677bf60f6a1f2f8c1cb748e8fe762d2bf9d3148b5599295b0fc4f", size = 165727, upload-time = "2025-04-19T11:48:59.673Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/20/12/38679034af332785aac8774540895e234f4d07f7545804097de4b666afd8/packaging-25.0-py3-none-any.whl", hash = "sha256:29572ef2b1f17581046b3a2227d5c611fb25ec70ca1ba8554b24b0e69331a484", size = 66469, upload-time = "2025-04-19T11:48:57.875Z" }, ] [[package]] name = "pallets-sphinx-themes" version = "2.3.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "packaging" }, { name = "sphinx" }, { name = "sphinx-notfound-page" }, ] sdist = { url = "https://files.pythonhosted.org/packages/3b/08/c57dd89e45dbc976930200a2cb7826ed76f3c9791454a9fcd1cde3f17177/pallets_sphinx_themes-2.3.0.tar.gz", hash = "sha256:6293ced11a1d5d3de7268af1acd60428732b5a9e6051a47a596c6d9a083e60d9", size = 21029, upload-time = "2024-10-24T18:52:38.574Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/ff/7d/a4aa06e452e031559dcfb066e035d2615ebfa6148e93514d7c36030004c1/pallets_sphinx_themes-2.3.0-py3-none-any.whl", hash = "sha256:7ed13de3743c462c2804e2aa63d96cc9ffa82cb76d0251cea03de9bcd9f8dbec", size = 24745, upload-time = "2024-10-24T18:52:37.265Z" }, ] [[package]] name = "pathspec" version = "0.12.1" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/ca/bc/f35b8446f4531a7cb215605d100cd88b7ac6f44ab3fc94870c120ab3adbf/pathspec-0.12.1.tar.gz", hash = "sha256:a482d51503a1ab33b1c67a6c3813a26953dbdc71c31dacaef9a838c4e29f5712", size = 51043, upload-time = "2023-12-10T22:30:45Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/cc/20/ff623b09d963f88bfde16306a54e12ee5ea43e9b597108672ff3a408aad6/pathspec-0.12.1-py3-none-any.whl", hash = "sha256:a0d503e138a4c123b27490a4f7beda6a01c6f288df0e4a8b79c7eb0dc7b4cc08", size = 31191, upload-time = "2023-12-10T22:30:43.14Z" }, ] [[package]] name = "platformdirs" version = "4.3.8" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/fe/8b/3c73abc9c759ecd3f1f7ceff6685840859e8070c4d947c93fae71f6a0bf2/platformdirs-4.3.8.tar.gz", hash = "sha256:3d512d96e16bcb959a814c9f348431070822a6496326a4be0911c40b5a74c2bc", size = 21362, upload-time = "2025-05-07T22:47:42.121Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/fe/39/979e8e21520d4e47a0bbe349e2713c0aac6f3d853d0e5b34d76206c439aa/platformdirs-4.3.8-py3-none-any.whl", hash = "sha256:ff7059bb7eb1179e2685604f4aaf157cfd9535242bd23742eadc3c13542139b4", size = 18567, upload-time = "2025-05-07T22:47:40.376Z" }, ] [[package]] name = "pluggy" version = "1.6.0" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/f9/e2/3e91f31a7d2b083fe6ef3fa267035b518369d9511ffab804f839851d2779/pluggy-1.6.0.tar.gz", hash = "sha256:7dcc130b76258d33b90f61b658791dede3486c3e6bfb003ee5c9bfb396dd22f3", size = 69412, upload-time = "2025-05-15T12:30:07.975Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/54/20/4d324d65cc6d9205fabedc306948156824eb9f0ee1633355a8f7ec5c66bf/pluggy-1.6.0-py3-none-any.whl", hash = "sha256:e920276dd6813095e9377c0bc5566d94c932c33b27a3e3945d8389c374dd4746", size = 20538, upload-time = "2025-05-15T12:30:06.134Z" }, ] [[package]] name = "pre-commit" version = "4.2.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "cfgv" }, { name = "identify" }, { name = "nodeenv" }, { name = "pyyaml" }, { name = "virtualenv" }, ] sdist = { url = "https://files.pythonhosted.org/packages/08/39/679ca9b26c7bb2999ff122d50faa301e49af82ca9c066ec061cfbc0c6784/pre_commit-4.2.0.tar.gz", hash = "sha256:601283b9757afd87d40c4c4a9b2b5de9637a8ea02eaff7adc2d0fb4e04841146", size = 193424, upload-time = "2025-03-18T21:35:20.987Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/88/74/a88bf1b1efeae488a0c0b7bdf71429c313722d1fc0f377537fbe554e6180/pre_commit-4.2.0-py2.py3-none-any.whl", hash = "sha256:a009ca7205f1eb497d10b845e52c838a98b6cdd2102a6c8e4540e94ee75c58bd", size = 220707, upload-time = "2025-03-18T21:35:19.343Z" }, ] [[package]] name = "pre-commit-uv" version = "4.1.4" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "pre-commit" }, { name = "uv" }, ] sdist = { url = "https://files.pythonhosted.org/packages/b1/6c/c3c1d01698c8abb0b546defc0304971fa7fb2ba84ad35587b9dad095d73f/pre_commit_uv-4.1.4.tar.gz", hash = "sha256:3db606a79b226127b27dbbd8381b78c0e30de3ac775a8492c576a68e9250535c", size = 6493, upload-time = "2024-10-29T23:07:28.918Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/f1/70/1b65f9118ef64f6ffe5d57a67170bbff25d4f4a3d1cb78e8ed3392e16114/pre_commit_uv-4.1.4-py3-none-any.whl", hash = "sha256:7f01fb494fa1caa5097d20a38f71df7cea0209197b2564699cef9b3f3aa9d135", size = 5578, upload-time = "2024-10-29T23:07:27.128Z" }, ] [[package]] name = "pycparser" version = "2.23" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/fe/cf/d2d3b9f5699fb1e4615c8e32ff220203e43b248e1dfcc6736ad9057731ca/pycparser-2.23.tar.gz", hash = "sha256:78816d4f24add8f10a06d6f05b4d424ad9e96cfebf68a4ddc99c65c0720d00c2", size = 173734, upload-time = "2025-09-09T13:23:47.91Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/a0/e3/59cd50310fc9b59512193629e1984c1f95e5c8ae6e5d8c69532ccc65a7fe/pycparser-2.23-py3-none-any.whl", hash = "sha256:e5c6e8d3fbad53479cab09ac03729e0a9faf2bee3db8208a550daf5af81a5934", size = 118140, upload-time = "2025-09-09T13:23:46.651Z" }, ] [[package]] name = "pygments" version = "2.19.1" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/7c/2d/c3338d48ea6cc0feb8446d8e6937e1408088a72a39937982cc6111d17f84/pygments-2.19.1.tar.gz", hash = "sha256:61c16d2a8576dc0649d9f39e089b5f02bcd27fba10d8fb4dcc28173f7a45151f", size = 4968581, upload-time = "2025-01-06T17:26:30.443Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/8a/0b/9fcc47d19c48b59121088dd6da2488a49d5f72dacf8262e2790a1d2c7d15/pygments-2.19.1-py3-none-any.whl", hash = "sha256:9ea1544ad55cecf4b8242fab6dd35a93bbce657034b0611ee383099054ab6d8c", size = 1225293, upload-time = "2025-01-06T17:26:25.553Z" }, ] [[package]] name = "pyproject-api" version = "1.9.1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "packaging" }, ] sdist = { url = "https://files.pythonhosted.org/packages/19/fd/437901c891f58a7b9096511750247535e891d2d5a5a6eefbc9386a2b41d5/pyproject_api-1.9.1.tar.gz", hash = "sha256:43c9918f49daab37e302038fc1aed54a8c7a91a9fa935d00b9a485f37e0f5335", size = 22710, upload-time = "2025-05-12T14:41:58.025Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/ef/e6/c293c06695d4a3ab0260ef124a74ebadba5f4c511ce3a4259e976902c00b/pyproject_api-1.9.1-py3-none-any.whl", hash = "sha256:7d6238d92f8962773dd75b5f0c4a6a27cce092a14b623b811dba656f3b628948", size = 13158, upload-time = "2025-05-12T14:41:56.217Z" }, ] [[package]] name = "pyright" version = "1.1.401" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "nodeenv" }, { name = "typing-extensions" }, ] sdist = { url = "https://files.pythonhosted.org/packages/79/9a/7ab2b333b921b2d6bfcffe05a0e0a0bbeff884bd6fb5ed50cd68e2898e53/pyright-1.1.401.tar.gz", hash = "sha256:788a82b6611fa5e34a326a921d86d898768cddf59edde8e93e56087d277cc6f1", size = 3894193, upload-time = "2025-05-21T10:44:52.03Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/0d/e6/1f908fce68b0401d41580e0f9acc4c3d1b248adcff00dfaad75cd21a1370/pyright-1.1.401-py3-none-any.whl", hash = "sha256:6fde30492ba5b0d7667c16ecaf6c699fab8d7a1263f6a18549e0b00bf7724c06", size = 5629193, upload-time = "2025-05-21T10:44:50.129Z" }, ] [[package]] name = "pytest" version = "8.4.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "colorama", marker = "sys_platform == 'win32'" }, { name = "iniconfig" }, { name = "packaging" }, { name = "pluggy" }, { name = "pygments" }, ] sdist = { url = "https://files.pythonhosted.org/packages/fb/aa/405082ce2749be5398045152251ac69c0f3578c7077efc53431303af97ce/pytest-8.4.0.tar.gz", hash = "sha256:14d920b48472ea0dbf68e45b96cd1ffda4705f33307dcc86c676c1b5104838a6", size = 1515232, upload-time = "2025-06-02T17:36:30.03Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/2f/de/afa024cbe022b1b318a3d224125aa24939e99b4ff6f22e0ba639a2eaee47/pytest-8.4.0-py3-none-any.whl", hash = "sha256:f40f825768ad76c0977cbacdf1fd37c6f7a468e460ea6a0636078f8972d4517e", size = 363797, upload-time = "2025-06-02T17:36:27.859Z" }, ] [[package]] name = "pyyaml" version = "6.0.2" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/54/ed/79a089b6be93607fa5cdaedf301d7dfb23af5f25c398d5ead2525b063e17/pyyaml-6.0.2.tar.gz", hash = "sha256:d584d9ec91ad65861cc08d42e834324ef890a082e591037abe114850ff7bbc3e", size = 130631, upload-time = "2024-08-06T20:33:50.674Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/f8/aa/7af4e81f7acba21a4c6be026da38fd2b872ca46226673c89a758ebdc4fd2/PyYAML-6.0.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:cc1c1159b3d456576af7a3e4d1ba7e6924cb39de8f67111c735f6fc832082774", size = 184612, upload-time = "2024-08-06T20:32:03.408Z" }, { url = "https://files.pythonhosted.org/packages/8b/62/b9faa998fd185f65c1371643678e4d58254add437edb764a08c5a98fb986/PyYAML-6.0.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:1e2120ef853f59c7419231f3bf4e7021f1b936f6ebd222406c3b60212205d2ee", size = 172040, upload-time = "2024-08-06T20:32:04.926Z" }, { url = "https://files.pythonhosted.org/packages/ad/0c/c804f5f922a9a6563bab712d8dcc70251e8af811fce4524d57c2c0fd49a4/PyYAML-6.0.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5d225db5a45f21e78dd9358e58a98702a0302f2659a3c6cd320564b75b86f47c", size = 736829, upload-time = "2024-08-06T20:32:06.459Z" }, { url = "https://files.pythonhosted.org/packages/51/16/6af8d6a6b210c8e54f1406a6b9481febf9c64a3109c541567e35a49aa2e7/PyYAML-6.0.2-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:5ac9328ec4831237bec75defaf839f7d4564be1e6b25ac710bd1a96321cc8317", size = 764167, upload-time = "2024-08-06T20:32:08.338Z" }, { url = "https://files.pythonhosted.org/packages/75/e4/2c27590dfc9992f73aabbeb9241ae20220bd9452df27483b6e56d3975cc5/PyYAML-6.0.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3ad2a3decf9aaba3d29c8f537ac4b243e36bef957511b4766cb0057d32b0be85", size = 762952, upload-time = "2024-08-06T20:32:14.124Z" }, { url = "https://files.pythonhosted.org/packages/9b/97/ecc1abf4a823f5ac61941a9c00fe501b02ac3ab0e373c3857f7d4b83e2b6/PyYAML-6.0.2-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:ff3824dc5261f50c9b0dfb3be22b4567a6f938ccce4587b38952d85fd9e9afe4", size = 735301, upload-time = "2024-08-06T20:32:16.17Z" }, { url = "https://files.pythonhosted.org/packages/45/73/0f49dacd6e82c9430e46f4a027baa4ca205e8b0a9dce1397f44edc23559d/PyYAML-6.0.2-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:797b4f722ffa07cc8d62053e4cff1486fa6dc094105d13fea7b1de7d8bf71c9e", size = 756638, upload-time = "2024-08-06T20:32:18.555Z" }, { url = "https://files.pythonhosted.org/packages/22/5f/956f0f9fc65223a58fbc14459bf34b4cc48dec52e00535c79b8db361aabd/PyYAML-6.0.2-cp311-cp311-win32.whl", hash = "sha256:11d8f3dd2b9c1207dcaf2ee0bbbfd5991f571186ec9cc78427ba5bd32afae4b5", size = 143850, upload-time = "2024-08-06T20:32:19.889Z" }, { url = "https://files.pythonhosted.org/packages/ed/23/8da0bbe2ab9dcdd11f4f4557ccaf95c10b9811b13ecced089d43ce59c3c8/PyYAML-6.0.2-cp311-cp311-win_amd64.whl", hash = "sha256:e10ce637b18caea04431ce14fabcf5c64a1c61ec9c56b071a4b7ca131ca52d44", size = 161980, upload-time = "2024-08-06T20:32:21.273Z" }, { url = "https://files.pythonhosted.org/packages/86/0c/c581167fc46d6d6d7ddcfb8c843a4de25bdd27e4466938109ca68492292c/PyYAML-6.0.2-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:c70c95198c015b85feafc136515252a261a84561b7b1d51e3384e0655ddf25ab", size = 183873, upload-time = "2024-08-06T20:32:25.131Z" }, { url = "https://files.pythonhosted.org/packages/a8/0c/38374f5bb272c051e2a69281d71cba6fdb983413e6758b84482905e29a5d/PyYAML-6.0.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:ce826d6ef20b1bc864f0a68340c8b3287705cae2f8b4b1d932177dcc76721725", size = 173302, upload-time = "2024-08-06T20:32:26.511Z" }, { url = "https://files.pythonhosted.org/packages/c3/93/9916574aa8c00aa06bbac729972eb1071d002b8e158bd0e83a3b9a20a1f7/PyYAML-6.0.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1f71ea527786de97d1a0cc0eacd1defc0985dcf6b3f17bb77dcfc8c34bec4dc5", size = 739154, upload-time = "2024-08-06T20:32:28.363Z" }, { url = "https://files.pythonhosted.org/packages/95/0f/b8938f1cbd09739c6da569d172531567dbcc9789e0029aa070856f123984/PyYAML-6.0.2-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:9b22676e8097e9e22e36d6b7bda33190d0d400f345f23d4065d48f4ca7ae0425", size = 766223, upload-time = "2024-08-06T20:32:30.058Z" }, { url = "https://files.pythonhosted.org/packages/b9/2b/614b4752f2e127db5cc206abc23a8c19678e92b23c3db30fc86ab731d3bd/PyYAML-6.0.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:80bab7bfc629882493af4aa31a4cfa43a4c57c83813253626916b8c7ada83476", size = 767542, upload-time = "2024-08-06T20:32:31.881Z" }, { url = "https://files.pythonhosted.org/packages/d4/00/dd137d5bcc7efea1836d6264f049359861cf548469d18da90cd8216cf05f/PyYAML-6.0.2-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:0833f8694549e586547b576dcfaba4a6b55b9e96098b36cdc7ebefe667dfed48", size = 731164, upload-time = "2024-08-06T20:32:37.083Z" }, { url = "https://files.pythonhosted.org/packages/c9/1f/4f998c900485e5c0ef43838363ba4a9723ac0ad73a9dc42068b12aaba4e4/PyYAML-6.0.2-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:8b9c7197f7cb2738065c481a0461e50ad02f18c78cd75775628afb4d7137fb3b", size = 756611, upload-time = "2024-08-06T20:32:38.898Z" }, { url = "https://files.pythonhosted.org/packages/df/d1/f5a275fdb252768b7a11ec63585bc38d0e87c9e05668a139fea92b80634c/PyYAML-6.0.2-cp312-cp312-win32.whl", hash = "sha256:ef6107725bd54b262d6dedcc2af448a266975032bc85ef0172c5f059da6325b4", size = 140591, upload-time = "2024-08-06T20:32:40.241Z" }, { url = "https://files.pythonhosted.org/packages/0c/e8/4f648c598b17c3d06e8753d7d13d57542b30d56e6c2dedf9c331ae56312e/PyYAML-6.0.2-cp312-cp312-win_amd64.whl", hash = "sha256:7e7401d0de89a9a855c839bc697c079a4af81cf878373abd7dc625847d25cbd8", size = 156338, upload-time = "2024-08-06T20:32:41.93Z" }, { url = "https://files.pythonhosted.org/packages/ef/e3/3af305b830494fa85d95f6d95ef7fa73f2ee1cc8ef5b495c7c3269fb835f/PyYAML-6.0.2-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:efdca5630322a10774e8e98e1af481aad470dd62c3170801852d752aa7a783ba", size = 181309, upload-time = "2024-08-06T20:32:43.4Z" }, { url = "https://files.pythonhosted.org/packages/45/9f/3b1c20a0b7a3200524eb0076cc027a970d320bd3a6592873c85c92a08731/PyYAML-6.0.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:50187695423ffe49e2deacb8cd10510bc361faac997de9efef88badc3bb9e2d1", size = 171679, upload-time = "2024-08-06T20:32:44.801Z" }, { url = "https://files.pythonhosted.org/packages/7c/9a/337322f27005c33bcb656c655fa78325b730324c78620e8328ae28b64d0c/PyYAML-6.0.2-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0ffe8360bab4910ef1b9e87fb812d8bc0a308b0d0eef8c8f44e0254ab3b07133", size = 733428, upload-time = "2024-08-06T20:32:46.432Z" }, { url = "https://files.pythonhosted.org/packages/a3/69/864fbe19e6c18ea3cc196cbe5d392175b4cf3d5d0ac1403ec3f2d237ebb5/PyYAML-6.0.2-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:17e311b6c678207928d649faa7cb0d7b4c26a0ba73d41e99c4fff6b6c3276484", size = 763361, upload-time = "2024-08-06T20:32:51.188Z" }, { url = "https://files.pythonhosted.org/packages/04/24/b7721e4845c2f162d26f50521b825fb061bc0a5afcf9a386840f23ea19fa/PyYAML-6.0.2-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:70b189594dbe54f75ab3a1acec5f1e3faa7e8cf2f1e08d9b561cb41b845f69d5", size = 759523, upload-time = "2024-08-06T20:32:53.019Z" }, { url = "https://files.pythonhosted.org/packages/2b/b2/e3234f59ba06559c6ff63c4e10baea10e5e7df868092bf9ab40e5b9c56b6/PyYAML-6.0.2-cp313-cp313-musllinux_1_1_aarch64.whl", hash = "sha256:41e4e3953a79407c794916fa277a82531dd93aad34e29c2a514c2c0c5fe971cc", size = 726660, upload-time = "2024-08-06T20:32:54.708Z" }, { url = "https://files.pythonhosted.org/packages/fe/0f/25911a9f080464c59fab9027482f822b86bf0608957a5fcc6eaac85aa515/PyYAML-6.0.2-cp313-cp313-musllinux_1_1_x86_64.whl", hash = "sha256:68ccc6023a3400877818152ad9a1033e3db8625d899c72eacb5a668902e4d652", size = 751597, upload-time = "2024-08-06T20:32:56.985Z" }, { url = "https://files.pythonhosted.org/packages/14/0d/e2c3b43bbce3cf6bd97c840b46088a3031085179e596d4929729d8d68270/PyYAML-6.0.2-cp313-cp313-win32.whl", hash = "sha256:bc2fa7c6b47d6bc618dd7fb02ef6fdedb1090ec036abab80d4681424b84c1183", size = 140527, upload-time = "2024-08-06T20:33:03.001Z" }, { url = "https://files.pythonhosted.org/packages/fa/de/02b54f42487e3d3c6efb3f89428677074ca7bf43aae402517bc7cca949f3/PyYAML-6.0.2-cp313-cp313-win_amd64.whl", hash = "sha256:8388ee1976c416731879ac16da0aff3f63b286ffdd57cdeb95f3f2e085687563", size = 156446, upload-time = "2024-08-06T20:33:04.33Z" }, ] [[package]] name = "requests" version = "2.32.3" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "certifi" }, { name = "charset-normalizer" }, { name = "idna" }, { name = "urllib3" }, ] sdist = { url = "https://files.pythonhosted.org/packages/63/70/2bf7780ad2d390a8d301ad0b550f1581eadbd9a20f896afe06353c2a2913/requests-2.32.3.tar.gz", hash = "sha256:55365417734eb18255590a9ff9eb97e9e1da868d4ccd6402399eaf68af20a760", size = 131218, upload-time = "2024-05-29T15:37:49.536Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/f9/9b/335f9764261e915ed497fcdeb11df5dfd6f7bf257d4a6a2a686d80da4d54/requests-2.32.3-py3-none-any.whl", hash = "sha256:70761cfe03c773ceb22aa2f671b4757976145175cdfca038c02654d061d6dcc6", size = 64928, upload-time = "2024-05-29T15:37:47.027Z" }, ] [[package]] name = "roman-numerals-py" version = "3.1.0" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/30/76/48fd56d17c5bdbdf65609abbc67288728a98ed4c02919428d4f52d23b24b/roman_numerals_py-3.1.0.tar.gz", hash = "sha256:be4bf804f083a4ce001b5eb7e3c0862479d10f94c936f6c4e5f250aa5ff5bd2d", size = 9017, upload-time = "2025-02-22T07:34:54.333Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/53/97/d2cbbaa10c9b826af0e10fdf836e1bf344d9f0abb873ebc34d1f49642d3f/roman_numerals_py-3.1.0-py3-none-any.whl", hash = "sha256:9da2ad2fb670bcf24e81070ceb3be72f6c11c440d73bd579fbeca1e9f330954c", size = 7742, upload-time = "2025-02-22T07:34:52.422Z" }, ] [[package]] name = "ruff" version = "0.11.13" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/ed/da/9c6f995903b4d9474b39da91d2d626659af3ff1eeb43e9ae7c119349dba6/ruff-0.11.13.tar.gz", hash = "sha256:26fa247dc68d1d4e72c179e08889a25ac0c7ba4d78aecfc835d49cbfd60bf514", size = 4282054, upload-time = "2025-06-05T21:00:15.721Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/7d/ce/a11d381192966e0b4290842cc8d4fac7dc9214ddf627c11c1afff87da29b/ruff-0.11.13-py3-none-linux_armv6l.whl", hash = "sha256:4bdfbf1240533f40042ec00c9e09a3aade6f8c10b6414cf11b519488d2635d46", size = 10292516, upload-time = "2025-06-05T20:59:32.944Z" }, { url = "https://files.pythonhosted.org/packages/78/db/87c3b59b0d4e753e40b6a3b4a2642dfd1dcaefbff121ddc64d6c8b47ba00/ruff-0.11.13-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:aef9c9ed1b5ca28bb15c7eac83b8670cf3b20b478195bd49c8d756ba0a36cf48", size = 11106083, upload-time = "2025-06-05T20:59:37.03Z" }, { url = "https://files.pythonhosted.org/packages/77/79/d8cec175856ff810a19825d09ce700265f905c643c69f45d2b737e4a470a/ruff-0.11.13-py3-none-macosx_11_0_arm64.whl", hash = "sha256:53b15a9dfdce029c842e9a5aebc3855e9ab7771395979ff85b7c1dedb53ddc2b", size = 10436024, upload-time = "2025-06-05T20:59:39.741Z" }, { url = "https://files.pythonhosted.org/packages/8b/5b/f6d94f2980fa1ee854b41568368a2e1252681b9238ab2895e133d303538f/ruff-0.11.13-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ab153241400789138d13f362c43f7edecc0edfffce2afa6a68434000ecd8f69a", size = 10646324, upload-time = "2025-06-05T20:59:42.185Z" }, { url = "https://files.pythonhosted.org/packages/6c/9c/b4c2acf24ea4426016d511dfdc787f4ce1ceb835f3c5fbdbcb32b1c63bda/ruff-0.11.13-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:6c51f93029d54a910d3d24f7dd0bb909e31b6cd989a5e4ac513f4eb41629f0dc", size = 10174416, upload-time = "2025-06-05T20:59:44.319Z" }, { url = "https://files.pythonhosted.org/packages/f3/10/e2e62f77c65ede8cd032c2ca39c41f48feabedb6e282bfd6073d81bb671d/ruff-0.11.13-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:1808b3ed53e1a777c2ef733aca9051dc9bf7c99b26ece15cb59a0320fbdbd629", size = 11724197, upload-time = "2025-06-05T20:59:46.935Z" }, { url = "https://files.pythonhosted.org/packages/bb/f0/466fe8469b85c561e081d798c45f8a1d21e0b4a5ef795a1d7f1a9a9ec182/ruff-0.11.13-py3-none-manylinux_2_17_ppc64.manylinux2014_ppc64.whl", hash = "sha256:d28ce58b5ecf0f43c1b71edffabe6ed7f245d5336b17805803312ec9bc665933", size = 12511615, upload-time = "2025-06-05T20:59:49.534Z" }, { url = "https://files.pythonhosted.org/packages/17/0e/cefe778b46dbd0cbcb03a839946c8f80a06f7968eb298aa4d1a4293f3448/ruff-0.11.13-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:55e4bc3a77842da33c16d55b32c6cac1ec5fb0fbec9c8c513bdce76c4f922165", size = 12117080, upload-time = "2025-06-05T20:59:51.654Z" }, { url = "https://files.pythonhosted.org/packages/5d/2c/caaeda564cbe103bed145ea557cb86795b18651b0f6b3ff6a10e84e5a33f/ruff-0.11.13-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:633bf2c6f35678c56ec73189ba6fa19ff1c5e4807a78bf60ef487b9dd272cc71", size = 11326315, upload-time = "2025-06-05T20:59:54.469Z" }, { url = "https://files.pythonhosted.org/packages/75/f0/782e7d681d660eda8c536962920c41309e6dd4ebcea9a2714ed5127d44bd/ruff-0.11.13-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4ffbc82d70424b275b089166310448051afdc6e914fdab90e08df66c43bb5ca9", size = 11555640, upload-time = "2025-06-05T20:59:56.986Z" }, { url = "https://files.pythonhosted.org/packages/5d/d4/3d580c616316c7f07fb3c99dbecfe01fbaea7b6fd9a82b801e72e5de742a/ruff-0.11.13-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:4a9ddd3ec62a9a89578c85842b836e4ac832d4a2e0bfaad3b02243f930ceafcc", size = 10507364, upload-time = "2025-06-05T20:59:59.154Z" }, { url = "https://files.pythonhosted.org/packages/5a/dc/195e6f17d7b3ea6b12dc4f3e9de575db7983db187c378d44606e5d503319/ruff-0.11.13-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:d237a496e0778d719efb05058c64d28b757c77824e04ffe8796c7436e26712b7", size = 10141462, upload-time = "2025-06-05T21:00:01.481Z" }, { url = "https://files.pythonhosted.org/packages/f4/8e/39a094af6967faa57ecdeacb91bedfb232474ff8c3d20f16a5514e6b3534/ruff-0.11.13-py3-none-musllinux_1_2_i686.whl", hash = "sha256:26816a218ca6ef02142343fd24c70f7cd8c5aa6c203bca284407adf675984432", size = 11121028, upload-time = "2025-06-05T21:00:04.06Z" }, { url = "https://files.pythonhosted.org/packages/5a/c0/b0b508193b0e8a1654ec683ebab18d309861f8bd64e3a2f9648b80d392cb/ruff-0.11.13-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:51c3f95abd9331dc5b87c47ac7f376db5616041173826dfd556cfe3d4977f492", size = 11602992, upload-time = "2025-06-05T21:00:06.249Z" }, { url = "https://files.pythonhosted.org/packages/7c/91/263e33ab93ab09ca06ce4f8f8547a858cc198072f873ebc9be7466790bae/ruff-0.11.13-py3-none-win32.whl", hash = "sha256:96c27935418e4e8e77a26bb05962817f28b8ef3843a6c6cc49d8783b5507f250", size = 10474944, upload-time = "2025-06-05T21:00:08.459Z" }, { url = "https://files.pythonhosted.org/packages/46/f4/7c27734ac2073aae8efb0119cae6931b6fb48017adf048fdf85c19337afc/ruff-0.11.13-py3-none-win_amd64.whl", hash = "sha256:29c3189895a8a6a657b7af4e97d330c8a3afd2c9c8f46c81e2fc5a31866517e3", size = 11548669, upload-time = "2025-06-05T21:00:11.147Z" }, { url = "https://files.pythonhosted.org/packages/ec/bf/b273dd11673fed8a6bd46032c0ea2a04b2ac9bfa9c628756a5856ba113b0/ruff-0.11.13-py3-none-win_arm64.whl", hash = "sha256:b4385285e9179d608ff1d2fb9922062663c658605819a6876d8beef0c30b7f3b", size = 10683928, upload-time = "2025-06-05T21:00:13.758Z" }, ] [[package]] name = "sniffio" version = "1.3.1" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/a2/87/a6771e1546d97e7e041b6ae58d80074f81b7d5121207425c964ddf5cfdbd/sniffio-1.3.1.tar.gz", hash = "sha256:f4324edc670a0f49750a81b895f35c3adb843cca46f0530f79fc1babb23789dc", size = 20372, upload-time = "2024-02-25T23:20:04.057Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/e9/44/75a9c9421471a6c4805dbf2356f7c181a29c1879239abab1ea2cc8f38b40/sniffio-1.3.1-py3-none-any.whl", hash = "sha256:2f6da418d1f1e0fddd844478f41680e794e6051915791a034ff65e5f100525a2", size = 10235, upload-time = "2024-02-25T23:20:01.196Z" }, ] [[package]] name = "snowballstemmer" version = "3.0.1" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/75/a7/9810d872919697c9d01295633f5d574fb416d47e535f258272ca1f01f447/snowballstemmer-3.0.1.tar.gz", hash = "sha256:6d5eeeec8e9f84d4d56b847692bacf79bc2c8e90c7f80ca4444ff8b6f2e52895", size = 105575, upload-time = "2025-05-09T16:34:51.843Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/c8/78/3565d011c61f5a43488987ee32b6f3f656e7f107ac2782dd57bdd7d91d9a/snowballstemmer-3.0.1-py3-none-any.whl", hash = "sha256:6cd7b3897da8d6c9ffb968a6781fa6532dce9c3618a4b127d920dab764a19064", size = 103274, upload-time = "2025-05-09T16:34:50.371Z" }, ] [[package]] name = "sortedcontainers" version = "2.4.0" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/e8/c4/ba2f8066cceb6f23394729afe52f3bf7adec04bf9ed2c820b39e19299111/sortedcontainers-2.4.0.tar.gz", hash = "sha256:25caa5a06cc30b6b83d11423433f65d1f9d76c4c6a0c90e3379eaa43b9bfdb88", size = 30594, upload-time = "2021-05-16T22:03:42.897Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/32/46/9cb0e58b2deb7f82b84065f37f3bffeb12413f947f9388e4cac22c4621ce/sortedcontainers-2.4.0-py2.py3-none-any.whl", hash = "sha256:a163dcaede0f1c021485e957a39245190e74249897e2ae4b2aa38595db237ee0", size = 29575, upload-time = "2021-05-16T22:03:41.177Z" }, ] [[package]] name = "sphinx" version = "8.2.3" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "alabaster" }, { name = "babel" }, { name = "colorama", marker = "sys_platform == 'win32'" }, { name = "docutils" }, { name = "imagesize" }, { name = "jinja2" }, { name = "packaging" }, { name = "pygments" }, { name = "requests" }, { name = "roman-numerals-py" }, { name = "snowballstemmer" }, { name = "sphinxcontrib-applehelp" }, { name = "sphinxcontrib-devhelp" }, { name = "sphinxcontrib-htmlhelp" }, { name = "sphinxcontrib-jsmath" }, { name = "sphinxcontrib-qthelp" }, { name = "sphinxcontrib-serializinghtml" }, ] sdist = { url = "https://files.pythonhosted.org/packages/38/ad/4360e50ed56cb483667b8e6dadf2d3fda62359593faabbe749a27c4eaca6/sphinx-8.2.3.tar.gz", hash = "sha256:398ad29dee7f63a75888314e9424d40f52ce5a6a87ae88e7071e80af296ec348", size = 8321876, upload-time = "2025-03-02T22:31:59.658Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/31/53/136e9eca6e0b9dc0e1962e2c908fbea2e5ac000c2a2fbd9a35797958c48b/sphinx-8.2.3-py3-none-any.whl", hash = "sha256:4405915165f13521d875a8c29c8970800a0141c14cc5416a38feca4ea5d9b9c3", size = 3589741, upload-time = "2025-03-02T22:31:56.836Z" }, ] [[package]] name = "sphinx-autobuild" version = "2024.10.3" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "colorama" }, { name = "sphinx" }, { name = "starlette" }, { name = "uvicorn" }, { name = "watchfiles" }, { name = "websockets" }, ] sdist = { url = "https://files.pythonhosted.org/packages/a5/2c/155e1de2c1ba96a72e5dba152c509a8b41e047ee5c2def9e9f0d812f8be7/sphinx_autobuild-2024.10.3.tar.gz", hash = "sha256:248150f8f333e825107b6d4b86113ab28fa51750e5f9ae63b59dc339be951fb1", size = 14023, upload-time = "2024-10-02T23:15:30.172Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/18/c0/eba125db38c84d3c74717008fd3cb5000b68cd7e2cbafd1349c6a38c3d3b/sphinx_autobuild-2024.10.3-py3-none-any.whl", hash = "sha256:158e16c36f9d633e613c9aaf81c19b0fc458ca78b112533b20dafcda430d60fa", size = 11908, upload-time = "2024-10-02T23:15:28.739Z" }, ] [[package]] name = "sphinx-notfound-page" version = "1.1.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "sphinx" }, ] sdist = { url = "https://files.pythonhosted.org/packages/6a/b2/67603444a8ee97b4a8ea71b0a9d6bab1727ed65e362c87e02f818ee57b8a/sphinx_notfound_page-1.1.0.tar.gz", hash = "sha256:913e1754370bb3db201d9300d458a8b8b5fb22e9246a816643a819a9ea2b8067", size = 7392, upload-time = "2025-01-28T18:45:02.871Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/cd/d4/019fe439c840a7966012bbb95ccbdd81c5c10271749706793b43beb05145/sphinx_notfound_page-1.1.0-py3-none-any.whl", hash = "sha256:835dc76ff7914577a1f58d80a2c8418fb6138c0932c8da8adce4d9096fbcd389", size = 8167, upload-time = "2025-01-28T18:45:00.465Z" }, ] [[package]] name = "sphinx-tabs" version = "3.4.7" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "docutils" }, { name = "pygments" }, { name = "sphinx" }, ] sdist = { url = "https://files.pythonhosted.org/packages/6a/53/a9a91995cb365e589f413b77fc75f1c0e9b4ac61bfa8da52a779ad855cc0/sphinx-tabs-3.4.7.tar.gz", hash = "sha256:991ad4a424ff54119799ba1491701aa8130dd43509474aef45a81c42d889784d", size = 15891, upload-time = "2024-10-08T13:37:27.887Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/6b/c6/f47505b564b918a3ba60c1e99232d4942c4a7e44ecaae603e829e3d05dae/sphinx_tabs-3.4.7-py3-none-any.whl", hash = "sha256:c12d7a36fd413b369e9e9967a0a4015781b71a9c393575419834f19204bd1915", size = 9727, upload-time = "2024-10-08T13:37:26.192Z" }, ] [[package]] name = "sphinxcontrib-applehelp" version = "2.0.0" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/ba/6e/b837e84a1a704953c62ef8776d45c3e8d759876b4a84fe14eba2859106fe/sphinxcontrib_applehelp-2.0.0.tar.gz", hash = "sha256:2f29ef331735ce958efa4734873f084941970894c6090408b079c61b2e1c06d1", size = 20053, upload-time = "2024-07-29T01:09:00.465Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/5d/85/9ebeae2f76e9e77b952f4b274c27238156eae7979c5421fba91a28f4970d/sphinxcontrib_applehelp-2.0.0-py3-none-any.whl", hash = "sha256:4cd3f0ec4ac5dd9c17ec65e9ab272c9b867ea77425228e68ecf08d6b28ddbdb5", size = 119300, upload-time = "2024-07-29T01:08:58.99Z" }, ] [[package]] name = "sphinxcontrib-devhelp" version = "2.0.0" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/f6/d2/5beee64d3e4e747f316bae86b55943f51e82bb86ecd325883ef65741e7da/sphinxcontrib_devhelp-2.0.0.tar.gz", hash = "sha256:411f5d96d445d1d73bb5d52133377b4248ec79db5c793ce7dbe59e074b4dd1ad", size = 12967, upload-time = "2024-07-29T01:09:23.417Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/35/7a/987e583882f985fe4d7323774889ec58049171828b58c2217e7f79cdf44e/sphinxcontrib_devhelp-2.0.0-py3-none-any.whl", hash = "sha256:aefb8b83854e4b0998877524d1029fd3e6879210422ee3780459e28a1f03a8a2", size = 82530, upload-time = "2024-07-29T01:09:21.945Z" }, ] [[package]] name = "sphinxcontrib-htmlhelp" version = "2.1.0" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/43/93/983afd9aa001e5201eab16b5a444ed5b9b0a7a010541e0ddfbbfd0b2470c/sphinxcontrib_htmlhelp-2.1.0.tar.gz", hash = "sha256:c9e2916ace8aad64cc13a0d233ee22317f2b9025b9cf3295249fa985cc7082e9", size = 22617, upload-time = "2024-07-29T01:09:37.889Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/0a/7b/18a8c0bcec9182c05a0b3ec2a776bba4ead82750a55ff798e8d406dae604/sphinxcontrib_htmlhelp-2.1.0-py3-none-any.whl", hash = "sha256:166759820b47002d22914d64a075ce08f4c46818e17cfc9470a9786b759b19f8", size = 98705, upload-time = "2024-07-29T01:09:36.407Z" }, ] [[package]] name = "sphinxcontrib-jsmath" version = "1.0.1" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/b2/e8/9ed3830aeed71f17c026a07a5097edcf44b692850ef215b161b8ad875729/sphinxcontrib-jsmath-1.0.1.tar.gz", hash = "sha256:a9925e4a4587247ed2191a22df5f6970656cb8ca2bd6284309578f2153e0c4b8", size = 5787, upload-time = "2019-01-21T16:10:16.347Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/c2/42/4c8646762ee83602e3fb3fbe774c2fac12f317deb0b5dbeeedd2d3ba4b77/sphinxcontrib_jsmath-1.0.1-py2.py3-none-any.whl", hash = "sha256:2ec2eaebfb78f3f2078e73666b1415417a116cc848b72e5172e596c871103178", size = 5071, upload-time = "2019-01-21T16:10:14.333Z" }, ] [[package]] name = "sphinxcontrib-log-cabinet" version = "1.0.1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "sphinx" }, ] sdist = { url = "https://files.pythonhosted.org/packages/75/26/0687391e10c605a4d0c7ebe118c57c51ecc687128bcdae5803d9b96def81/sphinxcontrib-log-cabinet-1.0.1.tar.gz", hash = "sha256:103b2e62df4e57abb943bea05ee9c2beb7da922222c8b77314ffd6ab9901c558", size = 4072, upload-time = "2019-07-05T23:22:34.596Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/27/e7/dbfc155c1b4c429a9a8149032a56bfb7bab4efabc656abb24ab4619c715d/sphinxcontrib_log_cabinet-1.0.1-py2.py3-none-any.whl", hash = "sha256:3decc888e8e453d1912cd95d50efb0794a4670a214efa65e71a7de277dcfe2cd", size = 4887, upload-time = "2019-07-05T23:22:32.969Z" }, ] [[package]] name = "sphinxcontrib-qthelp" version = "2.0.0" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/68/bc/9104308fc285eb3e0b31b67688235db556cd5b0ef31d96f30e45f2e51cae/sphinxcontrib_qthelp-2.0.0.tar.gz", hash = "sha256:4fe7d0ac8fc171045be623aba3e2a8f613f8682731f9153bb2e40ece16b9bbab", size = 17165, upload-time = "2024-07-29T01:09:56.435Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/27/83/859ecdd180cacc13b1f7e857abf8582a64552ea7a061057a6c716e790fce/sphinxcontrib_qthelp-2.0.0-py3-none-any.whl", hash = "sha256:b18a828cdba941ccd6ee8445dbe72ffa3ef8cbe7505d8cd1fa0d42d3f2d5f3eb", size = 88743, upload-time = "2024-07-29T01:09:54.885Z" }, ] [[package]] name = "sphinxcontrib-serializinghtml" version = "2.0.0" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/3b/44/6716b257b0aa6bfd51a1b31665d1c205fb12cb5ad56de752dfa15657de2f/sphinxcontrib_serializinghtml-2.0.0.tar.gz", hash = "sha256:e9d912827f872c029017a53f0ef2180b327c3f7fd23c87229f7a8e8b70031d4d", size = 16080, upload-time = "2024-07-29T01:10:09.332Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/52/a7/d2782e4e3f77c8450f727ba74a8f12756d5ba823d81b941f1b04da9d033a/sphinxcontrib_serializinghtml-2.0.0-py3-none-any.whl", hash = "sha256:6e2cb0eef194e10c27ec0023bfeb25badbbb5868244cf5bc5bdc04e4464bf331", size = 92072, upload-time = "2024-07-29T01:10:08.203Z" }, ] [[package]] name = "starlette" version = "0.47.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "anyio" }, ] sdist = { url = "https://files.pythonhosted.org/packages/8b/d0/0332bd8a25779a0e2082b0e179805ad39afad642938b371ae0882e7f880d/starlette-0.47.0.tar.gz", hash = "sha256:1f64887e94a447fed5f23309fb6890ef23349b7e478faa7b24a851cd4eb844af", size = 2582856, upload-time = "2025-05-29T15:45:27.628Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/e3/81/c60b35fe9674f63b38a8feafc414fca0da378a9dbd5fa1e0b8d23fcc7a9b/starlette-0.47.0-py3-none-any.whl", hash = "sha256:9d052d4933683af40ffd47c7465433570b4949dc937e20ad1d73b34e72f10c37", size = 72796, upload-time = "2025-05-29T15:45:26.305Z" }, ] [[package]] name = "tox" version = "4.26.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "cachetools" }, { name = "chardet" }, { name = "colorama" }, { name = "filelock" }, { name = "packaging" }, { name = "platformdirs" }, { name = "pluggy" }, { name = "pyproject-api" }, { name = "virtualenv" }, ] sdist = { url = "https://files.pythonhosted.org/packages/fd/3c/dcec0c00321a107f7f697fd00754c5112572ea6dcacb40b16d8c3eea7c37/tox-4.26.0.tar.gz", hash = "sha256:a83b3b67b0159fa58e44e646505079e35a43317a62d2ae94725e0586266faeca", size = 197260, upload-time = "2025-05-13T15:04:28.481Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/de/14/f58b4087cf248b18c795b5c838c7a8d1428dfb07cb468dad3ec7f54041ab/tox-4.26.0-py3-none-any.whl", hash = "sha256:75f17aaf09face9b97bd41645028d9f722301e912be8b4c65a3f938024560224", size = 172761, upload-time = "2025-05-13T15:04:26.207Z" }, ] [[package]] name = "tox-uv" version = "1.26.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "packaging" }, { name = "tox" }, { name = "uv" }, ] sdist = { url = "https://files.pythonhosted.org/packages/7e/da/37790b4a176f05b0ec7a699f54979078fc726f743640aa5c10c551c27edb/tox_uv-1.26.0.tar.gz", hash = "sha256:5045880c467eed58a98f7eaa7fe286b7ef688e2c56f2123d53e275011495c381", size = 21523, upload-time = "2025-05-27T14:51:42.702Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/46/b8/04c5cb83da072a3f96d357d68a551f5e97e162573c2011a09437df995811/tox_uv-1.26.0-py3-none-any.whl", hash = "sha256:894b2e7274fd6131c3bd1012813edc858753cad67727050c21cd973a08e691c8", size = 16562, upload-time = "2025-05-27T14:51:40.803Z" }, ] [[package]] name = "trio" version = "0.31.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "attrs" }, { name = "cffi", marker = "implementation_name != 'pypy' and os_name == 'nt'" }, { name = "idna" }, { name = "outcome" }, { name = "sniffio" }, { name = "sortedcontainers" }, ] sdist = { url = "https://files.pythonhosted.org/packages/76/8f/c6e36dd11201e2a565977d8b13f0b027ba4593c1a80bed5185489178e257/trio-0.31.0.tar.gz", hash = "sha256:f71d551ccaa79d0cb73017a33ef3264fde8335728eb4c6391451fe5d253a9d5b", size = 605825, upload-time = "2025-09-09T15:17:15.242Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/31/5b/94237a3485620dbff9741df02ff6d8acaa5fdec67d81ab3f62e4d8511bf7/trio-0.31.0-py3-none-any.whl", hash = "sha256:b5d14cd6293d79298b49c3485ffd9c07e3ce03a6da8c7dfbe0cb3dd7dc9a4774", size = 512679, upload-time = "2025-09-09T15:17:13.821Z" }, ] [[package]] name = "typing-extensions" version = "4.14.0" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/d1/bc/51647cd02527e87d05cb083ccc402f93e441606ff1f01739a62c8ad09ba5/typing_extensions-4.14.0.tar.gz", hash = "sha256:8676b788e32f02ab42d9e7c61324048ae4c6d844a399eebace3d4979d75ceef4", size = 107423, upload-time = "2025-06-02T14:52:11.399Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/69/e0/552843e0d356fbb5256d21449fa957fa4eff3bbc135a74a691ee70c7c5da/typing_extensions-4.14.0-py3-none-any.whl", hash = "sha256:a1514509136dd0b477638fc68d6a91497af5076466ad0fa6c338e44e359944af", size = 43839, upload-time = "2025-06-02T14:52:10.026Z" }, ] [[package]] name = "urllib3" version = "2.4.0" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/8a/78/16493d9c386d8e60e442a35feac5e00f0913c0f4b7c217c11e8ec2ff53e0/urllib3-2.4.0.tar.gz", hash = "sha256:414bc6535b787febd7567804cc015fee39daab8ad86268f1310a9250697de466", size = 390672, upload-time = "2025-04-10T15:23:39.232Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/6b/11/cc635220681e93a0183390e26485430ca2c7b5f9d33b15c74c2861cb8091/urllib3-2.4.0-py3-none-any.whl", hash = "sha256:4e16665048960a0900c702d4a66415956a584919c03361cac9f1df5c5dd7e813", size = 128680, upload-time = "2025-04-10T15:23:37.377Z" }, ] [[package]] name = "uv" version = "0.7.12" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/67/35/360a4aa325254b7f11d0898d30588861428659011b34f1e19c40fdd15db6/uv-0.7.12.tar.gz", hash = "sha256:4aa152e6a70d5662ca66a918f697bf8fb710f391068aa7d04e032af2edebb095", size = 3298683, upload-time = "2025-06-06T20:39:04.308Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/f8/64/ee9f1b27f006c49a6765e9655ab93e7c8cbd6f0bf8b731f30f608b0be9fd/uv-0.7.12-py3-none-linux_armv6l.whl", hash = "sha256:81824caf5756ffee54b4c937d92d7c8c224c416270c90a83b9b4a973f6e4e559", size = 17024991, upload-time = "2025-06-06T20:38:17.053Z" }, { url = "https://files.pythonhosted.org/packages/43/aa/f42707faa13a9c1b4f662456b2dca4bde169eb921f135319d8856c6e5e8e/uv-0.7.12-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:02e67c5f9d141fb25976cddb28abceaf715412ed83070cb9b87c5c488c8451af", size = 17097383, upload-time = "2025-06-06T20:38:21.174Z" }, { url = "https://files.pythonhosted.org/packages/b9/a9/0f27e16e161f98240a328b5201b8abf178b751fde4fc56c54c1321812cd5/uv-0.7.12-py3-none-macosx_11_0_arm64.whl", hash = "sha256:e70a4393fd6a09b056e1ac500fe2b796d26c30783194868c6801ea08c3bbf863", size = 15812649, upload-time = "2025-06-06T20:38:23.51Z" }, { url = "https://files.pythonhosted.org/packages/0b/eb/605d8f1d08606024209d0e31c3799c696199a887260ee1db52663e4da2e8/uv-0.7.12-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.musllinux_1_1_aarch64.whl", hash = "sha256:bb47326b9c4802db28e11f1aab174d5c9c0a8b26ed0a83094d3882dd8f5049ad", size = 16344497, upload-time = "2025-06-06T20:38:25.899Z" }, { url = "https://files.pythonhosted.org/packages/b7/86/3503eb869fa17d607cc296a6514db52ec73c2ec85ad608952a207fd2e8ff/uv-0.7.12-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:14214a51e0ae0f0e8dbcac35a29722c45dbf40d0fd37309897642f7989af6caf", size = 16773525, upload-time = "2025-06-06T20:38:28.619Z" }, { url = "https://files.pythonhosted.org/packages/9b/d6/868fb3f0b9f2a0d2f14cb8079171b862adbd782e47e0469dad3d3d71c938/uv-0.7.12-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:0fa630d865111c26f26c5e6f4547a73b13284f098471a4ca982d7b0caf0e658b", size = 17551173, upload-time = "2025-06-06T20:38:31.166Z" }, { url = "https://files.pythonhosted.org/packages/d4/a8/b5be1c67c7894caf178e850903ac25f465e3508a6eada2ae735b187dc39d/uv-0.7.12-py3-none-manylinux_2_17_ppc64.manylinux2014_ppc64.whl", hash = "sha256:1557a154d2c36030ff0b707f3c2bfafd977e54fcd4d628dd0fa8a265449e9f13", size = 18359491, upload-time = "2025-06-06T20:38:33.569Z" }, { url = "https://files.pythonhosted.org/packages/95/23/f62bab13f67ed785f7ad01546c499809d1db71b03f94950380f0bc407625/uv-0.7.12-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:7e0ba7767b21d58d65703c3cd43814ccfe06d7664ac42b3589d5f2b72486b903", size = 18098855, upload-time = "2025-06-06T20:38:36.029Z" }, { url = "https://files.pythonhosted.org/packages/a6/4a/db21a5d3839771799af2df366cc5ed0933ebe9fc9e920f212e33dc00136e/uv-0.7.12-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:e0672dc5dc1b0ae7191d11ecae8bb794c7e860936b66c2bc3855bd0dee17fca1", size = 18206282, upload-time = "2025-06-06T20:38:38.582Z" }, { url = "https://files.pythonhosted.org/packages/bc/ae/fcfd916cbc109c5626dc25b208395b47ba12b27af82f3bb8e247b4e95692/uv-0.7.12-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e34b4ad4288828210c2e075934009903514ca97bd603aced7d0755040b4d0489", size = 17777690, upload-time = "2025-06-06T20:38:41.021Z" }, { url = "https://files.pythonhosted.org/packages/92/78/608163b35ffaf1054cd10197646b6336e7be7b6a51dfef6d98a91600c6be/uv-0.7.12-py3-none-manylinux_2_28_aarch64.whl", hash = "sha256:8a7ed9e94ec409bfc7181ee274d1b0ed6292698a20df0ae035ce422224863af5", size = 16599406, upload-time = "2025-06-06T20:38:43.72Z" }, { url = "https://files.pythonhosted.org/packages/d4/d6/6fe3b16390472a9d31dd1e0e7e3759b884d71e8a0dff1baf4a753b4adaaa/uv-0.7.12-py3-none-musllinux_1_1_armv7l.whl", hash = "sha256:85e8d3dea95016a45ed8c48343f98734d1b5c4be7bba26257d4c8873059646fa", size = 16714823, upload-time = "2025-06-06T20:38:45.949Z" }, { url = "https://files.pythonhosted.org/packages/b3/a5/b0432a25eaa23e9f909649321784b8e4be4579e9957eb5d369aa30c79164/uv-0.7.12-py3-none-musllinux_1_1_i686.whl", hash = "sha256:01310c45d55f6e7580124c9b1f7e3586b9609c4f8e5a78558a75951b03541bb2", size = 17086446, upload-time = "2025-06-06T20:38:48.648Z" }, { url = "https://files.pythonhosted.org/packages/da/d8/673591f34f897aa4216144a513e60c2004399155c47e7b550612960359c6/uv-0.7.12-py3-none-musllinux_1_1_x86_64.whl", hash = "sha256:4c697ef9d9f6b6f42df5a661efa8a745c0e4c330039d45b549b2ca7e7b66f8a5", size = 17903789, upload-time = "2025-06-06T20:38:51.864Z" }, { url = "https://files.pythonhosted.org/packages/15/09/e476187c0a1da78b9c2021f3c3ab31ed2469a70d222bde5dc892236b3c4f/uv-0.7.12-py3-none-win32.whl", hash = "sha256:6008abf92c8d37060944377d89bf9f514aa18370391d9d63dc7d449dac94aca1", size = 17344011, upload-time = "2025-06-06T20:38:54.276Z" }, { url = "https://files.pythonhosted.org/packages/08/9e/c52c7f50280e57110ca79b6805877f50514d9a777d31a683a4eb1de52312/uv-0.7.12-py3-none-win_amd64.whl", hash = "sha256:bb57bd26becd86194788f832af373b6ba431314fa0f6f7e904c90cac1818a7dc", size = 18803328, upload-time = "2025-06-06T20:38:59.368Z" }, { url = "https://files.pythonhosted.org/packages/8e/35/4800ff7bc1663d9f967eabc8440074f906c8a98ea28d1aae66d2d19b7ae9/uv-0.7.12-py3-none-win_arm64.whl", hash = "sha256:8aba24e12ded2f2974a2f213e55daabf78002613d3772c1396fc924c6682cd27", size = 17450522, upload-time = "2025-06-06T20:39:01.963Z" }, ] [[package]] name = "uvicorn" version = "0.34.3" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "click" }, { name = "h11" }, ] sdist = { url = "https://files.pythonhosted.org/packages/de/ad/713be230bcda622eaa35c28f0d328c3675c371238470abdea52417f17a8e/uvicorn-0.34.3.tar.gz", hash = "sha256:35919a9a979d7a59334b6b10e05d77c1d0d574c50e0fc98b8b1a0f165708b55a", size = 76631, upload-time = "2025-06-01T07:48:17.531Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/6d/0d/8adfeaa62945f90d19ddc461c55f4a50c258af7662d34b6a3d5d1f8646f6/uvicorn-0.34.3-py3-none-any.whl", hash = "sha256:16246631db62bdfbf069b0645177d6e8a77ba950cfedbfd093acef9444e4d885", size = 62431, upload-time = "2025-06-01T07:48:15.664Z" }, ] [[package]] name = "virtualenv" version = "20.31.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "distlib" }, { name = "filelock" }, { name = "platformdirs" }, ] sdist = { url = "https://files.pythonhosted.org/packages/56/2c/444f465fb2c65f40c3a104fd0c495184c4f2336d65baf398e3c75d72ea94/virtualenv-20.31.2.tar.gz", hash = "sha256:e10c0a9d02835e592521be48b332b6caee6887f332c111aa79a09b9e79efc2af", size = 6076316, upload-time = "2025-05-08T17:58:23.811Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/f3/40/b1c265d4b2b62b58576588510fc4d1fe60a86319c8de99fd8e9fec617d2c/virtualenv-20.31.2-py3-none-any.whl", hash = "sha256:36efd0d9650ee985f0cad72065001e66d49a6f24eb44d98980f630686243cf11", size = 6057982, upload-time = "2025-05-08T17:58:21.15Z" }, ] [[package]] name = "watchfiles" version = "1.0.5" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "anyio" }, ] sdist = { url = "https://files.pythonhosted.org/packages/03/e2/8ed598c42057de7aa5d97c472254af4906ff0a59a66699d426fc9ef795d7/watchfiles-1.0.5.tar.gz", hash = "sha256:b7529b5dcc114679d43827d8c35a07c493ad6f083633d573d81c660abc5979e9", size = 94537, upload-time = "2025-04-08T10:36:26.722Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/39/f4/41b591f59021786ef517e1cdc3b510383551846703e03f204827854a96f8/watchfiles-1.0.5-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:237f9be419e977a0f8f6b2e7b0475ababe78ff1ab06822df95d914a945eac827", size = 405336, upload-time = "2025-04-08T10:34:59.359Z" }, { url = "https://files.pythonhosted.org/packages/ae/06/93789c135be4d6d0e4f63e96eea56dc54050b243eacc28439a26482b5235/watchfiles-1.0.5-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:e0da39ff917af8b27a4bdc5a97ac577552a38aac0d260a859c1517ea3dc1a7c4", size = 395977, upload-time = "2025-04-08T10:35:00.522Z" }, { url = "https://files.pythonhosted.org/packages/d2/db/1cd89bd83728ca37054512d4d35ab69b5f12b8aa2ac9be3b0276b3bf06cc/watchfiles-1.0.5-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2cfcb3952350e95603f232a7a15f6c5f86c5375e46f0bd4ae70d43e3e063c13d", size = 455232, upload-time = "2025-04-08T10:35:01.698Z" }, { url = "https://files.pythonhosted.org/packages/40/90/d8a4d44ffe960517e487c9c04f77b06b8abf05eb680bed71c82b5f2cad62/watchfiles-1.0.5-cp311-cp311-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:68b2dddba7a4e6151384e252a5632efcaa9bc5d1c4b567f3cb621306b2ca9f63", size = 459151, upload-time = "2025-04-08T10:35:03.358Z" }, { url = "https://files.pythonhosted.org/packages/6c/da/267a1546f26465dead1719caaba3ce660657f83c9d9c052ba98fb8856e13/watchfiles-1.0.5-cp311-cp311-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:95cf944fcfc394c5f9de794ce581914900f82ff1f855326f25ebcf24d5397418", size = 489054, upload-time = "2025-04-08T10:35:04.561Z" }, { url = "https://files.pythonhosted.org/packages/b1/31/33850dfd5c6efb6f27d2465cc4c6b27c5a6f5ed53c6fa63b7263cf5f60f6/watchfiles-1.0.5-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:ecf6cd9f83d7c023b1aba15d13f705ca7b7d38675c121f3cc4a6e25bd0857ee9", size = 523955, upload-time = "2025-04-08T10:35:05.786Z" }, { url = "https://files.pythonhosted.org/packages/09/84/b7d7b67856efb183a421f1416b44ca975cb2ea6c4544827955dfb01f7dc2/watchfiles-1.0.5-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:852de68acd6212cd6d33edf21e6f9e56e5d98c6add46f48244bd479d97c967c6", size = 502234, upload-time = "2025-04-08T10:35:07.187Z" }, { url = "https://files.pythonhosted.org/packages/71/87/6dc5ec6882a2254cfdd8b0718b684504e737273903b65d7338efaba08b52/watchfiles-1.0.5-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d5730f3aa35e646103b53389d5bc77edfbf578ab6dab2e005142b5b80a35ef25", size = 454750, upload-time = "2025-04-08T10:35:08.859Z" }, { url = "https://files.pythonhosted.org/packages/3d/6c/3786c50213451a0ad15170d091570d4a6554976cf0df19878002fc96075a/watchfiles-1.0.5-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:18b3bd29954bc4abeeb4e9d9cf0b30227f0f206c86657674f544cb032296acd5", size = 631591, upload-time = "2025-04-08T10:35:10.64Z" }, { url = "https://files.pythonhosted.org/packages/1b/b3/1427425ade4e359a0deacce01a47a26024b2ccdb53098f9d64d497f6684c/watchfiles-1.0.5-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:ba5552a1b07c8edbf197055bc9d518b8f0d98a1c6a73a293bc0726dce068ed01", size = 625370, upload-time = "2025-04-08T10:35:12.412Z" }, { url = "https://files.pythonhosted.org/packages/15/ba/f60e053b0b5b8145d682672024aa91370a29c5c921a88977eb565de34086/watchfiles-1.0.5-cp311-cp311-win32.whl", hash = "sha256:2f1fefb2e90e89959447bc0420fddd1e76f625784340d64a2f7d5983ef9ad246", size = 277791, upload-time = "2025-04-08T10:35:13.719Z" }, { url = "https://files.pythonhosted.org/packages/50/ed/7603c4e164225c12c0d4e8700b64bb00e01a6c4eeea372292a3856be33a4/watchfiles-1.0.5-cp311-cp311-win_amd64.whl", hash = "sha256:b6e76ceb1dd18c8e29c73f47d41866972e891fc4cc7ba014f487def72c1cf096", size = 291622, upload-time = "2025-04-08T10:35:15.071Z" }, { url = "https://files.pythonhosted.org/packages/a2/c2/99bb7c96b4450e36877fde33690ded286ff555b5a5c1d925855d556968a1/watchfiles-1.0.5-cp311-cp311-win_arm64.whl", hash = "sha256:266710eb6fddc1f5e51843c70e3bebfb0f5e77cf4f27129278c70554104d19ed", size = 283699, upload-time = "2025-04-08T10:35:16.732Z" }, { url = "https://files.pythonhosted.org/packages/2a/8c/4f0b9bdb75a1bfbd9c78fad7d8854369283f74fe7cf03eb16be77054536d/watchfiles-1.0.5-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:b5eb568c2aa6018e26da9e6c86f3ec3fd958cee7f0311b35c2630fa4217d17f2", size = 401511, upload-time = "2025-04-08T10:35:17.956Z" }, { url = "https://files.pythonhosted.org/packages/dc/4e/7e15825def77f8bd359b6d3f379f0c9dac4eb09dd4ddd58fd7d14127179c/watchfiles-1.0.5-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:0a04059f4923ce4e856b4b4e5e783a70f49d9663d22a4c3b3298165996d1377f", size = 392715, upload-time = "2025-04-08T10:35:19.202Z" }, { url = "https://files.pythonhosted.org/packages/58/65/b72fb817518728e08de5840d5d38571466c1b4a3f724d190cec909ee6f3f/watchfiles-1.0.5-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3e380c89983ce6e6fe2dd1e1921b9952fb4e6da882931abd1824c092ed495dec", size = 454138, upload-time = "2025-04-08T10:35:20.586Z" }, { url = "https://files.pythonhosted.org/packages/3e/a4/86833fd2ea2e50ae28989f5950b5c3f91022d67092bfec08f8300d8b347b/watchfiles-1.0.5-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:fe43139b2c0fdc4a14d4f8d5b5d967f7a2777fd3d38ecf5b1ec669b0d7e43c21", size = 458592, upload-time = "2025-04-08T10:35:21.87Z" }, { url = "https://files.pythonhosted.org/packages/38/7e/42cb8df8be9a37e50dd3a818816501cf7a20d635d76d6bd65aae3dbbff68/watchfiles-1.0.5-cp312-cp312-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:ee0822ce1b8a14fe5a066f93edd20aada932acfe348bede8aa2149f1a4489512", size = 487532, upload-time = "2025-04-08T10:35:23.143Z" }, { url = "https://files.pythonhosted.org/packages/fc/fd/13d26721c85d7f3df6169d8b495fcac8ab0dc8f0945ebea8845de4681dab/watchfiles-1.0.5-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:a0dbcb1c2d8f2ab6e0a81c6699b236932bd264d4cef1ac475858d16c403de74d", size = 522865, upload-time = "2025-04-08T10:35:24.702Z" }, { url = "https://files.pythonhosted.org/packages/a1/0d/7f9ae243c04e96c5455d111e21b09087d0eeaf9a1369e13a01c7d3d82478/watchfiles-1.0.5-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:a2014a2b18ad3ca53b1f6c23f8cd94a18ce930c1837bd891262c182640eb40a6", size = 499887, upload-time = "2025-04-08T10:35:25.969Z" }, { url = "https://files.pythonhosted.org/packages/8e/0f/a257766998e26aca4b3acf2ae97dff04b57071e991a510857d3799247c67/watchfiles-1.0.5-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:10f6ae86d5cb647bf58f9f655fcf577f713915a5d69057a0371bc257e2553234", size = 454498, upload-time = "2025-04-08T10:35:27.353Z" }, { url = "https://files.pythonhosted.org/packages/81/79/8bf142575a03e0af9c3d5f8bcae911ee6683ae93a625d349d4ecf4c8f7df/watchfiles-1.0.5-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:1a7bac2bde1d661fb31f4d4e8e539e178774b76db3c2c17c4bb3e960a5de07a2", size = 630663, upload-time = "2025-04-08T10:35:28.685Z" }, { url = "https://files.pythonhosted.org/packages/f1/80/abe2e79f610e45c63a70d271caea90c49bbf93eb00fa947fa9b803a1d51f/watchfiles-1.0.5-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:4ab626da2fc1ac277bbf752446470b367f84b50295264d2d313e28dc4405d663", size = 625410, upload-time = "2025-04-08T10:35:30.42Z" }, { url = "https://files.pythonhosted.org/packages/91/6f/bc7fbecb84a41a9069c2c6eb6319f7f7df113adf113e358c57fc1aff7ff5/watchfiles-1.0.5-cp312-cp312-win32.whl", hash = "sha256:9f4571a783914feda92018ef3901dab8caf5b029325b5fe4558c074582815249", size = 277965, upload-time = "2025-04-08T10:35:32.023Z" }, { url = "https://files.pythonhosted.org/packages/99/a5/bf1c297ea6649ec59e935ab311f63d8af5faa8f0b86993e3282b984263e3/watchfiles-1.0.5-cp312-cp312-win_amd64.whl", hash = "sha256:360a398c3a19672cf93527f7e8d8b60d8275119c5d900f2e184d32483117a705", size = 291693, upload-time = "2025-04-08T10:35:33.225Z" }, { url = "https://files.pythonhosted.org/packages/7f/7b/fd01087cc21db5c47e5beae507b87965db341cce8a86f9eb12bf5219d4e0/watchfiles-1.0.5-cp312-cp312-win_arm64.whl", hash = "sha256:1a2902ede862969077b97523987c38db28abbe09fb19866e711485d9fbf0d417", size = 283287, upload-time = "2025-04-08T10:35:34.568Z" }, { url = "https://files.pythonhosted.org/packages/c7/62/435766874b704f39b2fecd8395a29042db2b5ec4005bd34523415e9bd2e0/watchfiles-1.0.5-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:0b289572c33a0deae62daa57e44a25b99b783e5f7aed81b314232b3d3c81a11d", size = 401531, upload-time = "2025-04-08T10:35:35.792Z" }, { url = "https://files.pythonhosted.org/packages/6e/a6/e52a02c05411b9cb02823e6797ef9bbba0bfaf1bb627da1634d44d8af833/watchfiles-1.0.5-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:a056c2f692d65bf1e99c41045e3bdcaea3cb9e6b5a53dcaf60a5f3bd95fc9763", size = 392417, upload-time = "2025-04-08T10:35:37.048Z" }, { url = "https://files.pythonhosted.org/packages/3f/53/c4af6819770455932144e0109d4854437769672d7ad897e76e8e1673435d/watchfiles-1.0.5-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b9dca99744991fc9850d18015c4f0438865414e50069670f5f7eee08340d8b40", size = 453423, upload-time = "2025-04-08T10:35:38.357Z" }, { url = "https://files.pythonhosted.org/packages/cb/d1/8e88df58bbbf819b8bc5cfbacd3c79e01b40261cad0fc84d1e1ebd778a07/watchfiles-1.0.5-cp313-cp313-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:894342d61d355446d02cd3988a7326af344143eb33a2fd5d38482a92072d9563", size = 458185, upload-time = "2025-04-08T10:35:39.708Z" }, { url = "https://files.pythonhosted.org/packages/ff/70/fffaa11962dd5429e47e478a18736d4e42bec42404f5ee3b92ef1b87ad60/watchfiles-1.0.5-cp313-cp313-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:ab44e1580924d1ffd7b3938e02716d5ad190441965138b4aa1d1f31ea0877f04", size = 486696, upload-time = "2025-04-08T10:35:41.469Z" }, { url = "https://files.pythonhosted.org/packages/39/db/723c0328e8b3692d53eb273797d9a08be6ffb1d16f1c0ba2bdbdc2a3852c/watchfiles-1.0.5-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:d6f9367b132078b2ceb8d066ff6c93a970a18c3029cea37bfd7b2d3dd2e5db8f", size = 522327, upload-time = "2025-04-08T10:35:43.289Z" }, { url = "https://files.pythonhosted.org/packages/cd/05/9fccc43c50c39a76b68343484b9da7b12d42d0859c37c61aec018c967a32/watchfiles-1.0.5-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:f2e55a9b162e06e3f862fb61e399fe9f05d908d019d87bf5b496a04ef18a970a", size = 499741, upload-time = "2025-04-08T10:35:44.574Z" }, { url = "https://files.pythonhosted.org/packages/23/14/499e90c37fa518976782b10a18b18db9f55ea73ca14641615056f8194bb3/watchfiles-1.0.5-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0125f91f70e0732a9f8ee01e49515c35d38ba48db507a50c5bdcad9503af5827", size = 453995, upload-time = "2025-04-08T10:35:46.336Z" }, { url = "https://files.pythonhosted.org/packages/61/d9/f75d6840059320df5adecd2c687fbc18960a7f97b55c300d20f207d48aef/watchfiles-1.0.5-cp313-cp313-musllinux_1_1_aarch64.whl", hash = "sha256:13bb21f8ba3248386337c9fa51c528868e6c34a707f729ab041c846d52a0c69a", size = 629693, upload-time = "2025-04-08T10:35:48.161Z" }, { url = "https://files.pythonhosted.org/packages/fc/17/180ca383f5061b61406477218c55d66ec118e6c0c51f02d8142895fcf0a9/watchfiles-1.0.5-cp313-cp313-musllinux_1_1_x86_64.whl", hash = "sha256:839ebd0df4a18c5b3c1b890145b5a3f5f64063c2a0d02b13c76d78fe5de34936", size = 624677, upload-time = "2025-04-08T10:35:49.65Z" }, { url = "https://files.pythonhosted.org/packages/bf/15/714d6ef307f803f236d69ee9d421763707899d6298d9f3183e55e366d9af/watchfiles-1.0.5-cp313-cp313-win32.whl", hash = "sha256:4a8ec1e4e16e2d5bafc9ba82f7aaecfeec990ca7cd27e84fb6f191804ed2fcfc", size = 277804, upload-time = "2025-04-08T10:35:51.093Z" }, { url = "https://files.pythonhosted.org/packages/a8/b4/c57b99518fadf431f3ef47a610839e46e5f8abf9814f969859d1c65c02c7/watchfiles-1.0.5-cp313-cp313-win_amd64.whl", hash = "sha256:f436601594f15bf406518af922a89dcaab416568edb6f65c4e5bbbad1ea45c11", size = 291087, upload-time = "2025-04-08T10:35:52.458Z" }, ] [[package]] name = "websockets" version = "15.0.1" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/21/e6/26d09fab466b7ca9c7737474c52be4f76a40301b08362eb2dbc19dcc16c1/websockets-15.0.1.tar.gz", hash = "sha256:82544de02076bafba038ce055ee6412d68da13ab47f0c60cab827346de828dee", size = 177016, upload-time = "2025-03-05T20:03:41.606Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/9f/32/18fcd5919c293a398db67443acd33fde142f283853076049824fc58e6f75/websockets-15.0.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:823c248b690b2fd9303ba00c4f66cd5e2d8c3ba4aa968b2779be9532a4dad431", size = 175423, upload-time = "2025-03-05T20:01:56.276Z" }, { url = "https://files.pythonhosted.org/packages/76/70/ba1ad96b07869275ef42e2ce21f07a5b0148936688c2baf7e4a1f60d5058/websockets-15.0.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:678999709e68425ae2593acf2e3ebcbcf2e69885a5ee78f9eb80e6e371f1bf57", size = 173082, upload-time = "2025-03-05T20:01:57.563Z" }, { url = "https://files.pythonhosted.org/packages/86/f2/10b55821dd40eb696ce4704a87d57774696f9451108cff0d2824c97e0f97/websockets-15.0.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:d50fd1ee42388dcfb2b3676132c78116490976f1300da28eb629272d5d93e905", size = 173330, upload-time = "2025-03-05T20:01:59.063Z" }, { url = "https://files.pythonhosted.org/packages/a5/90/1c37ae8b8a113d3daf1065222b6af61cc44102da95388ac0018fcb7d93d9/websockets-15.0.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d99e5546bf73dbad5bf3547174cd6cb8ba7273062a23808ffea025ecb1cf8562", size = 182878, upload-time = "2025-03-05T20:02:00.305Z" }, { url = "https://files.pythonhosted.org/packages/8e/8d/96e8e288b2a41dffafb78e8904ea7367ee4f891dafc2ab8d87e2124cb3d3/websockets-15.0.1-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:66dd88c918e3287efc22409d426c8f729688d89a0c587c88971a0faa2c2f3792", size = 181883, upload-time = "2025-03-05T20:02:03.148Z" }, { url = "https://files.pythonhosted.org/packages/93/1f/5d6dbf551766308f6f50f8baf8e9860be6182911e8106da7a7f73785f4c4/websockets-15.0.1-cp311-cp311-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8dd8327c795b3e3f219760fa603dcae1dcc148172290a8ab15158cf85a953413", size = 182252, upload-time = "2025-03-05T20:02:05.29Z" }, { url = "https://files.pythonhosted.org/packages/d4/78/2d4fed9123e6620cbf1706c0de8a1632e1a28e7774d94346d7de1bba2ca3/websockets-15.0.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:8fdc51055e6ff4adeb88d58a11042ec9a5eae317a0a53d12c062c8a8865909e8", size = 182521, upload-time = "2025-03-05T20:02:07.458Z" }, { url = "https://files.pythonhosted.org/packages/e7/3b/66d4c1b444dd1a9823c4a81f50231b921bab54eee2f69e70319b4e21f1ca/websockets-15.0.1-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:693f0192126df6c2327cce3baa7c06f2a117575e32ab2308f7f8216c29d9e2e3", size = 181958, upload-time = "2025-03-05T20:02:09.842Z" }, { url = "https://files.pythonhosted.org/packages/08/ff/e9eed2ee5fed6f76fdd6032ca5cd38c57ca9661430bb3d5fb2872dc8703c/websockets-15.0.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:54479983bd5fb469c38f2f5c7e3a24f9a4e70594cd68cd1fa6b9340dadaff7cf", size = 181918, upload-time = "2025-03-05T20:02:11.968Z" }, { url = "https://files.pythonhosted.org/packages/d8/75/994634a49b7e12532be6a42103597b71098fd25900f7437d6055ed39930a/websockets-15.0.1-cp311-cp311-win32.whl", hash = "sha256:16b6c1b3e57799b9d38427dda63edcbe4926352c47cf88588c0be4ace18dac85", size = 176388, upload-time = "2025-03-05T20:02:13.32Z" }, { url = "https://files.pythonhosted.org/packages/98/93/e36c73f78400a65f5e236cd376713c34182e6663f6889cd45a4a04d8f203/websockets-15.0.1-cp311-cp311-win_amd64.whl", hash = "sha256:27ccee0071a0e75d22cb35849b1db43f2ecd3e161041ac1ee9d2352ddf72f065", size = 176828, upload-time = "2025-03-05T20:02:14.585Z" }, { url = "https://files.pythonhosted.org/packages/51/6b/4545a0d843594f5d0771e86463606a3988b5a09ca5123136f8a76580dd63/websockets-15.0.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:3e90baa811a5d73f3ca0bcbf32064d663ed81318ab225ee4f427ad4e26e5aff3", size = 175437, upload-time = "2025-03-05T20:02:16.706Z" }, { url = "https://files.pythonhosted.org/packages/f4/71/809a0f5f6a06522af902e0f2ea2757f71ead94610010cf570ab5c98e99ed/websockets-15.0.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:592f1a9fe869c778694f0aa806ba0374e97648ab57936f092fd9d87f8bc03665", size = 173096, upload-time = "2025-03-05T20:02:18.832Z" }, { url = "https://files.pythonhosted.org/packages/3d/69/1a681dd6f02180916f116894181eab8b2e25b31e484c5d0eae637ec01f7c/websockets-15.0.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:0701bc3cfcb9164d04a14b149fd74be7347a530ad3bbf15ab2c678a2cd3dd9a2", size = 173332, upload-time = "2025-03-05T20:02:20.187Z" }, { url = "https://files.pythonhosted.org/packages/a6/02/0073b3952f5bce97eafbb35757f8d0d54812b6174ed8dd952aa08429bcc3/websockets-15.0.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e8b56bdcdb4505c8078cb6c7157d9811a85790f2f2b3632c7d1462ab5783d215", size = 183152, upload-time = "2025-03-05T20:02:22.286Z" }, { url = "https://files.pythonhosted.org/packages/74/45/c205c8480eafd114b428284840da0b1be9ffd0e4f87338dc95dc6ff961a1/websockets-15.0.1-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:0af68c55afbd5f07986df82831c7bff04846928ea8d1fd7f30052638788bc9b5", size = 182096, upload-time = "2025-03-05T20:02:24.368Z" }, { url = "https://files.pythonhosted.org/packages/14/8f/aa61f528fba38578ec553c145857a181384c72b98156f858ca5c8e82d9d3/websockets-15.0.1-cp312-cp312-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:64dee438fed052b52e4f98f76c5790513235efaa1ef7f3f2192c392cd7c91b65", size = 182523, upload-time = "2025-03-05T20:02:25.669Z" }, { url = "https://files.pythonhosted.org/packages/ec/6d/0267396610add5bc0d0d3e77f546d4cd287200804fe02323797de77dbce9/websockets-15.0.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:d5f6b181bb38171a8ad1d6aa58a67a6aa9d4b38d0f8c5f496b9e42561dfc62fe", size = 182790, upload-time = "2025-03-05T20:02:26.99Z" }, { url = "https://files.pythonhosted.org/packages/02/05/c68c5adbf679cf610ae2f74a9b871ae84564462955d991178f95a1ddb7dd/websockets-15.0.1-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:5d54b09eba2bada6011aea5375542a157637b91029687eb4fdb2dab11059c1b4", size = 182165, upload-time = "2025-03-05T20:02:30.291Z" }, { url = "https://files.pythonhosted.org/packages/29/93/bb672df7b2f5faac89761cb5fa34f5cec45a4026c383a4b5761c6cea5c16/websockets-15.0.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:3be571a8b5afed347da347bfcf27ba12b069d9d7f42cb8c7028b5e98bbb12597", size = 182160, upload-time = "2025-03-05T20:02:31.634Z" }, { url = "https://files.pythonhosted.org/packages/ff/83/de1f7709376dc3ca9b7eeb4b9a07b4526b14876b6d372a4dc62312bebee0/websockets-15.0.1-cp312-cp312-win32.whl", hash = "sha256:c338ffa0520bdb12fbc527265235639fb76e7bc7faafbb93f6ba80d9c06578a9", size = 176395, upload-time = "2025-03-05T20:02:33.017Z" }, { url = "https://files.pythonhosted.org/packages/7d/71/abf2ebc3bbfa40f391ce1428c7168fb20582d0ff57019b69ea20fa698043/websockets-15.0.1-cp312-cp312-win_amd64.whl", hash = "sha256:fcd5cf9e305d7b8338754470cf69cf81f420459dbae8a3b40cee57417f4614a7", size = 176841, upload-time = "2025-03-05T20:02:34.498Z" }, { url = "https://files.pythonhosted.org/packages/cb/9f/51f0cf64471a9d2b4d0fc6c534f323b664e7095640c34562f5182e5a7195/websockets-15.0.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:ee443ef070bb3b6ed74514f5efaa37a252af57c90eb33b956d35c8e9c10a1931", size = 175440, upload-time = "2025-03-05T20:02:36.695Z" }, { url = "https://files.pythonhosted.org/packages/8a/05/aa116ec9943c718905997412c5989f7ed671bc0188ee2ba89520e8765d7b/websockets-15.0.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:5a939de6b7b4e18ca683218320fc67ea886038265fd1ed30173f5ce3f8e85675", size = 173098, upload-time = "2025-03-05T20:02:37.985Z" }, { url = "https://files.pythonhosted.org/packages/ff/0b/33cef55ff24f2d92924923c99926dcce78e7bd922d649467f0eda8368923/websockets-15.0.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:746ee8dba912cd6fc889a8147168991d50ed70447bf18bcda7039f7d2e3d9151", size = 173329, upload-time = "2025-03-05T20:02:39.298Z" }, { url = "https://files.pythonhosted.org/packages/31/1d/063b25dcc01faa8fada1469bdf769de3768b7044eac9d41f734fd7b6ad6d/websockets-15.0.1-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:595b6c3969023ecf9041b2936ac3827e4623bfa3ccf007575f04c5a6aa318c22", size = 183111, upload-time = "2025-03-05T20:02:40.595Z" }, { url = "https://files.pythonhosted.org/packages/93/53/9a87ee494a51bf63e4ec9241c1ccc4f7c2f45fff85d5bde2ff74fcb68b9e/websockets-15.0.1-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:3c714d2fc58b5ca3e285461a4cc0c9a66bd0e24c5da9911e30158286c9b5be7f", size = 182054, upload-time = "2025-03-05T20:02:41.926Z" }, { url = "https://files.pythonhosted.org/packages/ff/b2/83a6ddf56cdcbad4e3d841fcc55d6ba7d19aeb89c50f24dd7e859ec0805f/websockets-15.0.1-cp313-cp313-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0f3c1e2ab208db911594ae5b4f79addeb3501604a165019dd221c0bdcabe4db8", size = 182496, upload-time = "2025-03-05T20:02:43.304Z" }, { url = "https://files.pythonhosted.org/packages/98/41/e7038944ed0abf34c45aa4635ba28136f06052e08fc2168520bb8b25149f/websockets-15.0.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:229cf1d3ca6c1804400b0a9790dc66528e08a6a1feec0d5040e8b9eb14422375", size = 182829, upload-time = "2025-03-05T20:02:48.812Z" }, { url = "https://files.pythonhosted.org/packages/e0/17/de15b6158680c7623c6ef0db361da965ab25d813ae54fcfeae2e5b9ef910/websockets-15.0.1-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:756c56e867a90fb00177d530dca4b097dd753cde348448a1012ed6c5131f8b7d", size = 182217, upload-time = "2025-03-05T20:02:50.14Z" }, { url = "https://files.pythonhosted.org/packages/33/2b/1f168cb6041853eef0362fb9554c3824367c5560cbdaad89ac40f8c2edfc/websockets-15.0.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:558d023b3df0bffe50a04e710bc87742de35060580a293c2a984299ed83bc4e4", size = 182195, upload-time = "2025-03-05T20:02:51.561Z" }, { url = "https://files.pythonhosted.org/packages/86/eb/20b6cdf273913d0ad05a6a14aed4b9a85591c18a987a3d47f20fa13dcc47/websockets-15.0.1-cp313-cp313-win32.whl", hash = "sha256:ba9e56e8ceeeedb2e080147ba85ffcd5cd0711b89576b83784d8605a7df455fa", size = 176393, upload-time = "2025-03-05T20:02:53.814Z" }, { url = "https://files.pythonhosted.org/packages/1b/6c/c65773d6cab416a64d191d6ee8a8b1c68a09970ea6909d16965d26bfed1e/websockets-15.0.1-cp313-cp313-win_amd64.whl", hash = "sha256:e09473f095a819042ecb2ab9465aee615bd9c2028e4ef7d933600a8401c79561", size = 176837, upload-time = "2025-03-05T20:02:55.237Z" }, { url = "https://files.pythonhosted.org/packages/fa/a8/5b41e0da817d64113292ab1f8247140aac61cbf6cfd085d6a0fa77f4984f/websockets-15.0.1-py3-none-any.whl", hash = "sha256:f7a866fbc1e97b5c617ee4116daaa09b722101d4a3c170c787450ba409f9736f", size = 169743, upload-time = "2025-03-05T20:03:39.41Z" }, ]