Merge main into stable (#3800)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Rowlando13 · committed by GitHub · parents 8ee83dd, 68e7ea7 · Browse files · 39 files·+1366 added−424 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
39 files+1366 added−424 removed
- tests:+808 added−162 removed
- other:+558 added−262 removed
Provenance
- Commit
420c8fb- Tree
2955d48- Author
Rowlando13 <67291205+Rowlando13@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent 1
8ee83dd- Parent 2
68e7ea7
39 files changed+1366 added−424 removed
modified:.github/workflows/lock.yaml+1 added-1 removed
17 unmodified lines1819202122222324252617 unmodified lines issues: write pull-requests: write discussions: write steps: - uses: dessant/lock-threads@7266a7ce5c1df01b1c6db85bf8cd86c737dadbe7 # v6.0.0 - uses: dessant/lock-threads@89ae32b08ed1a541efecbab17912962a5e38981c # v6.0.2 with: issue-inactive-days: 14 pr-inactive-days: 14 discussion-inactive-days: 14modified:.github/workflows/nightly.yaml+30 added-5 removed
11234521 unmodified lines2728293031313233343535363738393839404142434445464748495051525354555657585960616263646566676869name: Nightly race testsname: Nightly testson: schedule: - cron: '0 6 * * *' workflow_dispatch:21 unmodified lines - {name: Stress 3.14, python: '3.14', tox: stress-py3.14} - {name: Stress 3.14t, python: '3.14t', tox: stress-py3.14t} - {name: Stress Mac 3.14t, python: '3.14t', tox: stress-py3.14t, os: macos-latest} steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false ref: ${{ matrix.branch }} - uses: astral-sh/setup-uv@cec208311dfd045dd5311c1add060b2062131d57 # v8.0.0 - uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0 with: enable-cache: true prune-cache: false - uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 with: python-version: ${{ matrix.config.python }} - run: uv run --locked --no-default-groups --group dev tox run env: TOX_ENV: ${{ matrix.config.tox }} flask-tests: name: Flask (${{ matrix.branch }}) runs-on: ubuntu-latest strategy: fail-fast: false matrix: branch: [main, stable] steps: # Check out Flask, not Click: the Click branch under test is installed # from git below, so Flask's own suite runs against it. - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false repository: pallets/flask - uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0 with: enable-cache: true - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 with: python-version: '3.14' - run: uv sync --all-extras # --with overlays the Click branch on top of the version Flask's lock # pins, so a downstream regression shows up as a Flask test failure. - run: uv run --with "git+https://github.com/pallets/click.git@${CLICK_REF}" -- pytest env: CLICK_REF: ${{ matrix.branch }}modified:.github/workflows/pre-commit.yaml+4 added-6 removed
9 unmodified lines1011121314141516171718192021222021222523242526279 unmodified linesjobs: main: runs-on: ubuntu-latest steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - uses: astral-sh/setup-uv@cec208311dfd045dd5311c1add060b2062131d57 # v8.0.0 - uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0 with: enable-cache: true prune-cache: false - uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 id: setup-python - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 with: python-version-file: pyproject.toml - uses: actions/cache@668228422ae6a00e4ad889ee87cd7109ec5666a7 # v5.0.4 - uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: ~/.cache/pre-commit key: pre-commit|${{ hashFiles('pyproject.toml', '.pre-commit-config.yaml') }} - run: uv run --locked --no-default-groups --group pre-commit pre-commit run --show-diff-on-failure --color=always --all-filesmodified:.github/workflows/publish.yaml+5 added-8 removed
10 unmodified lines1112131415151617181819202122212223242527262728293024 unmodified lines555657586061625910 unmodified lines runs-on: ubuntu-latest outputs: artifact-id: ${{ steps.upload-artifact.outputs.artifact-id }} steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - uses: astral-sh/setup-uv@cec208311dfd045dd5311c1add060b2062131d57 # v8.0.0 - uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0 with: enable-cache: false prune-cache: false - uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.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@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0 - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 id: upload-artifact with: name: dist path: dist/24 unmodified lines - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 with: artifact-ids: ${{ needs.build.outputs.artifact-id }} path: dist/ - uses: pypa/gh-action-pypi-publish@ed0c53931b1dc9bd32cbe73a98c7f6766f8a527e # v1.13.0 with: packages-dir: "dist/" - uses: pypa/gh-action-pypi-publish@ba38be9e461d3875417946c167d0b5f3d385a247 # v1.14.1modified:.github/workflows/tests.yaml+7 added-9 removed
25 unmodified lines26 - {python: '3.11'}27 - {python: '3.10'}28 - {name: PyPy, python: 'pypy-3.11', tox: pypy3.11}29 steps:30- - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.230+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.131 with:32 persist-credentials: false33- - uses: astral-sh/setup-uv@cec208311dfd045dd5311c1add060b2062131d57 # v8.0.033+ - uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.034 with:35 enable-cache: true36- prune-cache: false37- - uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.036+ - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.037 with:38 python-version: ${{ matrix.python }}39 - run: uv run --locked --no-default-groups --group dev tox run40 env:41 TOX_ENV: ${{ matrix.tox || format('py{0}', matrix.python) }}42 typing:43 runs-on: ubuntu-latest44 steps:46- - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.245+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.146 with:47 persist-credentials: false49- - uses: astral-sh/setup-uv@cec208311dfd045dd5311c1add060b2062131d57 # v8.0.048+ - uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.049 with:50 enable-cache: true52- prune-cache: false53- - uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.051+ - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.052 with:53 python-version-file: pyproject.toml54 - name: cache mypy57- uses: actions/cache@668228422ae6a00e4ad889ee87cd7109ec5666a7 # v5.0.455+ uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.056 with:57 path: ./.mypy_cache58 key: mypy|${{ hashFiles('pyproject.toml') }}59 - run: uv run --locked --no-default-groups --group dev tox run -e typingmodified:.github/workflows/zizmor.yaml+2 added-2 removed
11 unmodified lines1213141516161718191920212211 unmodified linesjobs: zizmor: runs-on: ubuntu-latest steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - uses: zizmorcore/zizmor-action@71321a20a9ded102f6e9ce5718a2fcec2c4f70d8 # v0.5.2 - uses: zizmorcore/zizmor-action@6599ee8b7a49aef6a770f63d261d214911a7ce02 # v0.6.0 with: advanced-security: false annotations: truemodified:docs/arguments.md+1 added-1 removed
8 unmodified lines9 10 * Are positional in nature.11 * Similar to a limited version of {ref}`options <options>` that12 can take an arbitrary number of inputs13-* Can take an optional `help` string shown in the ``Positional arguments``13+* Can take an optional `help` string shown in the `Positional arguments`14 section of the help page, or be {ref}`documented in the command docstring15 <documenting-arguments>`.16 17 Useful and often used kwargs are:172 unmodified linesmodified:docs/contributing.md+3 added-2 removed
23 unmodified lines24 ```shell-session25 $ tox r -e random26 ```27 28-- A CI workflow (`.github/workflows/test-flask.yaml`)29- runs Flask's test suite to catch downstream28+- The nightly workflow29+ (`.github/workflows/nightly.yaml`) runs Flask's test30+ suite against `main` and `stable` to catch downstream31 regressions.32 33 ## Code Style34 11 unmodified linesmodified:docs/documentation.md+2 added-2 removed
13 unmodified lines14 ```{eval-rst}15 .. click:example::16 17 @click.command()18- @click.argument('name', help='The name to print')18+ @click.argument('name', help='The name to print.')19 @click.option('--count', default=1, help='number of greetings')20 def hello(name: str, count: int):21 """This script prints hello and a name one or more times."""22 for x in range(count):90 unmodified lines113 114 ## Documenting Arguments115 116 {class}`click.argument` accepts an optional `help` parameter that is shown in117-the ``Positional arguments`` section of the help page. You can still document117+the `Positional arguments` section of the help page. You can still document118 arguments in the command docstring, especially when you want to describe them119 in the main help text by name.120 121 A brief example:222 unmodified linesmodified:docs/faqs.md+45 added
35 unmodified lines36 #### Answer37 38 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.39 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.40+41+### `UnicodeEncodeError` on Windows42+43+A Click CLI that uses Unicode characters in its help text or `echo` output can raise `UnicodeEncodeError`:44+45+```pytb46+UnicodeEncodeError: 'charmap' codec can't encode character '\u2023' in position 62: character maps to <undefined>47+```48+49+This is not a bug in Click. When `<stdout>` is a console, Click relies on the Windows console API, which supports full Unicode rendering. But when `<stdout>` is redirected, it cannot use that API, so Python falls back to encoding the stream with the system's code page (often `cp1252`) and `errors="strict"`. That codec cannot represent every Unicode character, so the write fails.50+51+#### Answer52+53+Run Python in [UTF-8 mode](https://docs.python.org/3/library/os.html#utf8-mode) so that redirected streams use UTF-8 instead of the code page.54+55+You can enforce that by:56+- Setting the `PYTHONUTF8=1` environment variable, or57+- Passing `-X utf8` to the `python` executable, or58+- Setting `PYTHONIOENCODING=utf8`, which configures only the standard streams, or59+- From your code, call `sys.stdout.reconfigure(encoding="utf-8")` and `sys.stderr.reconfigure(encoding="utf-8")` before producing output.60+61+This is not a bug for Click to fix, but a system configuration. It will naturally go away with UTF-8 mode becoming the default in Python 3.15 (see [PEP 686](https://peps.python.org/pep-0686/)).62+63+#### For library authors64+65+Click intentionally does not fix this in code: it has no way to know what the caller expects. Reconfiguring the stream itself would mix encodings within one process: `echo` could write UTF-8 to a redirected file while a bare `print()` still writes the code page. A loud `UnicodeEncodeError` is easier to diagnose than silently interleaved encodings.66+67+But if your own CLI knows the environment it runs under, it can choose to degrade its output:68+69+```python70+import sys71+72+encoding = getattr(sys.stdout, "encoding", "") or ""73+ascii_only = not encoding.lower().startswith("utf")74+```75+76+Note that the check we recommend here is against `sys.stdout.encoding`, not `sys.flags.utf8_mode`: only the former reports UTF-8 for all three options listed below.77+78+| Invocation | `sys.flags.utf8_mode` | `sys.stdout.encoding` |79+| :-------------------------------------- | :-------------------: | :-------------------: |80+| `PYTHONIOENCODING=utf8` | `0` | `utf-8` |81+| `python -X utf8` | `1` | `utf-8` |82+| `sys.stdout.reconfigure(encoding=…)` | `0` | `utf-8` |83+84+Do not rely on `sys.getfilesystemencoding()` on Windows either: [PEP 529](https://peps.python.org/pep-0529/) makes it `utf-8` regardless of the actual stream encoding.modified:docs/option-decorators.md+2 added
82 unmodified lines83 84 ## Version Option85 86 {func}`version_option` adds a `--version` option which immediately prints the version number and exits the program.87+88+The message and values it can show are intentionally limited, and its feature set is frozen. If you need values it does not expose, such as the Python version or git metadata, use {func}`custom_version_option` and produce the output yourself in a callback.modified:docs/shell-completion.md+2 added-2 removed
3 unmodified lines4 5 ```{currentmodule} click.shell_completion6 ```7 8-Click provides tab completion support for Bash (version 4.4 and up), Zsh, and Fish. It is possible to add support for9-other shells too, and suggestions can be customized at multiple levels.8+Click provides tab completion support for Bash (version 4.4 and up), Zsh, Fish, and PowerShell. It is possible to add9+support for other shells too, and suggestions can be customized at multiple levels.10 11 Shell completion suggests command names, option names, and values for choice, file, and path parameter types. Options12 are only listed if at least a dash has been entered. Hidden commands and options are not shown.13 262 unmodified linesmodified:docs/testing.md+45 added-27 removed
5 unmodified lines6 7 Click provides the {ref}`click.testing <testing>` module to help you invoke8 command line applications and check their behavior.9 10-These tools should only be used for testing since they change11-the entire interpreter state for simplicity. They are not thread-safe!10+```{warning}11+These tools should only be used for testing since they change the entire12+interpreter state for simplicity. They are not thread-safe: see13+[Running tests in parallel](#running-tests-in-parallel) for the supported14+way to run CLI tests concurrently.15+```16 17 The examples use [pytest](https://docs.pytest.org/en/stable/) style tests.18 19 ```{contents}102 unmodified lines122 ```123 124 ## File System Isolation125 122-The {meth}`CliRunner.isolated_filesystem` context manager sets the current123-working directory to a new, empty folder.126+To test a command that reads or writes files, give each test its own127+directory and pass absolute paths to the command. Pytest's128+[`tmp_path`](https://docs.pytest.org/en/stable/how-to/tmp_path.html) fixture129+provides a fresh directory per test; {class}`tempfile.TemporaryDirectory`130+works without pytest.131 132 ```{code-block} python133 :caption: cat.py134 10 unmodified lines145 146 from click.testing import CliRunner147 from cat import cat148 142-def test_cat():143- runner = CliRunner()144- with runner.isolated_filesystem():145- with open('hello.txt', 'w') as f:146- f.write('Hello World!')149+def test_cat(tmp_path):150+ hello = tmp_path / 'hello.txt'151+ hello.write_text('Hello World!')152 153+ runner = CliRunner()148- result = runner.invoke(cat, ['hello.txt'])149- assert result.exit_code == 0150- assert result.output == 'Hello World!\n'154+ result = runner.invoke(cat, [str(hello)])155+ assert result.exit_code == 0156+ assert result.output == 'Hello World!\n'157 ```158 153-Pass in a path to control where the temporary directory is created.154-In this case, the directory will not be removed by Click. Its useful155-to integrate with a framework like Pytest that manages temporary files.159+Because the directory is unique to the test and the command receives an160+absolute path, nothing leaks between tests and the working directory is never161+changed.162 157-```{code-block} python158-:caption: test_cat.py163+### Running tests in parallel164 160-from click.testing import CliRunner161-from cat import cat165+Isolating the file system with pytest is thread-safe: each test, or each thread,166+works in its own directory through absolute paths, with no shared state.167 163-def test_cat_with_path_specified():164- runner = CliRunner()165- with runner.isolated_filesystem('~/test_folder'):166- with open('hello.txt', 'w') as f:167- f.write('Hello World!')168+{meth}`CliRunner.invoke` is different. While a command runs it swaps several169+pieces of process-global state into place (like `sys.stdout`, `sys.stderr`,170+`sys.stdin`, etc). Two invocations active at the same time in one interpreter171+overwrite each other's state, so the runner cannot be driven from several172+threads at once.173 169- result = runner.invoke(cat, ['hello.txt'])170- assert result.exit_code == 0171- assert result.output == 'Hello World!\n'174+```{warning}175+Do not parallelize CLI tests with threads. Use process-based isolation176+instead, where each worker has its own interpreter and its own copy of those177+globals. [pytest-xdist](https://pytest-xdist.readthedocs.io/) does this with178+`pytest --numprocesses=auto`.179 ```180 181+Click's own test suite uses exactly this setup: the `tests-random` dependency182+group and the `random` tox environment in183+[`pyproject.toml`](https://github.com/pallets/click/blob/main/pyproject.toml)184+run the suite under `pytest-randomly` and `pytest-xdist` to surface ordering185+bugs and races.186+187+```{deprecated} 8.5.0188+{meth}`CliRunner.isolated_filesystem` is deprecated and will be removed in189+Click 9.0. Use a temporary directory with absolute paths, as shown above.190+```191+192 ## Input Streams193 194 The test wrapper can provide input data for the input stream (stdin). This is195 very useful for testing prompts.88 unmodified linesmodified:docs/upgrade-guides.md+1 added-1 removed
11 unmodified lines12 13 ### Deprecations14 15 For each deprecation, provide a brief explanation, and direct users to new function / class if available.16-- TBD16+- `CliRunner.isolated_filesystem()` is deprecated and will be removed in Click 9.0. The helper predates Python 3 and modern pytest, and it relies on `os.chdir`, which mutates process-global state and is therefore not thread-safe. Replace it with a temporary directory (`tempfile.TemporaryDirectory`, or pytest's `tmp_path` fixture) and pass absolute paths to the command instead of relying on the current working directory. To run commands in parallel, use process-based isolation (such as `pytest-xdist`) rather than threads, since `CliRunner.invoke()` also redirects the process-global standard streams and other interpreter-wide state. See [#3700](https://github.com/pallets/click/issues/3700), [#3501](https://github.com/pallets/click/issues/3501) and the [testing guide](testing.md#running-tests-in-parallel).17 18 ### Removals with prior deprecation19 20 For each removal, provide a brief explanation, and direct users to new function / class if available. If possible, deprecate and remove in 10.0.0, rather than removing outright.14 unmodified linesmodified:docs/utils.md+8 added-5 removed
54 unmodified lines55 The {func}`echo` function supports ANSI colors and styles. It will56 automatically strip ANSI color codes if the stream is not connected to a57 terminal.58 59-:::{admonition} Older Windows Support59+```{admonition} Older Windows Support60 :class: note61 62-Recent Windows 11 supports ANSI styling by default, in both Terminal and cmd.exe.63-If you need to support color output on older versions of Windows, install62+Recent versions of Windows 11 support ANSI styling by default, in both63+Windows Terminal and cmd.exe. If you need to support color output on older64+versions of Windows, install65 [colorama](https://pypi.org/project/colorama/) and call `colorama.init()`.65-:::66+```67 68 For styling a string, the {func}`style` function can be used:69 70 ```python53 unmodified lines124 for idx in range(50000):125 print(idx, file=pager)126 ```127 127-```{hint} Why print instead of echo?128+```{admonition} Why print() instead of echo()?129+:class: hint130+131 The pager object deals with ANSI color and style codes itself: they are kept or132 stripped depending on what the pager supports, exactly as {func}`echo` would do.133 Any code that writes to a file, including plain {func}`print`, can therefore be134 used with it.255 unmodified linesmodified:src/click/_compat.py+2 added-2 removed
504 unmodified lines505 if color is None:506 if stream is None:507 stream = sys.stdin508 elif hasattr(stream, "color"):509- # ._termui_impl.MaybeStripAnsi handles stripping ansi itself,509+ # ._termui_impl._PagerWriter handles stripping ansi itself,510 # so we don't need to strip it here511 return False512 return not isatty(stream) and not _is_jupyter_kernel_output(stream)513 return not color514 515 516-# double check is needed so mypy does not analyze this on Linux516+# Double check is needed so mypy does not analyze this on Linux.517 if sys.platform.startswith("win") and WIN:518 from ._winconsole import _get_windows_console_stream519 520 def _get_argv_encoding() -> str:70 unmodified linesmodified:src/click/_termui_impl.py+172 added-145 removed
6 unmodified lines7 from __future__ import annotations8 9 import collections.abc as cabc10 import contextlib11-import io11 import math12 import os13 import shlex14 import sys11 unmodified lines26 from ._compat import strip_ansi27 from ._compat import term_len28 from ._compat import WIN29 from .exceptions import ClickException31-from .utils import _KeepOpenFile30 from .utils import echo31 32 V = t.TypeVar("V")33 34 37-class _BufferedTextPagerStream(t.Protocol):38- buffer: t.BinaryIO39-40-41-def _has_binary_buffer(42- stream: t.BinaryIO | t.TextIO,43-) -> t.TypeGuard[_BufferedTextPagerStream]:44- # TextIO is wider than TextIOWrapper; text-only streams such as StringIO45- # are valid TextIO values but do not expose a binary buffer to wrap.46- return getattr(stream, "buffer", None) is not None47-48-35 if os.name == "nt":36 BEFORE_BAR = "\r"37 AFTER_BAR = "\n"38 else:100 unmodified lines139 # twice works and does "what you want".140 return next(iter(self))141 142 def render_finish(self) -> None:143+ # Steps stay pending until they add up to update_min_steps, so a length144+ # that is not a multiple of it keeps a sub-threshold remainder that145+ # never reaches pos. Apply it so the bar settles on its true position.146+ if self._completed_intervals:147+ self.make_step(self._completed_intervals)148+ self._completed_intervals = 0149+ self.render_progress()150+151 if self.hidden or not self._is_atty:152 return153 self.file.write(AFTER_BAR)154 self.file.flush()224 unmodified lines379 self.finish()380 self.render_progress()381 382 389-class MaybeStripAnsi(io.TextIOWrapper):390- def __init__(self, stream: t.IO[bytes], *, color: bool, **kwargs: t.Any):391- super().__init__(stream, **kwargs)383+class _PagerWriter:384+ """Wrap a pager's output stream to strip ANSI styling when colors are385+ disabled.386+387+ The wrapped stream is owned by the pager strategy that produced it, so this388+ wrapper never closes it: ``_pipepager`` closes its pipe to signal EOF to the389+ pager process, ``_tempfilepager`` closes and removes its temporary file, and390+ ``_nullpager`` leaves an external stream such as ``sys.stdout`` untouched.391+392+ The ``color`` attribute lets :func:`click.echo` detect that ANSI stripping393+ is handled here, so it doesn't strip a second time (see394+ :func:`._compat.should_strip_ansi`).395+ """396+397+ def __init__(self, stream: t.TextIO, color: bool) -> None:398+ self._stream = stream399 self.color = color400 401 def write(self, text: str) -> int:402 if not self.color:403 text = strip_ansi(text)397- return super().write(text)404 405+ return self._stream.write(text)406 407+ def writelines(self, lines: cabc.Iterable[str]) -> None:408+ for line in lines:409+ self.write(line)410+411+ def flush(self) -> None:412+ self._stream.flush()413+414+ def close(self) -> None:415+ # The pager strategy owns the stream's lifecycle. Flush pending output,416+ # but never close the underlying stream from here.417+ self._stream.flush()418+419+ def __getattr__(self, name: str) -> t.Any:420+ return getattr(self._stream, name)421+422+423+def _resolve_pager_command(cmd_parts: list[str]) -> tuple[Path, list[str]] | None:424+ """Resolve a pager ``argv`` to an absolute command path and its parameters.425+426+ The command is looked up with :func:`shutil.which`, which the427+ :mod:`subprocess` docs recommend on every platform for an unqualified name:428+ https://docs.python.org/3/library/subprocess.html#popen-constructor429+430+ Returns ``None`` when there is no command to run or it is not on the path,431+ leaving the caller to pick a fallback.432+ """433+ if not cmd_parts:434+ return None435+436+ import shutil437+438+ cmd_filepath = shutil.which(cmd_parts[0])439+440+ if not cmd_filepath:441+ return None442+443+ # Normalize to an absolute path without resolving symlinks: multi-call444+ # binaries such as busybox derive their identity from the link they are445+ # invoked through, so resolving less -> busybox makes them misbehave.446+ # See https://github.com/pallets/click/issues/2943 and447+ # https://github.com/pallets/click/pull/2944448+ return Path(cmd_filepath).absolute(), cmd_parts[1:]449+450+451 def _pager_contextmanager(452 color: bool | None = None,402-) -> t.ContextManager[tuple[t.BinaryIO | t.TextIO, str, bool]]:453+) -> t.ContextManager[tuple[t.TextIO, bool | None]]:454 """Decide what method to use for paging through text."""455 stdout = _default_text_stdout()456 457 # There are no standard streams attached to write to. For example,8 unmodified lines466 # stripped from tokens and quoted Windows paths are preserved.467 # Non-POSIX mode retains quotes in tokens, and wrapping tokens468 # with shlex.quote re-introduces quoting issues on Windows.469 pager_cmd_parts = shlex.split(os.environ.get("PAGER", ""))470+471 if pager_cmd_parts:420- if WIN:421- return _tempfilepager(pager_cmd_parts, color)422- return _pipepager(pager_cmd_parts, color)472+ # Piping to `more` on Windows adds spurious \r\n, so it gets the temp473+ # file strategy whatever the user asked for.474+ use_tempfile = WIN475+ else:476+ if os.environ.get("TERM") in ("dumb", "emacs"):477+ return _nullpager(stdout, color)478 424- if os.environ.get("TERM") in ("dumb", "emacs"):479+ use_tempfile = WIN or sys.platform.startswith("os2")480+ pager_cmd_parts = ["more"] if use_tempfile else ["less"]481+482+ resolved = _resolve_pager_command(pager_cmd_parts)483+484+ if resolved is None:485+ # Page through stdout, which _nullpager leaves open for its owner.486 return _nullpager(stdout, color)426- if WIN or sys.platform.startswith("os2"):427- return _tempfilepager(["more"], color)428- return _pipepager(["less"], color)487 488+ cmd_path, cmd_params = resolved489 490+ if use_tempfile:491+ return _tempfilepager(cmd_path, cmd_params, color)492+493+ return _pipepager(cmd_path, cmd_params, color)494+495+496 @contextlib.contextmanager497 def get_pager_file(color: bool | None = None) -> t.Generator[t.TextIO, None, None]:498 """Context manager.499 3 unmodified lines503 504 :param color: controls if the pager supports ANSI colors or not. The505 default is autodetection.506 """442- with _pager_contextmanager(color=color) as (stream, encoding, color):443- # Split streams by capabilities rather than the abstract TextIO /444- # BinaryIO annotations: buffered text streams can be unwrapped to bytes,445- # while other streams are yielded as-is.446- wrapper: MaybeStripAnsi | None = None447- if _has_binary_buffer(stream):448- # Text stream backed by a binary buffer.449- wrapper = MaybeStripAnsi(stream.buffer, color=color, encoding=encoding)450- stream = wrapper507+ with _pager_contextmanager(color=color) as (stream, color):508+ # Every pager strategy yields a text stream, so the only thing left to509+ # do is strip ANSI styling when colors are disabled. A strategy yields510+ # None when it has no opinion on colors, which settles as off here. The511+ # wrapper does not close the stream: each strategy owns its stream's512+ # lifecycle.513+ writer = _PagerWriter(stream, color=bool(color))514 try:452- # Narrow the BinaryIO | TextIO union that _pager_contextmanager453- # yields; the caller writes text to the pager.454- yield t.cast(t.TextIO, stream)515+ yield t.cast(t.TextIO, writer)516 finally:456- try:457- stream.flush()517+ writer.flush()458- finally:459- # Hand the binary buffer back to the pager that produced it460- # rather than letting this TextIOWrapper close it on garbage461- # collection. The pager owns the buffer's lifecycle: subprocess462- # pipes and temp files are closed by their own helpers, while a463- # borrowed stdout must stay open for the caller. detach() runs464- # even if flush() raised, so the buffer is never closed here.465- if wrapper is not None:466- wrapper.detach()518 519 520+def _less_uses_raw_mode(less_env: str, cmd_params: list[str]) -> bool:521+ """Detect a raw-control-characters request in a ``less`` invocation.522+523+ Parses the tokens of the ``LESS`` environment variable and the command524+ line: only short-option clusters (``-R``, ``-rX``, ``-XrY``) and the525+ ``--raw-control-chars`` long option request raw mode. Filenames and526+ long-option values may carry the letter ``r`` without being such a527+ request.528+ """529+ try:530+ env_tokens = shlex.split(less_env)531+ except ValueError:532+ # Unbalanced quotes make ``LESS`` unparsable: fall back to whitespace533+ # splitting rather than failing the pager over it.534+ env_tokens = less_env.split()535+ tokens = env_tokens + cmd_params536+537+ for token in tokens:538+ if token.startswith("--"):539+ if token.casefold() == "--raw-control-chars":540+ return True541+ elif token.startswith("-") and len(token) > 1:542+ if "r" in token[1:].casefold():543+ return True544+545+ return False546+547+548 @contextlib.contextmanager549 def _pipepager(471- cmd_parts: list[str], color: bool | None = None472-) -> t.Iterator[tuple[t.BinaryIO | t.TextIO, str, bool]]:550+ cmd_path: Path, cmd_params: list[str], color: bool | None = None551+) -> t.Iterator[tuple[t.TextIO, bool | None]]:552 """Page through text by feeding it to another program.553 475- Invokes the pager via :class:`subprocess.Popen` with an ``argv`` list476- produced by :func:`shlex.split`. The command is resolved to an absolute477- path with :func:`shutil.which` as recommended by the478- :mod:`subprocess` docs for Windows compatibility.554+ Invokes the pager via :class:`subprocess.Popen` with an ``argv`` list.555 556 Invoking a pager through this might support colors: if piping to557 ``less`` and the user hasn't decided on colors, ``LESS=-R`` is set558 automatically.559 """484- # Split the command into the invoked CLI and its parameters.485- if not cmd_parts:486- # No usable pager: fall back to stdout through _nullpager so it gets the487- # same borrowed-stream handling and the caller's stream is not closed.488- stdout = _default_text_stdout() or StringIO()489- with _nullpager(stdout, color) as rv:490- yield rv491- return492-493- import shutil494-495- cmd = cmd_parts[0]496- cmd_params = cmd_parts[1:]497-498- cmd_filepath = shutil.which(cmd)499- if not cmd_filepath:500- # No usable pager: fall back to stdout through _nullpager so it gets the501- # same borrowed-stream handling and the caller's stream is not closed.502- stdout = _default_text_stdout() or StringIO()503- with _nullpager(stdout, color) as rv:504- yield rv505- return506-507- # Produces a normalized absolute path string.508- # multi-call binaries such as busybox derive their identity from the symlink509- # less -> busybox. resolve() causes them to misbehave. (eg. less becomes busybox)510- cmd_path = Path(cmd_filepath).absolute()511- cmd_name = cmd_path.name512-560 import subprocess561 562 # Make a local copy of the environment to not affect the global one.563 env = dict(os.environ)564 565 # If we're piping to less and the user hasn't decided on colors, we enable519- # them by default we find the -R flag in the command line arguments.566+ # them: either the invocation already requests raw control characters, or567+ # ``LESS=-R`` is injected. Match on the stem so a resolved ``less.exe`` is568+ # recognized like bare ``less``, case-insensitively on Windows since its569+ # filesystems are. POSIX keeps an exact match.570+ cmd_name = cmd_path.stem571+ if WIN:572+ # ``_pager_contextmanager`` currently routes every Windows invocation573+ # to ``_tempfilepager``, so this branch is not reachable on Windows574+ # today: it keeps the detection correct should that routing ever575+ # change.576+ cmd_name = cmd_name.casefold()577+578 if color is None and cmd_name == "less":521- less_flags = f"{os.environ.get('LESS', '')}{' '.join(cmd_params)}"522- if not less_flags:579+ less_env = os.environ.get("LESS", "")580+ if _less_uses_raw_mode(less_env, cmd_params):581+ color = True582+ elif not less_env and not cmd_params:583 env["LESS"] = "-R"584 color = True525- elif "r" in less_flags or "R" in less_flags:526- color = True585 528- if color is None:529- color = False530-586 c = subprocess.Popen(587 [str(cmd_path)] + cmd_params,588 shell=False,589 stdin=subprocess.PIPE,590 env=env,591 errors="replace",592 text=True,593 )539- stdin = t.cast(t.BinaryIO, c.stdin)540- encoding = get_best_encoding(stdin)594+ # With ``text=True``, ``c.stdin`` is already a text stream that encodes595+ # writes for the pager process (honoring ``errors="replace"``).596+ stdin = t.cast(t.TextIO, c.stdin)597 try:542- yield stdin, encoding, color598+ yield stdin, color599 except BrokenPipeError:600 # In case the pager exited unexpectedly, ignore the broken pipe error.601 pass602 except Exception as e:30 unmodified lines633 634 635 @contextlib.contextmanager636 def _tempfilepager(581- cmd_parts: list[str], color: bool | None = None582-) -> t.Iterator[tuple[t.BinaryIO | t.TextIO, str, bool]]:637+ cmd_path: Path, cmd_params: list[str], color: bool | None = None638+) -> t.Iterator[tuple[t.TextIO, bool | None]]:639 """Page through text by invoking a program on a temporary file.640 641 Used as the primary pager strategy on Windows (where piping to642 ``more`` adds spurious ``\\r\\n``), and as a fallback on other587- platforms. The command is resolved to an absolute path with588- :func:`shutil.which`.643+ platforms. The command is invoked with any parameters from ``PAGER``644+ followed by the temporary file name.645 """590- # Split the command into the invoked CLI and its parameters.591- if not cmd_parts:592- # No usable pager: fall back to stdout through _nullpager so it gets the593- # same borrowed-stream handling and the caller's stream is not closed.594- stdout = _default_text_stdout() or StringIO()595- with _nullpager(stdout, color) as rv:596- yield rv597- return598-599- import shutil646 import subprocess601-602- cmd = cmd_parts[0]603-604- cmd_filepath = shutil.which(cmd)605- if not cmd_filepath:606- # No usable pager: fall back to stdout through _nullpager so it gets the607- # same borrowed-stream handling and the caller's stream is not closed.608- stdout = _default_text_stdout() or StringIO()609- with _nullpager(stdout, color) as rv:610- yield rv611- return612-613- # Produces a normalized absolute path string.614- # multi-call binaries such as busybox derive their identity from the symlink615- # less -> busybox. resolve() causes them to misbehave. (eg. less becomes busybox)616- cmd_path = Path(cmd_filepath).absolute()617-647 import tempfile648 649 encoding = get_best_encoding(sys.stdout)621- if color is None:622- color = False650 # On Windows, NamedTemporaryFile cannot be opened by another process651 # while Python still has it open, so we use delete=False and clean up manually652 # rather than using a contextmanager here.626- f = tempfile.NamedTemporaryFile(mode="wb", delete=False)653+ f = tempfile.NamedTemporaryFile(654+ mode="w", encoding=encoding, errors="replace", delete=False655+ )656 try:628- yield t.cast(t.BinaryIO, f), encoding, color657+ yield t.cast(t.TextIO, f), color658 f.flush()659 f.close()631- subprocess.call([str(cmd_path), f.name])660+ subprocess.call([str(cmd_path), *cmd_params, f.name])661 finally:662+ # An error raised while paging skips the close() above, and Windows663+ # refuses to unlink a file the process still holds open. Closing here664+ # keeps that PermissionError from replacing the original exception.665+ # close() is idempotent, so this is a no-op on the success path.666+ f.close()667 os.unlink(f.name)668 669 670 @contextlib.contextmanager671 def _nullpager(672 stream: t.TextIO, color: bool | None = None639-) -> t.Iterator[tuple[t.TextIO, str, bool]]:640- """Simply print unformatted text. This is the ultimate fallback. Don't close the641- output stream in this case, since it's coming from elsewhere rather than our642- internal helpers.673+) -> t.Iterator[tuple[t.TextIO, bool | None]]:674+ """Simply print unformatted text. This is the ultimate fallback.675 644- The stream is wrapped in :class:`~click.utils._KeepOpenFile` so that, as a645- borrowed stream, it is not closed by a ``with`` block. The wrapper that646- :func:`get_pager_file` builds around it is detached rather than closed.676+ The stream comes from elsewhere (typically ``sys.stdout``), so its lifecycle677+ is left untouched: :class:`_PagerWriter` never closes what it wraps, and it678+ is the only thing :func:`get_pager_file` hands to the caller.679 """648- encoding = get_best_encoding(stream)680+ yield stream, color681 650- if color is None:651- color = False682 653- yield _KeepOpenFile(stream), encoding, color # type: ignore[misc]654-655-683 class Editor:684 def __init__(685 self,686 editor: str | None = None,22 unmodified lines709 if which(editor) is not None:710 return editor711 return "vi"712 686- def edit_files(self, filenames: cabc.Iterable[str]) -> None:713+ def edit_files(self, filenames: cabc.Iterable[str | os.PathLike[str]]) -> None:714 """Open files in the user's editor."""715 import shlex716 import subprocess717 255 unmodified linesmodified:src/click/core.py+12 added-5 removed
1173 unmodified lines1174 1175 return rv1176 1177 def get_help_option_names(self, ctx: Context) -> list[str]:1178- """Returns the names for the help option."""1179- all_names = set(ctx.help_option_names)1178+ """Returns the names for the help option.1179+1180+ Drops duplicates and names already reserved by another parameter. Order of1181+ :attr:`Context.help_option_names` is preserved, so the result is stable.1182+1183+ .. versionchanged:: 8.5.01184+ Names keep their declaration order.1185+ """1186+ all_names = dict.fromkeys(ctx.help_option_names)1187 for param in self.params:1181- all_names.difference_update(param.opts)1182- all_names.difference_update(param.secondary_opts)1188+ for name in (*param.opts, *param.secondary_opts):1189+ all_names.pop(name, None)1190 return list(all_names)1191 1192 def get_help_option(self, ctx: Context) -> Option | None:1193 """Returns the help option object.2474 unmodified lines3668 All parameters are passed onwards to the constructor of :class:`Parameter`.3669 3670 :param help: the help string.3671 3665- .. versionchanged:: 8.53672+ .. versionchanged:: 8.5.03673 Added the ``help`` parameter.3674 """3675 3676 param_type_name = "argument"123 unmodified linesmodified:src/click/shell_completion.py+2 added-2 removed
519 unmodified lines520 521 class PowerShellComplete(ShellComplete):522 """Shell completion for PowerShell (Windows PowerShell 5.1+ and pwsh 7+).523 524- .. versionadded:: 8.5524+ .. versionadded:: 8.5.0525 """526 527 name: t.ClassVar[str] = "powershell"528 source_template: t.ClassVar[str] = _SOURCE_POWERSHELL93 unmodified lines622 623 lex = shlex.shlex(string, posix=True)624 lex.whitespace_split = True625 lex.commenters = ""626- out = [] # type: list[str]626+ out: list[str] = []627 628 try:629 out.extend(lex)630 except ValueError:171 unmodified linesmodified:src/click/termui.py+79 added-25 removed
2 unmodified lines3 import collections.abc as cabc4 import inspect5 import io6 import itertools7+import os8 import re9 import sys10 import typing as t11 from contextlib import AbstractContextManager96 unmodified lines108 def _build_prompt(109 text: str,110 suffix: str,111 show_default: bool | str = False,111- default: t.Any | None = None,112+ default: object | None = None,113 show_choices: bool = True,113- type: ParamType[t.Any] | None = None,114+ type: object | None = None,115 ) -> str:116 prompt = text117 if type is not None and show_choices and isinstance(type, Choice):118 prompt += f" ({', '.join(map(str, type.choices))})"118- if isinstance(show_default, str):119- default = f"({show_default})"120- if default is not None and show_default:121- prompt = f"{prompt} [{_format_default(default)}]"122- return f"{prompt}{suffix}"119+ default_preview = ""120+ if show_default:121+ if isinstance(show_default, str):122+ default_preview = f" [({show_default})]"123+ elif default is not None:124+ default_preview = f" [{_format_default(default)}]"125+ return f"{prompt}{default_preview}{suffix}"126 127 125-def _format_default(default: t.Any) -> t.Any:126- if isinstance(default, (io.IOBase, _LazyFile)) and hasattr(default, "name"):127- return default.name128+def _format_default(default: V) -> V | str:129+ if isinstance(default, (io.IOBase, _LazyFile)):130+ name = getattr(default, "name", None)131 132+ if name is not None:133+ return str(name)134+135 return default136 137 138+@t.overload139 def prompt(140 text: str,134- default: t.Any | None = None,141+ default: str | None = None,142 hide_input: bool = False,143 confirmation_prompt: bool | str = False,137- type: ParamType[t.Any] | t.Any | None = None,138- value_proc: t.Callable[[str], t.Any] | None = None,144+ type: None = None,145+ value_proc: None = None,146 prompt_suffix: str = ": ",147 show_default: bool | str = True,148 err: bool = False,149 show_choices: bool = True,143-) -> t.Any:150+) -> str: ...151+152+153+@t.overload154+def prompt(155+ text: str,156+ default: V | str | None = None,157+ hide_input: bool = False,158+ confirmation_prompt: bool | str = False,159+ type: ParamType[V, str] | type[V] | None = None,160+ value_proc: t.Callable[[str], V] | None = None,161+ prompt_suffix: str = ": ",162+ show_default: bool | str = True,163+ err: bool = False,164+ show_choices: bool = True,165+) -> V: ...166+167+168+def prompt(169+ text: str,170+ default: V | str | None = None,171+ hide_input: bool = False,172+ confirmation_prompt: bool | str = False,173+ type: ParamType[V, str] | type[V] | None = None,174+ value_proc: t.Callable[[str], V] | None = None,175+ prompt_suffix: str = ": ",176+ show_default: bool | str = True,177+ err: bool = False,178+ show_choices: bool = True,179+) -> V:180 """Prompts a user for input. This is a convenience function that can181 be used to prompt a user for input later.182 183 If the user aborts the input by sending an interrupt signal, this21 unmodified lines205 For example if type is a Choice of either day or week,206 show_choices is true and text is "Group by" then the207 prompt will be "Group by (day, week): ".208 209+ .. versionchanged:: 8.5.0210+ Generically typed: the return type is narrowed by ``type``,211+ ``value_proc``, or ``default`` instead of being ``Any``. Runtime212+ behavior is unchanged.213+214 .. versionchanged:: 8.3.3215 ``show_default`` can be a string to show a custom value instead216 of the actual default, matching the help text behavior.217 44 unmodified lines262 value = prompt_func(prompt)263 if value:264 break265 elif default is not None:225- value = default266+ # Defaults of any type are accepted and round trip through267+ # value_proc like typed input, so the annotation is only268+ # accurate for typed input.269+ value = t.cast("str", default)270 break271 try:272 result = value_proc(value)273 except UsageError as e:438 unmodified lines712 :param reset: by default a reset-all code is added at the end of the713 string which means that styles do not carry over. This714 can be disabled to compose styles.715 672- .. versionchanged:: 8.5716+ .. versionchanged:: 8.5.0717 All invalid color values raise :exc:`ValueError`. 256-color index674- ``0`` is not ignored718+ ``0`` is no longer ignored.719 720 .. versionchanged:: 8.0721 A non-string ``message`` is converted to a string.722 114 unmodified lines837 editor: str | None = None,838 env: cabc.Mapping[str, str] | None = None,839 require_save: bool = True,840 extension: str = ".txt",797- filename: str | cabc.Iterable[str] | None = None,841+ filename: str842+ | os.PathLike[str]843+ | cabc.Iterable[str | os.PathLike[str]]844+ | None = None,845 ) -> None: ...846 847 848 def edit(1 unmodified line850 editor: str | None = None,851 env: cabc.Mapping[str, str] | None = None,852 require_save: bool = True,853 extension: str = ".txt",807- filename: str | cabc.Iterable[str] | None = None,854+ filename: str855+ | os.PathLike[str]856+ | cabc.Iterable[str | os.PathLike[str]]857+ | None = None,858 ) -> str | bytes | bytearray | None:859 r"""Edits the given text in the defined editor. If an editor is given860 (should be the full path to the executable but the regular operating861 system search path is used for finding the executable) it overrides18 unmodified lines880 to `.txt` but changing this might change syntax881 highlighting.882 :param filename: if provided it will edit this file instead of the883 provided text contents. It will not use a temporary834- file as an indirection in that case. If the editor supports835- editing multiple files at once, a sequence of files may be836- passed as well. Invoke `click.file` once per file instead837- if multiple files cannot be managed at once or editing the838- files serially is desired.884+ file as an indirection in that case. It accepts a path885+ or any iterable of paths. If the editor supports886+ editing multiple files at once, a sequence of files may887+ be passed as well. Invoke `click.file` once per file888+ instead if multiple files cannot be managed at once or889+ editing the files serially is desired.890 891 .. versionchanged:: 8.2.0892 ``filename`` now accepts any ``Iterable[str]`` in addition to a ``str``893 if the ``editor`` supports editing multiple files at once.894 895+ .. versionchanged:: 8.5.0896+ ``filename`` accepts ``os.PathLike`` values in addition to strings.897+898 """899 from ._termui_impl import Editor900 901 ed = Editor(editor=editor, env=env, require_save=require_save, extension=extension)902 903 if filename is None:904 return ed.edit(text)905 852- if isinstance(filename, str):906+ if isinstance(filename, (str, os.PathLike)):907 filename = (filename,)908 909 ed.edit_files(filenames=filename)910 return None104 unmodified linesmodified:src/click/testing.py+26 added
745 unmodified lines746 changes the current working directory to it. This isolates tests747 that affect the contents of the CWD to prevent them from748 interfering with each other.749 750+ .. warning::751+ This helper predates Python 3 and modern pytest, and is not752+ thread-safe: it relies on :func:`os.chdir`, which mutates753+ process-global state, and :meth:`invoke` swaps the754+ process-global standard streams too. Parallelize tests with755+ processes (``pytest-xdist``), not threads. Locking the756+ runner (:pr:`3511`, :pr:`3520`, :pr:`3530`) and a757+ ``set_filesystem()`` API (:issue:`3123`) were declined:758+ neither removes the global-state mutation. See :issue:`3700`759+ and :issue:`3501`.760+761 :param temp_dir: Create the temporary directory under this762 directory. If given, the created directory is not removed763 when exiting.764 765+ .. deprecated:: 8.5.0766+ Will be removed in Click 9.0. Use767+ :class:`tempfile.TemporaryDirectory` or pytest's768+ ``tmp_path`` fixture with absolute paths instead.769+770 .. versionchanged:: 8.0771 Added the ``temp_dir`` parameter.772 """773+ import warnings774+775+ warnings.warn(776+ "'isolated_filesystem' is deprecated and will be removed in Click"777+ " 9.0. Use 'tempfile.TemporaryDirectory' or pytest's 'tmp_path'"778+ " fixture with absolute paths instead.",779+ DeprecationWarning,780+ stacklevel=3,781+ )782+783 cwd = os.getcwd()784 dt = tempfile.mkdtemp(dir=temp_dir)785 os.chdir(dt)786 12 unmodified linesmodified:src/click/types.py+50 added-3 removed
28 unmodified lines29 _ValueT = t.TypeVar("_ValueT")30 _ValueT_contra = t.TypeVar("_ValueT_contra", contravariant=True)31 _ValueT_co = t.TypeVar("_ValueT_co", covariant=True)32 33+# The input type parameter of ParamType defaults to Any. TypeVar defaults34+# (PEP 696) landed in typing on Python 3.13, so type checkers get the35+# default from typing_extensions, which is never imported at runtime. On36+# older Pythons the runtime TypeVar carries no default;37+# ParamType.__class_getitem__ fills in the omitted parameter instead.38+if t.TYPE_CHECKING:39+ _InputT_contra = te.TypeVar("_InputT_contra", contravariant=True, default=t.Any)40+elif sys.version_info >= (3, 13):41+ _InputT_contra = t.TypeVar("_InputT_contra", contravariant=True, default=t.Any)42+else:43+ _InputT_contra = t.TypeVar("_InputT_contra", contravariant=True)44+45 _FloatValueT = t.TypeVar("_FloatValueT", bound=float)46 _FloatValueT_co = t.TypeVar("_FloatValueT_co", bound=float, covariant=True)47 48 1 unmodified line50 param_type: str51 name: str52 53 42-class ParamType(t.Generic[_ValueT_co], abc.ABC):54+class ParamType(t.Generic[_ValueT_co, _InputT_contra], abc.ABC):55 """Represents the type of a parameter. Validates and converts values56 from the command line or Python into the correct type.57 58 To implement a custom type, subclass and implement at least the13 unmodified lines72 Now a generic abstract base class. Parameterize with the73 converted value type (``ParamType[int]`` for an integer-returning74 type) so that :meth:`convert` and downstream consumers carry the75 narrowed return type.76+77+ .. versionchanged:: 8.5.078+ Accepts a second optional type parameter for the input value type79+ that :meth:`convert` accepts (``ParamType[int, str]`` for a type80+ converting strings to integers), defaulting to ``Any``.81 """82 83 is_composite: t.ClassVar[bool] = False84 arity: int = 1 # read-only8 unmodified lines93 #: are split by ``os.path.pathsep`` by default (":" on Unix and ";" on94 #: Windows).95 envvar_list_splitter: t.ClassVar[str | None] = None96 97+ if sys.version_info < (3, 13):98+ # ``_InputT_contra`` carries its ``Any`` default only for type99+ # checkers: ``TypeVar(default=...)`` (PEP 696) is unavailable at100+ # runtime before Python 3.13. Fill in the omitted input type101+ # parameter by hand so ``ParamType[int]`` keeps working.102+ def __class_getitem__(cls, params: t.Any) -> t.Any:103+ if cls is ParamType:104+ if not isinstance(params, tuple):105+ params = (params,)106+ if len(params) == 1:107+ params = (*params, t.Any)108+ # Checkers cannot see Generic.__class_getitem__ through super().109+ return super().__class_getitem__(params) # type: ignore[misc]110+111 def to_info_dict(self) -> ParamTypeInfoDict:112 """Gather information that could be useful for a tool generating113 user-facing documentation.114 13 unmodified lines128 name = param_type129 130 return {"param_type": param_type, "name": name}131 132+ @t.overload133 def __call__(134 self,103- value: t.Any,135+ value: None,136 param: Parameter | None = None,137 ctx: Context | None = None,138+ ) -> None: ...139+140+ @t.overload141+ def __call__(142+ self,143+ value: _InputT_contra,144+ param: Parameter | None = None,145+ ctx: Context | None = None,146+ ) -> _ValueT_co: ...147+148+ def __call__(149+ self,150+ value: _InputT_contra | None,151+ param: Parameter | None = None,152+ ctx: Context | None = None,153 ) -> _ValueT_co | None:154 if value is not None:155 return self.convert(value, param, ctx)156 return None8 unmodified lines165 .. versionadded:: 2.0166 """167 168 def convert(122- self, value: t.Any, param: Parameter | None, ctx: Context | None169+ self, value: _InputT_contra, param: Parameter | None, ctx: Context | None170 ) -> _ValueT_co:171 """Convert the value to the correct type. This is not called if172 the value is ``None`` (the missing value).173 1249 unmodified linesmodified:src/click/utils.py+1 added-1 removed
277 unmodified lines278 :param color: Force showing or hiding colors and other styles. By279 default Click will remove color if the output does not look like280 an interactive terminal.281 282- .. versionchanged:: 8.5282+ .. versionchanged:: 8.5.0283 Colorama is no longer used for color on Windows.284 285 .. versionchanged:: 6.0286 Support Unicode output on the Windows console. Click does not402 unmodified linesmodified:tests/test_utils/test_echo_via_pager.py+3 added-3 removed
195 unmodified lines196 the pager stream before propagating the exception.197 198 The pager file content is intentionally NOT asserted: pipe-drain timing199 between click and the pager subprocess is outside click's control200- (#2899, #3470). Spying on ``MaybeStripAnsi.write`` records what click sent200+ (#2899, #3470). Spying on ``_PagerWriter.write`` records what click sent201 to the pager, which is deterministic regardless of scheduling.202 """203 monkeypatch.setitem(os.environ, "PAGER", "cat")204 monkeypatch.setattr(click._termui_impl, "isatty", lambda x: True)205 206 writes: list[str] = []207- real_write = click._termui_impl.MaybeStripAnsi.write207+ real_write = click._termui_impl._PagerWriter.write208 209 def spy(self, text):210 writes.append(text)211 return real_write(self, text)212 213- monkeypatch.setattr(click._termui_impl.MaybeStripAnsi, "write", spy)213+ monkeypatch.setattr(click._termui_impl._PagerWriter, "write", spy)214 215 pager_out_tmp = tmp_path / "pager_out.txt"216 with (217 pager_out_tmp.open("w") as f,42 unmodified linesmodified:tests/test_utils/test_open_file.py+50 added-55 removed
6 unmodified lines7 import click8 from click._compat import WIN9 10 11-def test_open_file(runner):11+def test_open_file(runner, tmp_path):12 @click.command()13 @click.argument("filename")14 def cli(filename):15 with click.open_file(filename) as f:16 click.echo(f.read())17 18 click.echo("meep")19 20- with runner.isolated_filesystem():21- with open("hello.txt", "w") as f:22- f.write("Cool stuff")20+ hello = tmp_path / "hello.txt"21+ hello.write_text("Cool stuff")22 24- result = runner.invoke(cli, ["hello.txt"])25- assert result.exception is None26- assert result.output == "Cool stuff\nmeep\n"23+ result = runner.invoke(cli, [str(hello)])24+ assert result.exception is None25+ assert result.output == "Cool stuff\nmeep\n"26 28- result = runner.invoke(cli, ["-"], input="foobar")29- assert result.exception is None30- assert result.output == "foobar\nmeep\n"27+ result = runner.invoke(cli, ["-"], input="foobar")28+ assert result.exception is None29+ assert result.output == "foobar\nmeep\n"30 31 32 def test_open_file_pathlib_dash(runner):33 @click.command()21 unmodified lines55 result = runner.invoke(cli, ["-"], input=os.urandom(16))56 assert result.exception is None57 58 60-def test_open_file_respects_ignore(runner):61- with runner.isolated_filesystem():62- with open("test.txt", "w") as f:63- f.write("Hello world!")59+def test_open_file_respects_ignore(tmp_path):60+ path = tmp_path / "test.txt"61+ path.write_text("Hello world!")62 65- with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:66- assert f.errors == "ignore"63+ with click.open_file(str(path), encoding="utf8", errors="ignore") as f:64+ assert f.errors == "ignore"65 66 69-def test_open_file_ignore_invalid_utf8(runner):70- with runner.isolated_filesystem():71- with open("test.txt", "wb") as f:72- f.write(b"\xe2\x28\xa1")67+def test_open_file_ignore_invalid_utf8(tmp_path):68+ path = tmp_path / "test.txt"69+ path.write_bytes(b"\xe2\x28\xa1")70 74- with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:75- f.read()71+ with click.open_file(str(path), encoding="utf8", errors="ignore") as f:72+ f.read()73 74 78-def test_open_file_ignore_no_encoding(runner):79- with runner.isolated_filesystem():80- with open("test.bin", "wb") as f:81- f.write(os.urandom(16))75+def test_open_file_ignore_no_encoding(tmp_path):76+ path = tmp_path / "test.bin"77+ path.write_bytes(os.urandom(16))78 83- with click.open_file("test.bin", errors="ignore") as f:84- f.read()79+ with click.open_file(str(path), errors="ignore") as f:80+ f.read()81 82 83 @pytest.mark.skipif(WIN, reason="os.chmod() is not fully supported on Windows.")84 @pytest.mark.parametrize("permissions", [0o400, 0o444, 0o600, 0o644])89-def test_open_file_atomic_permissions_existing_file(runner, permissions):90- with runner.isolated_filesystem():91- with open("existing.txt", "w") as f:92- f.write("content")93- os.chmod("existing.txt", permissions)85+def test_open_file_atomic_permissions_existing_file(runner, tmp_path, permissions):86+ existing = tmp_path / "existing.txt"87+ existing.write_text("content")88+ os.chmod(existing, permissions)89 95- @click.command()96- @click.argument("filename")97- def cli(filename):98- click.open_file(filename, "w", atomic=True).close()90+ @click.command()91+ @click.argument("filename")92+ def cli(filename):93+ click.open_file(filename, "w", atomic=True).close()94 100- result = runner.invoke(cli, ["existing.txt"])101- assert result.exception is None102- assert stat.S_IMODE(os.stat("existing.txt").st_mode) == permissions95+ result = runner.invoke(cli, [str(existing)])96+ assert result.exception is None97+ assert stat.S_IMODE(os.stat(existing).st_mode) == permissions98 99 100 @pytest.mark.skipif(WIN, reason="os.stat() is not fully supported on Windows.")106-def test_open_file_atomic_permissions_new_file(runner):107- with runner.isolated_filesystem():101+def test_open_file_atomic_permissions_new_file(runner, tmp_path):102+ @click.command()103+ @click.argument("filename")104+ def cli(filename):105+ click.open_file(filename, "w", atomic=True).close()106 109- @click.command()110- @click.argument("filename")111- def cli(filename):112- click.open_file(filename, "w", atomic=True).close()107+ # Create a test file to get the expected permissions for new files108+ # according to the current umask.109+ probe = tmp_path / "test.txt"110+ with open(probe, "w"):111+ pass112+ permissions = stat.S_IMODE(os.stat(probe).st_mode)113 114- # Create a test file to get the expected permissions for new files115- # according to the current umask.116- with open("test.txt", "w"):117- pass118- permissions = stat.S_IMODE(os.stat("test.txt").st_mode)119-120- result = runner.invoke(cli, ["new.txt"])121- assert result.exception is None122- assert stat.S_IMODE(os.stat("new.txt").st_mode) == permissions114+ new = tmp_path / "new.txt"115+ result = runner.invoke(cli, [str(new)])116+ assert result.exception is None117+ assert stat.S_IMODE(os.stat(new).st_mode) == permissionsmodified:tests/test_utils/test_prompt.py+26 added
12 unmodified lines13 capfd.readouterr()14 assert isinstance(value, int)15 16 17+def test_prompt_default_round_trips_through_type(capfd, monkeypatch):18+ """A default that already has the converted value type still passes19+ through ``ParamType.convert``, so conversion side effects keep20+ applying to defaults."""21+22+ class DoublingType(click.ParamType[int]):23+ name = "doubling"24+25+ def convert(self, value, param, ctx):26+ return int(value) * 227+28+ monkeypatch.setattr(sys, "stdin", StringIO("\n"))29+ value = click.prompt("value", default=5, type=DoublingType())30+ capfd.readouterr()31+ assert value == 1032+33+34+def test_prompt_default_validated_by_type(capfd, monkeypatch):35+ """An out-of-range default is rejected by the type's validation and36+ prompts again instead of being returned as-is."""37+ monkeypatch.setattr(sys, "stdin", StringIO("\n7\n"))38+ value = click.prompt("value", default=100, type=click.IntRange(0, 10))39+ capfd.readouterr()40+ assert value == 741+42+43 @pytest.mark.skipif(WIN, reason="Different behavior on windows.")44 def test_prompts_abort(monkeypatch, capsys):45 def f(_):46 raise KeyboardInterrupt()54 unmodified linesadded:tests/typing/typing_edit.py+10 added
1+from pathlib import Path2+3+from typing_extensions import assert_type4+5+import click6+7+# ``filename`` accepts a path or an iterable of paths.8+assert_type(click.edit(filename="f.txt"), None)9+assert_type(click.edit(filename=Path("f.txt")), None)10+assert_type(click.edit(filename=["f.txt", Path("g.txt")]), None)added:tests/typing/typing_prompt.py+50 added
1+from typing_extensions import assert_type2+3+import click4+5+# Without ``type``, ``value_proc``, or a non-``str`` ``default``, the raw6+# string input is returned.7+assert_type(click.prompt("Name"), str)8+assert_type(click.prompt("Name", default="bob"), str)9+10+# The return type is narrowed by the ``type`` argument, whether it is a11+# ParamType instance or a plain class, independently of the default's type.12+assert_type(click.prompt("Age", type=click.INT), int)13+assert_type(click.prompt("Age", type=click.IntRange(0, 130), default=18), int)14+assert_type(click.prompt("Age", type=int), int)15+assert_type(click.prompt("Age", type=int, default="100"), int)16+17+# The return type is narrowed by the ``value_proc`` argument.18+19+20+def to_float(value: str) -> float:21+ return float(value)22+23+24+assert_type(click.prompt("Ratio", value_proc=to_float), float)25+26+# The return type is narrowed by the ``default`` argument alone.27+assert_type(click.prompt("Age", default=18), int)28+29+30+# A custom type may declare both its converted value and accepted input31+# types. Omitting the input type parameter defaults it to ``Any``.32+class DoublingType(click.ParamType[int, str]):33+ name = "doubling"34+35+ def convert(36+ self, value: str, param: click.Parameter | None, ctx: click.Context | None37+ ) -> int:38+ return int(value) * 239+40+41+assert_type(click.prompt("Num", type=DoublingType()), int)42+assert_type(DoublingType()("21"), int)43+assert_type(DoublingType()(None), None)44+45+46+class SimpleType(click.ParamType[int]):47+ name = "simple"48+49+50+assert_type(SimpleType()("21"), int)modified:tests/test_arguments.py+16 added-19 removed
100 unmodified lines101 catch_exceptions=False,102 )103 104 105-def test_file_args(runner):105+def test_file_args(runner, tmp_path):106 @click.command()107 @click.argument("input", type=click.File("rb"))108 @click.argument("output", type=click.File("wb"))109 def inout(input, output):2 unmodified lines112 if not chunk:113 break114 output.write(chunk)115 116- with runner.isolated_filesystem():117- result = runner.invoke(inout, ["-", "hello.txt"], input="Hey!")118- assert result.output == ""119- assert result.exit_code == 0120- with open("hello.txt", "rb") as f:121- assert f.read() == b"Hey!"116+ hello = tmp_path / "hello.txt"117+ result = runner.invoke(inout, ["-", str(hello)], input="Hey!")118+ assert result.output == ""119+ assert result.exit_code == 0120+ assert hello.read_bytes() == b"Hey!"121 123- result = runner.invoke(inout, ["hello.txt", "-"])124- assert result.output == "Hey!"125- assert result.exit_code == 0122+ result = runner.invoke(inout, [str(hello), "-"])123+ assert result.output == "Hey!"124+ assert result.exit_code == 0125 126 127 def test_path_allow_dash(runner):128 @click.command()5 unmodified lines134 assert result.output == "-\n"135 assert result.exit_code == 0136 137 139-def test_file_atomics(runner):138+def test_file_atomics(runner, tmp_path):139 @click.command()140 @click.argument("output", type=click.File("wb", atomic=True))141 def inout(output):142 output.write(b"Foo bar baz\n")1 unmodified line144 with open(output.name, "rb") as f:145 old_content = f.read()146 assert old_content == b"OLD\n"147 149- with runner.isolated_filesystem():150- with open("foo.txt", "wb") as f:151- f.write(b"OLD\n")152- result = runner.invoke(inout, ["foo.txt"], input="Hey!", catch_exceptions=False)153- assert result.output == ""154- assert result.exit_code == 0155- with open("foo.txt", "rb") as f:156- assert f.read() == b"Foo bar baz\n"148+ foo = tmp_path / "foo.txt"149+ foo.write_bytes(b"OLD\n")150+ result = runner.invoke(inout, [str(foo)], input="Hey!", catch_exceptions=False)151+ assert result.output == ""152+ assert result.exit_code == 0153+ assert foo.read_bytes() == b"Foo bar baz\n"154 155 156 def test_stdout_default(runner):157 @click.command()583 unmodified linesmodified:tests/test_basic.py+38 added-40 removed
413 unmodified lines414 result = runner.invoke(cli, args)415 assert result.output == repr(expected)416 417 418-def test_file_option(runner):418+def test_file_option(runner, tmp_path):419 @click.command()420 @click.option("--file", type=click.File("w"))421 def input(file):422 file.write("Hello World!\n")2 unmodified lines425 @click.option("--file", type=click.File("r"))426 def output(file):427 click.echo(file.read())428 429- with runner.isolated_filesystem():430- result_in = runner.invoke(input, ["--file=example.txt"])431- result_out = runner.invoke(output, ["--file=example.txt"])429+ example = tmp_path / "example.txt"430+ result_in = runner.invoke(input, [f"--file={example}"])431+ result_out = runner.invoke(output, [f"--file={example}"])432 433 assert not result_in.exception434 assert result_in.output == ""435 assert not result_out.exception436 assert result_out.output == "Hello World!\n\n"437 438 439-def test_file_lazy_mode(runner):439+def test_file_lazy_mode(runner, tmp_path):440 do_io = False441 442 @click.command()443 @click.option("--file", type=click.File("w"))5 unmodified lines449 @click.option("--file", type=click.File("r"))450 def output(file):451 pass452 453- with runner.isolated_filesystem():454- os.mkdir("example.txt")453+ example = tmp_path / "example.txt"454+ example.mkdir()455 456- do_io = True457- result_in = runner.invoke(input, ["--file=example.txt"])458- assert result_in.exit_code == 1456+ do_io = True457+ result_in = runner.invoke(input, [f"--file={example}"])458+ assert result_in.exit_code == 1459 460- do_io = False461- result_in = runner.invoke(input, ["--file=example.txt"])462- assert result_in.exit_code == 0460+ do_io = False461+ result_in = runner.invoke(input, [f"--file={example}"])462+ assert result_in.exit_code == 0463 464- result_out = runner.invoke(output, ["--file=example.txt"])465- assert result_out.exception464+ result_out = runner.invoke(output, [f"--file={example}"])465+ assert result_out.exception466 467 @click.command()468 @click.option("--file", type=click.File("w", lazy=False))469 def input_non_lazy(file):470 file.write("Hello World!\n")471 472- with runner.isolated_filesystem():473- os.mkdir("example.txt")474- result_in = runner.invoke(input_non_lazy, ["--file=example.txt"])475- assert result_in.exit_code == 2476- assert "Invalid value for '--file': 'example.txt'" in result_in.output472+ non_lazy = tmp_path / "non_lazy.txt"473+ non_lazy.mkdir()474+ result_in = runner.invoke(input_non_lazy, [f"--file={non_lazy}"])475+ assert result_in.exit_code == 2476+ assert f"Invalid value for '--file': '{non_lazy}'" in result_in.output477 478 479-def test_path_option(runner):479+def test_path_option(runner, tmp_path):480 @click.command()481 @click.option("-O", type=click.Path(file_okay=False, exists=True, writable=True))482 def write_to_dir(o):483 with open(os.path.join(o, "foo.txt"), "wb") as f:484 f.write(b"meh\n")485 486- with runner.isolated_filesystem():487- os.mkdir("test")486+ test_dir = tmp_path / "test"487+ test_dir.mkdir()488 489- result = runner.invoke(write_to_dir, ["-O", "test"])490- assert not result.exception489+ result = runner.invoke(write_to_dir, ["-O", str(test_dir)])490+ assert not result.exception491 492- with open("test/foo.txt", "rb") as f:493- assert f.read() == b"meh\n"492+ with open(test_dir / "foo.txt", "rb") as f:493+ assert f.read() == b"meh\n"494 495- result = runner.invoke(write_to_dir, ["-O", "test/foo.txt"])496- assert "is a file" in result.output495+ result = runner.invoke(write_to_dir, ["-O", str(test_dir / "foo.txt")])496+ assert "is a file" in result.output497 498 @click.command()499 @click.option("-f", type=click.Path(exists=True))500 def showtype(f):501 click.echo(f"is_file={os.path.isfile(f)}")502 click.echo(f"is_dir={os.path.isdir(f)}")503 504- with runner.isolated_filesystem():505- result = runner.invoke(showtype, ["-f", "xxx"])506- assert "does not exist" in result.output504+ result = runner.invoke(showtype, ["-f", str(tmp_path / "xxx")])505+ assert "does not exist" in result.output506 508- result = runner.invoke(showtype, ["-f", "."])509- assert "is_file=False" in result.output510- assert "is_dir=True" in result.output507+ result = runner.invoke(showtype, ["-f", str(tmp_path)])508+ assert "is_file=False" in result.output509+ assert "is_dir=True" in result.output510 511 @click.command()512 @click.option("-f", type=click.Path())513 def exists(f):514 click.echo(f"exists={os.path.exists(f)}")515 517- with runner.isolated_filesystem():518- result = runner.invoke(exists, ["-f", "xxx"])519- assert "exists=False" in result.output516+ result = runner.invoke(exists, ["-f", str(tmp_path / "xxx")])517+ assert "exists=False" in result.output518 521- result = runner.invoke(exists, ["-f", "."])522- assert "exists=True" in result.output519+ result = runner.invoke(exists, ["-f", str(tmp_path)])520+ assert "exists=True" in result.output521 522 523 def test_choice_option(runner):524 @click.command()438 unmodified linesmodified:tests/test_commands.py+50 added
417 unmodified lines418 == expected_params419 )420 421 422+@pytest.mark.parametrize(423+ ("help_option_names", "params", "expected"),424+ [425+ # A single default name is returned unchanged.426+ (["--help"], [], ["--help"]),427+ # Declaration order is preserved verbatim, whatever it is.428+ (["-h", "--help"], [], ["-h", "--help"]),429+ (["--help", "-h"], [], ["--help", "-h"]),430+ (["--help", "-h", "-?"], [], ["--help", "-h", "-?"]),431+ (["-?", "--help", "-h"], [], ["-?", "--help", "-h"]),432+ # Duplicate names collapse to their first occurrence, keeping order.433+ (["--help", "--help"], [], ["--help"]),434+ (["-h", "--help", "-h"], [], ["-h", "--help"]),435+ # A name already claimed by another parameter's option is dropped.436+ (["-h", "--help"], [["--help"]], ["-h"]),437+ (["-h", "--help"], [["-h", "--verbose"]], ["--help"]),438+ # Both options of a feature-switch flag are removed too.439+ (["--shout", "--help"], [["--shout/--no-shout"]], ["--help"]),440+ (["--no-shout", "--help"], [["--shout/--no-shout"]], ["--help"]),441+ # Filtering every name out yields an empty list.442+ (["-h", "--help"], [["-h"], ["--help"]], []),443+ # Deduplication and conflict removal combine, order still preserved.444+ (["-h", "--help", "-h", "--assist"], [["--assist"]], ["-h", "--help"]),445+ ],446+ ids=[447+ "default",448+ "order-short-long",449+ "order-long-short",450+ "order-three",451+ "order-three-shuffled",452+ "dedupe-adjacent",453+ "dedupe-spread",454+ "conflict-long",455+ "conflict-short",456+ "conflict-flag-on",457+ "conflict-flag-off",458+ "all-removed",459+ "dedupe-and-conflict",460+ ],461+)462+def test_get_help_option_names(help_option_names, params, expected):463+ """Check help option names are deduplicated but keep stable order.464+465+ https://github.com/pallets/click/pull/3728466+ """467+ cli = click.Command("cli", params=[click.Option(decls) for decls in params])468+ ctx = click.Context(cli, help_option_names=help_option_names)469+ assert cli.get_help_option_names(ctx) == expected470+471+472 def test_help_param_priority(runner):473 """Cover the edge-case in which the eagerness of help option was not474 respected, because it was internally generated multiple times.475 225 unmodified linesmodified:tests/test_deprecations.py+63 added-15 removed
1+import importlib.metadata2+3 import pytest4 5 import click6+import click.core7+import click.parser8+import click.shell_completion9+import click.utils10 11 6-@pytest.mark.parametrize("module", [click, click.utils], ids=["click", "click.utils"])7-@pytest.mark.parametrize("name", ["get_binary_stream", "get_text_stream"])8-def test_stream_helper_deprecated(module, name):9- with pytest.warns(DeprecationWarning, match=name):10- getattr(module, name)11-12-12 @pytest.mark.parametrize(14- "name",13+ ("module", "name", "target"),14 [16- "LazyFile",17- "KeepOpenFile",18- "make_default_short_help",19- "PacifyFlushWrapper",20- "safecall",15+ # Stream helpers, re-exported from both `click` and `click.utils`.16+ (click, "get_binary_stream", click.utils._get_binary_stream),17+ (click, "get_text_stream", click.utils._get_text_stream),18+ (click.utils, "get_binary_stream", click.utils._get_binary_stream),19+ (click.utils, "get_text_stream", click.utils._get_text_stream),20+ # Command-class aliases, re-exported from `click` and `click.core`.21+ (click, "BaseCommand", click.core._BaseCommand),22+ (click, "MultiCommand", click.core._MultiCommand),23+ (click.core, "BaseCommand", click.core._BaseCommand),24+ (click.core, "MultiCommand", click.core._MultiCommand),25+ # Old parser API (moved to `optparse`); `OptionParser` is also26+ # re-exported from the top-level `click` namespace.27+ (click, "OptionParser", click.parser._OptionParser),28+ (click.parser, "OptionParser", click.parser._OptionParser),29+ (click.parser, "Argument", click.parser._Argument),30+ (click.parser, "Option", click.parser._Option),31+ (click.parser, "split_opt", click.parser._split_opt),32+ (click.parser, "normalize_opt", click.parser._normalize_opt),33+ (click.parser, "ParsingState", click.parser._ParsingState),34+ (click.parser, "split_arg_string", click.shell_completion.split_arg_string),35+ # Deprecated `click.utils` utilities.36+ (click.utils, "LazyFile", click.utils._LazyFile),37+ (click.utils, "KeepOpenFile", click.utils._KeepOpenFile),38+ (click.utils, "make_default_short_help", click.utils._make_default_short_help),39+ (click.utils, "PacifyFlushWrapper", click.utils._PacifyFlushWrapper),40+ (click.utils, "safecall", click.utils._safecall),41+ # Version metadata attribute.42+ (click, "__version__", importlib.metadata.version("click")),43 ],44+ ids=lambda v: getattr(v, "__name__", v),45 )23-def test_utilities_deprecated(name):46+def test_attr_deprecated(module, name, target):47 with pytest.warns(DeprecationWarning, match=name):25- getattr(click.utils, name)48+ value = getattr(module, name)49+50+ assert value == target51+52+53+@pytest.mark.parametrize(54+ "module",55+ [click, click.core, click.parser, click.utils],56+ ids=lambda m: m.__name__,57+)58+def test_unknown_attribute_raises(module):59+ with pytest.raises(AttributeError, match="no_such_attribute"):60+ _ = module.no_such_attribute61+62+63+def test_context_protected_args_deprecated():64+ ctx = click.Context(click.Command("cli"))65+66+ with pytest.warns(DeprecationWarning, match="protected_args"):67+ assert ctx.protected_args == []68+69+70+def test_isolated_filesystem_deprecated(runner):71+ with pytest.warns(DeprecationWarning, match="isolated_filesystem"):72+ with runner.isolated_filesystem():73+ passmodified:tests/test_shell_completion.py+18 added-19 removed
572 unmodified lines573 assert click.shell_completion._available_shells["mysh"] is MyshComplete574 575 576 # Don't make the ResourceWarning give an error577-@pytest.mark.filterwarnings("default")578-def test_files_closed(runner) -> None:579- with runner.isolated_filesystem():580- config_file = "foo.txt"581- with open(config_file, "w") as f:582- f.write("bar")577+@pytest.mark.filterwarnings("default::ResourceWarning")578+def test_files_closed(tmp_path) -> None:579+ config_file = str(tmp_path / "foo.txt")580+ with open(config_file, "w") as f:581+ f.write("bar")582 584- @click.group()585- @click.option(586- "--config-file",587- default=config_file,588- type=click.File(mode="r"),589- )590- @click.pass_context591- def cli(ctx, config_file):592- pass583+ @click.group()584+ @click.option(585+ "--config-file",586+ default=config_file,587+ type=click.File(mode="r"),588+ )589+ @click.pass_context590+ def cli(ctx, config_file):591+ pass592 594- with warnings.catch_warnings(record=True) as current_warnings:595- assert not current_warnings, "There should be no warnings to start"596- _get_completions(cli, args=[], incomplete="")597- assert not current_warnings, "There should be no warnings after either"593+ with warnings.catch_warnings(record=True) as current_warnings:594+ assert not current_warnings, "There should be no warnings to start"595+ _get_completions(cli, args=[], incomplete="")596+ assert not current_warnings, "There should be no warnings after either"597 598 599 def test_fish_format_completion_escapes_help():600 fc = FishComplete(Command("x"), {}, "x", "_X_COMPLETE")17 unmodified linesmodified:tests/test_termui.py+383 added-11 removed
1 import contextlib2 import gc3 import io4+import os5+import pathlib6 import platform7 import shlex8 import shutil9+import subprocess10 import sys11 import tempfile12 import time13 from unittest.mock import patch94 unmodified lines108 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)109 assert runner.invoke(cli, []).output == ""110 111 112+@pytest.mark.parametrize("update_min_steps", [1, 2, 3, 7, 20, 25])113+@pytest.mark.parametrize("drive", ["iterate", "update"])114+def test_progressbar_lands_on_final_position(monkeypatch, update_min_steps, drive):115+ """The bar reaches its total whatever the ``update_min_steps`` threshold.116+117+ Regression for issue #3571: a threshold that does not divide the length118+ left a remainder pending, so `show_pos` froze below completion, reporting119+ `14/20` for a length of 20 and a threshold of 7. Thresholds of 1 and 2 do120+ divide 20, and 25 exceeds it, so nothing is ever rendered until the end.121+ """122+ monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)123+ stream = io.StringIO()124+125+ if drive == "iterate":126+ with click.progressbar(127+ range(20), show_pos=True, update_min_steps=update_min_steps, file=stream128+ ) as bar:129+ for _ in bar:130+ pass131+ else:132+ with click.progressbar(133+ length=20, show_pos=True, update_min_steps=update_min_steps, file=stream134+ ) as bar:135+ for _ in range(20):136+ bar.update(1)137+138+ assert bar.pos == 20139+ assert bar.finished140+ assert "20/20" in stream.getvalue()141+142+143 @pytest.mark.parametrize("avg, expected", [([], 0.0), ([1, 4], 2.5)])144 def test_progressbar_time_per_iteration(runner, avg, expected):145 with _create_progress(2, avg=avg) as progress:146 assert progress.time_per_iteration == expected273 unmodified lines420 with pytest.raises(exc):421 click.getchar()422 423 390-@pytest.mark.skipif(platform.system() == "Windows", reason="No sed on Windows.")424+@pytest.mark.skipif(WIN, reason="No sed on Windows.")425 def test_fast_edit(runner):426 result = click.edit("a\nb", editor="sed -i~ 's/$/Test/'")427 assert result == "aTest\nbTest\n"428 429 396-@pytest.mark.skipif(platform.system() == "Windows", reason="No sed on Windows.")430+@pytest.mark.skipif(WIN, reason="No sed on Windows.")431 def test_edit(runner):432 with tempfile.NamedTemporaryFile(mode="w") as named_tempfile:433 named_tempfile.write("a\nb\n")434 named_tempfile.flush()12 unmodified lines447 # terminated by newline too.448 assert reopened_file.read() == "aTest\nbTest\n"449 450 451+@pytest.mark.skipif(WIN, reason="No sed on Windows.")452+@pytest.mark.parametrize("use_iterable", [False, True], ids=["single", "iterable"])453+def test_edit_pathlib(runner, tmp_path, use_iterable):454+ """Issue #2869: ``filename`` accepts ``os.PathLike`` values."""455+ file_path = tmp_path / "file.txt"456+ file_path.write_text("a\nb\n", encoding="UTF-8")457+ filename = [file_path] if use_iterable else file_path458+459+ result = click.edit(filename=filename, editor="sed -i~ 's/$/Test/'")460+ assert result is None461+ assert file_path.read_text(encoding="UTF-8") == "aTest\nbTest\n"462+463+464 @pytest.mark.parametrize(465 ("editor_cmd", "filenames", "expected_args"),466 [467 pytest.param(305 unmodified lines773 assert err == ""774 assert out == expected775 776 777+@pytest.mark.skipif(WIN, reason="The fake pager is a shell script.")778+@pytest.mark.parametrize(779+ ("pager_name", "expected_color"),780+ [781+ pytest.param("less", True, id="less"),782+ pytest.param("less.exe", True, id="less.exe"),783+ pytest.param("LESS.EXE", False, id="upper case stays unmatched on POSIX"),784+ pytest.param("cat", False, id="not less"),785+ ],786+)787+def test_pipepager_less_detection_matches_stem(788+ monkeypatch, tmp_path, pager_name, expected_color789+):790+ """The ``less`` detection behind the ``LESS=-R`` auto-enable matches the791+ command stem, so a ``less.exe`` resolved on Windows is recognized the same792+ as a bare ``less``. POSIX keeps an exact, case-sensitive match.793+ """794+ fake_pager = tmp_path / pager_name795+ fake_pager.write_text("#!/bin/sh\ncat\n", encoding="UTF-8")796+ fake_pager.chmod(0o755)797+798+ monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)799+ monkeypatch.setitem(click._termui_impl.os.environ, "PAGER", str(fake_pager))800+ monkeypatch.delitem(click._termui_impl.os.environ, "LESS", raising=False)801+802+ with click.get_pager_file() as pager:803+ assert pager.color is expected_color804+805+806+@pytest.mark.skipif(WIN, reason="The fake pager is a shell script.")807+def test_pipepager_less_detection_case_insensitive_on_windows(monkeypatch, tmp_path):808+ """Windows filesystems are case-insensitive, so ``which`` resolves809+ whatever case the file carries: the ``less`` match casefolds there.810+811+ Runs ``_pipepager`` directly: faking ``WIN`` makes812+ ``_pager_contextmanager`` route to the temp file strategy instead.813+ """814+ fake_pager = tmp_path / "LESS.EXE"815+ fake_pager.write_text("#!/bin/sh\ncat\n", encoding="UTF-8")816+ fake_pager.chmod(0o755)817+818+ monkeypatch.setattr(click._termui_impl, "WIN", True)819+ monkeypatch.delitem(click._termui_impl.os.environ, "LESS", raising=False)820+821+ with click._termui_impl._pipepager(fake_pager, []) as (_, color):822+ assert color is True823+824+825+class _FakePagerProcess:826+ """Stand-in for :class:`subprocess.Popen` recording argv and env without827+ launching a process."""828+829+ def __init__(self, argv, *, env=None, **kwargs):830+ self.argv = argv831+ self.env = env832+ self.returncode = 0833+ self.stdin = io.StringIO()834+835+ def terminate(self):836+ pass837+838+ def wait(self):839+ return 0840+841+842+@pytest.mark.parametrize(843+ ("cmd_parts", "less_env", "expected_color", "expected_less"),844+ [845+ pytest.param(["less"], None, True, "-R", id="no flags: inject LESS=-R"),846+ pytest.param(["less", "-R"], None, True, None, id="explicit -R"),847+ pytest.param(["less", "-rX"], None, True, None, id="bundled short flags"),848+ pytest.param(["less"], "-R", True, "-R", id="LESS env var"),849+ pytest.param(850+ ["less", "--RAW-CONTROL-CHARS"], None, True, None, id="long option"851+ ),852+ pytest.param(["less", "-X"], None, None, None, id="unrelated flag"),853+ pytest.param(854+ ["less"],855+ "--prompt=resume",856+ None,857+ "--prompt=resume",858+ id="long option with r substring",859+ ),860+ pytest.param(["less", "README.md"], None, None, None, id="filename with R"),861+ pytest.param(862+ ["less", "requirements.txt"], None, None, None, id="filename with r"863+ ),864+ pytest.param(865+ ["less", "--", "README.md"],866+ None,867+ None,868+ None,869+ id="option terminator shields filenames",870+ ),871+ pytest.param(872+ # The detection matches the bare long option: an ``r`` inside an873+ # option value does not request raw mode.874+ ["less", "--raw-control-chars=x"],875+ None,876+ None,877+ None,878+ id="long option with value",879+ ),880+ pytest.param(881+ # Unbalanced quotes make shlex.split raise: the detection falls882+ # back to whitespace splitting, which still finds the -R.883+ ["less"],884+ '-R "',885+ True,886+ '-R "',887+ id="unparsable LESS",888+ ),889+ ],890+)891+def test_pipepager_less_raw_mode_detection(892+ monkeypatch, cmd_parts, less_env, expected_color, expected_less893+):894+ """Raw-mode detection parses the option tokens from ``LESS`` and the895+ command line. Filenames and unrelated options carrying the letter ``r``896+ or ``R`` do not request raw mode, and ``_pipepager`` then reports no897+ opinion (``None``) that :func:`get_pager_file` settles to off.898+ {issue}`3416`899+ """900+ if less_env is None:901+ monkeypatch.delitem(click._termui_impl.os.environ, "LESS", raising=False)902+ else:903+ monkeypatch.setitem(click._termui_impl.os.environ, "LESS", less_env)904+905+ processes: list[_FakePagerProcess] = []906+907+ def fake_popen(*args, **kwargs):908+ process = _FakePagerProcess(*args, **kwargs)909+ processes.append(process)910+ return process911+912+ monkeypatch.setattr(subprocess, "Popen", fake_popen)913+ # Popen is faked, so no real binary needs to exist behind the resolved914+ # path: the stem is all the less detection reads from it.915+ cmd_path = pathlib.Path("/tests/less")916+917+ with click._termui_impl._pipepager(cmd_path, cmd_parts[1:]) as (_, color):918+ pass919+920+ assert color is expected_color921+ (process,) = processes922+ if expected_less is None:923+ assert "LESS" not in process.env924+ else:925+ assert process.env["LESS"] == expected_less926+927+928 def test_echo_via_pager_streams_each_write(monkeypatch):929 """Each write is flushed so a slow generator streams to the pager930 incrementally instead of buffering until the end (issues #3242, #2542).931 """137 unmodified lines1069 )1070 def test_get_pager_file_nullpager_wraps_textio_stream(1071 monkeypatch, tmp_path, color, expected1072 ):875- """When paging falls back to a real TextIO stream, ``.buffer`` is wrapped."""1073+ """When paging falls back to a real text stream, ANSI styling is stripped or1074+ preserved according to ``color``."""1075 pager_out = tmp_path / "pager_out.txt"1076 1077 with pager_out.open("w", encoding="utf-8") as text_stream:1078 monkeypatch.setattr(9 unmodified lines1088 assert pager_out.read_text(encoding="utf-8") == expected1089 1090 1091 def test_get_pager_file_nullpager_keeps_stringio_stream(monkeypatch):893- """The no-stdout fallback should keep a text-only stream and set ``.color``."""1092+ """The no-stdout fallback keeps the text stream open and strips ANSI."""1093 1094 stream = io.StringIO()1095 monkeypatch.setattr(sys, "stdout", None)1096 monkeypatch.setattr(click._termui_impl, "StringIO", lambda: stream)1097 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: False)1098 900- styled_text = click.style("hello", fg="red")901-1099 with click.get_pager_file(color=False) as pager:903- pager.write(styled_text)1100+ pager.write(click.style("hello", fg="red"))1101 1102+ # The wrapper must not close a stream it does not own.1103 assert not stream.closed1104+ # With colors disabled, ANSI styling is stripped.906- assert stream.getvalue() == styled_text1105+ assert stream.getvalue() == "hello"1106 1107 1108 def test_get_pager_file_flushes_stream_on_exception(monkeypatch):1109 """Exceptions should still flush the yielded stream in ``finally``."""1110 1111 class FlushableTextStream(io.StringIO):1112 def __init__(self):1113 super().__init__()915- self.color = None1114 self.flush_calls = 01115 1116 def flush(self):1117 self.flush_calls += 11 unmodified line1119 stream = FlushableTextStream()1120 1121 @contextlib.contextmanager1122 def pager_contextmanager(color=None):925- yield stream, "utf-8", color1123+ yield stream, False1124 1125 monkeypatch.setattr(1126 click._termui_impl, "_pager_contextmanager", pager_contextmanager1127 )1128 1129 with pytest.raises(RuntimeError, match="boom"):1130 with click.get_pager_file() as pager:933- assert pager is stream1131+ pager.write("partial")1132 raise RuntimeError("boom")1133 1134 assert stream.flush_calls == 11135+ assert stream.getvalue() == "partial"1136 1137 1138+def test_get_pager_file_close_does_not_close_borrowed_stream(monkeypatch):1139+ """Closing the yielded pager must not close a stream the caller owns.1140+1141+ ``_PagerWriter.close()`` flushes but deliberately stops there: each pager1142+ strategy owns its stream's lifecycle. This is the caller-driven half of1143+ ``test_get_pager_file_missing_pager_keeps_borrowed_stream_open``, which1144+ covers the same fallback but never calls ``close`` itself.1145+1146+ Wrapping the borrowed stream in :class:`~click.utils._KeepOpenFile` does not1147+ satisfy this: that proxy only covers a ``with`` block and passes an explicit1148+ ``close`` straight through. Only the writer's own ``close`` stops it.1149+ """1150+ stream = io.StringIO()1151+ monkeypatch.setattr(click._termui_impl, "_default_text_stdout", lambda: stream)1152+ monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)1153+ # A tty plus a ``PAGER`` that doesn't resolve sends us through the1154+ # ``_pipepager`` (or ``_tempfilepager``) missing-binary fallback branch.1155+ monkeypatch.setitem(1156+ click._termui_impl.os.environ,1157+ "PAGER",1158+ "click-tests-nonexistent-pager-9b3f2",1159+ )1160+1161+ with click.get_pager_file() as pager:1162+ pager.write("hello\n")1163+ pager.close()1164+ assert not stream.closed1165+1166+ assert not stream.closed1167+ assert stream.getvalue() == "hello\n"1168+1169+1170+def _force_tempfile_pager(monkeypatch, pager_cmd="cat"):1171+ """Route ``get_pager_file`` through the ``_tempfilepager`` backend.1172+1173+ That backend is only reachable on Windows, so the platform flag and the tty1174+ probes are faked to exercise it from any runner.1175+1176+ ``PAGER`` is set to the bare command name, not to the path1177+ :func:`shutil.which` resolves it to. ``pager()`` splits ``PAGER`` with1178+ :func:`shlex.split` in POSIX mode, where a Windows path loses its1179+ backslashes and splits on the space in ``C:\\Program Files``, leaving a1180+ command that resolves to nothing. Click resolves the bare name itself.1181+ """1182+ cmd = shlex.split(pager_cmd)[0]1183+ assert shutil.which(cmd) is not None, f"{cmd} not available"1184+ monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)1185+ monkeypatch.setattr(click._termui_impl, "WIN", True)1186+ monkeypatch.setitem(click._termui_impl.os.environ, "PAGER", pager_cmd)1187+1188+1189+def _page_with_get_pager_file():1190+ with click.get_pager_file() as pager:1191+ pager.write("hello\n")1192+1193+1194+def _page_with_echo_via_pager():1195+ click.echo_via_pager("hello")1196+1197+1198+@pytest.mark.skipif(shutil.which("cat") is None, reason="cat not available")1199+@pytest.mark.parametrize(1200+ "page",1201+ [1202+ pytest.param(_page_with_get_pager_file, id="get_pager_file"),1203+ pytest.param(_page_with_echo_via_pager, id="echo_via_pager"),1204+ ],1205+)1206+def test_tempfile_pager_accepts_text(monkeypatch, capfd, page):1207+ """The temp file backend must yield a text stream (issues #3731, #3740).1208+1209+ Regression: a binary-mode temp file handed straight to ``get_pager_file``1210+ left the caller writing ``str`` to a binary handle, which raises1211+ ``TypeError: a bytes-like object is required``.1212+ """1213+ _force_tempfile_pager(monkeypatch)1214+1215+ page()1216+1217+ out, err = capfd.readouterr()1218+ assert err == ""1219+ assert out.replace("\r\n", "\n") == "hello\n"1220+1221+1222+@pytest.mark.skipif(shutil.which("cat") is None, reason="cat not available")1223+@pytest.mark.parametrize(1224+ ("color", "expected"),1225+ [1226+ pytest.param(False, "hello\n", id="strip ansi"),1227+ pytest.param(True, click.style("hello", fg="red") + "\n", id="preserve ansi"),1228+ ],1229+)1230+def test_tempfile_pager_handles_ansi(monkeypatch, capfd, color, expected):1231+ """The temp file backend honors ``color`` like the pipe backend does.1232+1233+ Regression: a binary temp file got no ANSI-stripping wrapper, so ``color``1234+ was silently ignored on this path.1235+ """1236+ _force_tempfile_pager(monkeypatch)1237+1238+ click.echo_via_pager(click.style("hello", fg="red"), color=color)1239+1240+ out, err = capfd.readouterr()1241+ assert err == ""1242+ assert out.replace("\r\n", "\n") == expected1243+1244+1245+@pytest.mark.skipif(shutil.which("head") is None, reason="head not available")1246+def test_tempfile_pager_passes_pager_params(monkeypatch, capfd):1247+ """The temp file backend forwards ``PAGER`` parameters to the command.1248+1249+ ``head -n 1`` renders one line out of two when the ``-n 1`` reaches the1250+ command.1251+ """1252+ _force_tempfile_pager(monkeypatch, pager_cmd="head -n 1")1253+1254+ click.echo_via_pager("line one\nline two\n")1255+1256+ out, err = capfd.readouterr()1257+ assert err == ""1258+ assert out.replace("\r\n", "\n") == "line one\n"1259+1260+1261+@pytest.mark.skipif(shutil.which("cat") is None, reason="cat not available")1262+def test_tempfile_pager_closes_file_before_unlink(monkeypatch):1263+ """An error while paging must not leave the temp file open at unlink time.1264+1265+ The ``f.close()`` on the success path sits after the ``yield``, so an1266+ exception raised while the pager is open used to skip it and reach1267+ ``finally: os.unlink(f.name)`` with the handle still open. Windows refuses1268+ to unlink an open file, so ``PermissionError: [WinError 32]`` replaced the1269+ original error and hid it (issue #3731).1270+ """1271+ _force_tempfile_pager(monkeypatch)1272+1273+ temp_files = []1274+ real_named_temporary_file = tempfile.NamedTemporaryFile1275+1276+ def record(*args, **kwargs):1277+ f = real_named_temporary_file(*args, **kwargs)1278+ temp_files.append(f)1279+ return f1280+1281+ monkeypatch.setattr(tempfile, "NamedTemporaryFile", record)1282+1283+ closed_at_unlink = []1284+ real_unlink = os.unlink1285+1286+ def spy_unlink(path, **kwargs):1287+ closed_at_unlink.append([f.closed for f in temp_files])1288+ return real_unlink(path, **kwargs)1289+1290+ monkeypatch.setattr(os, "unlink", spy_unlink)1291+1292+ try:1293+ with pytest.raises(RuntimeError, match="boom"):1294+ with click.get_pager_file():1295+ raise RuntimeError("boom")1296+ finally:1297+ # Should this invariant regress, the assertion below reports it. Close1298+ # the handle anyway so the leak does not also resurface as a1299+ # ResourceWarning charged to an unrelated test.1300+ for f in temp_files:1301+ if not f.closed:1302+ f.close()1303+1304+ assert temp_files, "the temp file pager backend was not used"1305+ assert closed_at_unlink == [[True]], (1306+ "temp file still open when unlink ran; on Windows this raises "1307+ "PermissionError [WinError 32] and masks the real error"1308+ )1309+1310+1311 def test_editor_unclosed_quote():1312 """An unclosed quote in the editor command raises ValueError."""1313 with pytest.raises(ValueError, match="No closing quotation"):1314 Editor(editor='"unclosed').edit_files(["f.txt"])670 unmodified linesmodified:tests/test_testing.py+79 added
438 unmodified lines439 result = runner.invoke(cli, ["-"])440 assert result.output == "<stdin>\nr"441 442 443+@pytest.mark.filterwarnings("ignore:'isolated_filesystem':DeprecationWarning")444 def test_isolated_runner(runner):445 with runner.isolated_filesystem() as d:446 assert os.path.exists(d)447 448 assert not os.path.exists(d)449 450 451+@pytest.mark.filterwarnings("ignore:'isolated_filesystem':DeprecationWarning")452 def test_isolated_runner_custom_tempdir(runner, tmp_path):453 with runner.isolated_filesystem(temp_dir=tmp_path) as d:454 assert os.path.exists(d)455 456 assert os.path.exists(d)457 os.rmdir(d)458 459 460+def test_tempdir_replacement_pattern(runner, tmp_path):461+ """The replacement for ``isolated_filesystem()``: a temp dir and absolute paths.462+463+ Rather than changing the working directory, create a directory (here with464+ pytest's ``tmp_path``; ``tempfile.TemporaryDirectory`` works the same) and465+ pass absolute paths to the command.466+ """467+468+ @click.command()469+ @click.argument("path", type=click.Path())470+ def write_marker(path):471+ with open(path, "w") as f:472+ f.write("written")473+474+ target = tmp_path / "marker.txt"475+ result = runner.invoke(write_marker, [str(target)])476+477+ assert result.exit_code == 0478+ assert target.read_text() == "written"479+480+481+def test_tempdir_isolation_is_thread_safe():482+ """The recommended replacement is thread-safe, unlike ``isolated_filesystem()``.483+484+ Each thread owns a ``tempfile.TemporaryDirectory`` and works through485+ absolute paths, so there is no ``os.chdir`` and no process-global CWD race486+ (the reason ``isolated_filesystem()`` is not thread-safe, issue #3501).487+488+ ``invoke()`` is deliberately not called concurrently here: it redirects the489+ process-global standard streams, so parallel invocations in one process490+ corrupt each other regardless of the filesystem. To run commands in491+ parallel, use separate processes (like pytest-xdist), not threads.492+ """493+ import tempfile494+ import threading495+496+ workers = 8497+ cwd_before = os.path.realpath(os.getcwd())498+ results: list[tuple[str, str, str]] = []499+ barrier = threading.Barrier(workers)500+ lock = threading.Lock()501+502+ def worker(index):503+ with tempfile.TemporaryDirectory() as d:504+ target = os.path.join(d, "data.txt")505+ # Release every thread at once to maximize contention.506+ barrier.wait(timeout=10)507+ with open(target, "w") as f:508+ f.write(f"payload-{index}")509+ with open(target) as f:510+ content = f.read()511+ with lock:512+ results.append(513+ (514+ os.path.realpath(d),515+ os.path.realpath(os.getcwd()),516+ content,517+ )518+ )519+520+ threads = [threading.Thread(target=worker, args=(i,)) for i in range(workers)]521+ for t in threads:522+ t.start()523+ for t in threads:524+ t.join(timeout=10)525+526+ assert len(results) == workers527+ # Every thread had its own distinct directory.528+ assert len({d for d, _, _ in results}) == workers529+ # No thread mutated the process-global working directory.530+ assert {cwd for _, cwd, _ in results} == {cwd_before}531+ # Each thread read back exactly the payload it wrote, with no cross-talk.532+ assert sorted(content for _, _, content in results) == sorted(533+ f"payload-{i}" for i in range(workers)534+ )535+536+537 def test_isolation_stderr_errors():538 """Writing to stderr should escape invalid characters instead of539 raising a UnicodeEncodeError.540 """300 unmodified linesmodified:tests/test_types.py+22 added
2 unmodified lines3 import platform4 import subprocess5 import sys6 import tempfile7+import typing as t8 9 import pytest10 11 import click296 unmodified lines308 def test_choice_get_invalid_choice_message():309 choice = click.Choice(["a", "b", "c"])310 message = choice.get_invalid_choice_message("d", ctx=None)311 assert message == "'d' is not one of 'a', 'b', 'c'."312+313+314+def test_param_type_input_parameter_defaults_at_runtime():315+ """Omitting the input type parameter works at runtime on every316+ supported Python. The ``Any`` default is native (PEP 696) on Python317+ 3.13+, and backfilled by ``ParamType.__class_getitem__`` before318+ that."""319+ assert t.get_args(click.ParamType[int]) == (int, t.Any)320+ assert t.get_args(click.ParamType[int, str]) == (int, str)321+322+323+def test_param_type_subclass_omitting_input_parameter():324+ class DoublingType(click.ParamType[int]):325+ name = "doubling"326+327+ def convert(self, value, param, ctx):328+ return int(value) * 2329+330+ doubling = DoublingType()331+ assert doubling("21") == 42332+ assert doubling(None) is Nonemodified:CHANGES.md+53 added-5 removed
1 ## Version 8.5.02 3-Unreleased3+Released 2026-08-244 5 - Add built-in shell completion support for PowerShell (Windows PowerShell6 5.1+ and pwsh 7+) alongside the existing `bash`, `zsh`, and `fish`7 completers. Use `_FOO_BAR_COMPLETE=powershell_source foo-bar` to generate8- the completion script.8+ the completion script. {issue}`2672` {pr}`3637`9 - Supported versions of Windows enable ANSI terminal styles by default.10 Colorama is no longer a dependency and is not used. {issue}`2986` {pr}`3505`11 - {class}`Argument` accepts a `help` parameter, and help output includes12 a `Positional arguments` section when argument help is available. {issue}`2983` {pr}`3473`1 unmodified line14 prompt when the output stream does not support them, matching `echo()`.15 This stripping was lost in `8.4.0` when {pr}`2969` began writing the16 prompt with `input()` directly. {issue}`3572` {pr}`3653`17 - Fix test failures when using pytest >= 9.1. {pr}`3656`18+- {class}`Path` with `allow_dash=True` no longer triggers a `BytesWarning`,19+ an error under `python -bb`, when checking a value against the `-`20+ convention. {issue}`2877` {pr}`3642`21 - Add {func}`custom_version_option`, a `--version` option whose output is22 produced by a callback, covering cases {func}`version_option` intentionally23 does not. The feature set of {func}`version_option` is now frozen; see24 [discussion #3527](https://github.com/pallets/click/discussions/3527). {pr}`3581`25 - `style()` and `secho()` no longer silently drop the 256-color index `0`23- (black) passed as `fg` or `bg`, and now validate color arguments. {pr}`3677`26+ (black) passed as `fg` or `bg`, and now validate color arguments. Invalid27+ colors raise a `ValueError` instead of a `TypeError`. {pr}`3677`28 - The automatic help option stores its value under the reserved name29 `_click_default_help` instead of `help`, so a parameter named `help` no30 longer breaks parsing. The new name is visible in31 {meth}`Command.to_info_dict` output. Parameters that overwrite each other's1 unmodified line33 parameter, or any parameter claiming the reserved name. Options may still34 share a name to compete for the same value (feature switches).35 {issue}`2819` {pr}`3678`36 - `unstyle` and the ANSI handling behind help-text wrapping now strip the full33- CSI escape-sequence grammar.37+ CSI escape-sequence grammar. {pr}`3681`38 - Streamline `Option` flag handling: the flag-kind, type, lazy-default and39 validation steps in `Option.__init__` move into focused helpers, and40 `flag_value` and `default` keep their unset sentinel at construction41 (resolved lazily on read) so `is UNSET` reliably tells a user-supplied value38- from an auto-derived one. Behavior is unchanged. {pr}`3641`42+ from an auto-derived one. Runtime behavior is unchanged, but43+ {meth}`Parameter.to_info_dict` now resolves `default=True` on a feature44+ switch to its `flag_value`, matching what the function receives at call45+ time. {pr}`3641`46 - {func}`get_binary_stream` and {func}`get_text_stream` are deprecated and47 will be removed in Click 9.0. {issue}`3481` {pr}`3695`48 - The following `click.utils` names were never intentionally public and are49 now private (`_`-prefixed). The old names remain available with a50 `DeprecationWarning` until Click 9.0: `LazyFile`, `KeepOpenFile`,51 `make_default_short_help`, `PacifyFlushWrapper`, and `safecall`.52 {issue}`3099` {pr}`3695`53+- Deprecate {meth}`CliRunner.isolated_filesystem`. It relies on54+ {func}`os.chdir`, which mutates process-global state and is not55+ thread-safe. The helper predates Python 3 and modern pytest: use a56+ temporary directory ({class}`tempfile.TemporaryDirectory` or pytest's57+ `tmp_path` fixture) with absolute paths instead. For running tests in58+ parallel, use process-based isolation (such as `pytest-xdist`) rather59+ than threads, since {meth}`CliRunner.invoke` also redirects the60+ process-global standard streams. {issue}`3501` {issue}`3700` {pr}`3704`61+- `prompt()` is now generically typed and returns the type produced by62+ `type`, `value_proc`, or a matching `default` instead of `Any`.63+ {class}`ParamType` takes a second optional type parameter describing the64+ input value it accepts (`ParamType[int, str]` for a type converting65+ strings to integers), defaulting to `Any`. {pr}`3407`66+- {meth}`Command.get_help_option_names` returns the help option names in the67+ order they were declared. {pr}`3728`68+- {func}`get_pager_file` yields a text stream on Windows again. The temporary69+ file backend opened its file in binary mode, so writing a `str` to the pager70+ raised `TypeError: a bytes-like object is required, not 'str'`, and the71+ `color` argument was ignored on that path. Regression introduced in `8.4.0`72+ by {pr}`1572`. {issue}`3731` {issue}`3732` {issue}`3740` {pr}`3739`73+- {func}`progressbar` settles on its final position when `update_min_steps`74+ does not divide the total. Steps below that threshold are applied when the75+ bar finishes, so `show_pos` renders `20/20` rather than the last multiple76+ it reached. {issue}`3571` {pr}`3769`77+- An error raised while writing to the pager no longer gets replaced by78+ `PermissionError: [WinError 32]` on Windows. The temporary file backend79+ unlinked its file without closing it first, and Windows refuses to remove a80+ file the process still holds open, so the cleanup failure masked the real81+ exception. {issue}`3731` {pr}`3764`82+- The temporary file the pager writes to on Windows is opened with the encoding83+ {func}`get_pager_file` picked for the output stream, and with84+ `errors="replace"` to match the pipe backend. Any text stdout can encode85+ reaches the pager.86+- The temporary file pager backend forwards any parameters the user set in87+ `PAGER` to the pager command instead of silently dropping them. On Windows,88+ `PAGER="less -R"` now invokes `less -R` on the temporary file rather than89+ bare `less`. {pr}`3777`90+- Improve raw mode detection by parsing the option tokens. {issue}`3416`91+ {pr}`3777`92+- {func}`edit` accepts `os.PathLike` values for `filename`, in addition to93+ strings. {issue}`2869` {pr}`3781`94 95 ## Version 8.4.296 97 Released 2026-06-241561 unmodified linesmodified:pyproject.toml+2 added-2 removed
1 [project]2 name = "click"3-version = "8.5.0.dev"3+version = "8.5.0"4 description = "Composable command line interface toolkit"5 readme = "README.md"6 license = "BSD-3-Clause"7 license-files = ["LICENSE.txt"]61 unmodified lines69 [tool.flit.sdist]70 include = [71 "docs/",72 "tests/",73- "CHANGES.rst",73+ "CHANGES.md",74 "uv.lock"75 ]76 exclude = [77 "docs/_build/",154 unmodified linesmodified:uv.lock+1 added-1 removed
171 unmodified lines172 ]173 174 [[package]]175 name = "click"176-version = "8.5.0.dev0"176+version = "8.5.0"177 source = { editable = "." }178 179 [package.dev-dependencies]180 dev = [1481 unmodified lines