Skip to content
Myr

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

39 files+1366 added−424 removed

modified:.github/workflows/lock.yaml+1 added-1 removed
modified:.github/workflows/nightly.yaml+30 added-5 removed
modified:.github/workflows/pre-commit.yaml+4 added-6 removed
modified:.github/workflows/publish.yaml+5 added-8 removed
modified:.github/workflows/tests.yaml+7 added-9 removed
25 unmodified lines
26 - {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 typing
modified:.github/workflows/zizmor.yaml+2 added-2 removed
modified:docs/arguments.md+1 added-1 removed
8 unmodified lines
910* 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>`.1617Useful and often used kwargs are:
172 unmodified lines
modified:docs/contributing.md+3 added-2 removed
23 unmodified lines
24 ```shell-session25 $ tox r -e random26 ```2728- 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.3233## Code Style34
11 unmodified lines
modified:docs/documentation.md+2 added-2 removed
13 unmodified lines
14```{eval-rst}15.. click:example::1617 @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 lines
113114## Documenting Arguments115116{class}`click.argument` accepts an optional `help` parameter that is shown in117the ``Positional arguments`` section of the help page. You can still document117the `Positional arguments` section of the help page. You can still document118arguments in the command docstring, especially when you want to describe them119in the main help text by name.120121A brief example:
222 unmodified lines
modified:docs/faqs.md+45 added
35 unmodified lines
36#### Answer3738If you don't want Click to emulate (as best it can) unix expansion on Windows, pass windows_expand_args=False when calling the CLI.39Windows 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.4041### `UnicodeEncodeError` on Windows4243A Click CLI that uses Unicode characters in its help text or `echo` output can raise `UnicodeEncodeError`:4445```pytb46UnicodeEncodeError: 'charmap' codec can't encode character '\u2023' in position 62: character maps to <undefined>47```4849This 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.5051#### Answer5253Run 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.5455You 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.6061This 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/)).6263#### For library authors6465Click 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.6667But if your own CLI knows the environment it runs under, it can choose to degrade its output:6869```python70import sys7172encoding = getattr(sys.stdout, "encoding", "") or ""73ascii_only = not encoding.lower().startswith("utf")74```7576Note 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.7778| 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` |8384Do 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 lines
8384## Version Option8586{func}`version_option` adds a `--version` option which immediately prints the version number and exits the program.8788The 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 lines
45```{currentmodule} click.shell_completion6```78Click provides tab completion support for Bash (version 4.4 and up), Zsh, and Fish. It is possible to add support for9other shells too, and suggestions can be customized at multiple levels.8Click provides tab completion support for Bash (version 4.4 and up), Zsh, Fish, and PowerShell. It is possible to add9support for other shells too, and suggestions can be customized at multiple levels.1011Shell completion suggests command names, option names, and values for choice, file, and path parameter types. Options12are only listed if at least a dash has been entered. Hidden commands and options are not shown.13
262 unmodified lines
modified:docs/testing.md+45 added-27 removed
5 unmodified lines
67Click provides the {ref}`click.testing <testing>` module to help you invoke8command line applications and check their behavior.910These tools should only be used for testing since they change11the entire interpreter state for simplicity. They are not thread-safe!10```{warning}11These tools should only be used for testing since they change the entire12interpreter state for simplicity. They are not thread-safe: see13[Running tests in parallel](#running-tests-in-parallel) for the supported14way to run CLI tests concurrently.15```1617The examples use [pytest](https://docs.pytest.org/en/stable/) style tests.1819```{contents}
102 unmodified lines
122```123124## File System Isolation125122The {meth}`CliRunner.isolated_filesystem` context manager sets the current123working directory to a new, empty folder.126To test a command that reads or writes files, give each test its own127directory and pass absolute paths to the command. Pytest's128[`tmp_path`](https://docs.pytest.org/en/stable/how-to/tmp_path.html) fixture129provides a fresh directory per test; {class}`tempfile.TemporaryDirectory`130works without pytest.131132```{code-block} python133:caption: cat.py134
10 unmodified lines
145146from click.testing import CliRunner147from cat import cat148142def test_cat():143 runner = CliRunner()144 with runner.isolated_filesystem():145 with open('hello.txt', 'w') as f:146 f.write('Hello World!')149def test_cat(tmp_path):150 hello = tmp_path / 'hello.txt'151 hello.write_text('Hello World!')152153 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```158153Pass in a path to control where the temporary directory is created.154In this case, the directory will not be removed by Click. Its useful155to integrate with a framework like Pytest that manages temporary files.159Because the directory is unique to the test and the command receives an160absolute path, nothing leaks between tests and the working directory is never161changed.162157```{code-block} python158:caption: test_cat.py163### Running tests in parallel164160from click.testing import CliRunner161from cat import cat165Isolating the file system with pytest is thread-safe: each test, or each thread,166works in its own directory through absolute paths, with no shared state.167163def 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 several169pieces of process-global state into place (like `sys.stdout`, `sys.stderr`,170`sys.stdin`, etc). Two invocations active at the same time in one interpreter171overwrite each other's state, so the runner cannot be driven from several172threads at once.173169 result = runner.invoke(cat, ['hello.txt'])170 assert result.exit_code == 0171 assert result.output == 'Hello World!\n'174```{warning}175Do not parallelize CLI tests with threads. Use process-based isolation176instead, where each worker has its own interpreter and its own copy of those177globals. [pytest-xdist](https://pytest-xdist.readthedocs.io/) does this with178`pytest --numprocesses=auto`.179```180181Click's own test suite uses exactly this setup: the `tests-random` dependency182group and the `random` tox environment in183[`pyproject.toml`](https://github.com/pallets/click/blob/main/pyproject.toml)184run the suite under `pytest-randomly` and `pytest-xdist` to surface ordering185bugs and races.186187```{deprecated} 8.5.0188{meth}`CliRunner.isolated_filesystem` is deprecated and will be removed in189Click 9.0. Use a temporary directory with absolute paths, as shown above.190```191192## Input Streams193194The test wrapper can provide input data for the input stream (stdin). This is195very useful for testing prompts.
88 unmodified lines
modified:docs/upgrade-guides.md+1 added-1 removed
11 unmodified lines
1213### Deprecations1415For 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).1718### Removals with prior deprecation1920For 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 lines
modified:docs/utils.md+8 added-5 removed
54 unmodified lines
55The {func}`echo` function supports ANSI colors and styles. It will56automatically strip ANSI color codes if the stream is not connected to a57terminal.5859:::{admonition} Older Windows Support59```{admonition} Older Windows Support60:class: note6162Recent Windows 11 supports ANSI styling by default, in both Terminal and cmd.exe.63If you need to support color output on older versions of Windows, install62Recent versions of Windows 11 support ANSI styling by default, in both63Windows Terminal and cmd.exe. If you need to support color output on older64versions of Windows, install65[colorama](https://pypi.org/project/colorama/) and call `colorama.init()`.65:::66```6768For styling a string, the {func}`style` function can be used:6970```python
53 unmodified lines
124 for idx in range(50000):125 print(idx, file=pager)126```127127```{hint} Why print instead of echo?128```{admonition} Why print() instead of echo()?129:class: hint130131The pager object deals with ANSI color and style codes itself: they are kept or132stripped depending on what the pager supports, exactly as {func}`echo` would do.133Any code that writes to a file, including plain {func}`print`, can therefore be134used with it.
255 unmodified lines
modified:src/click/_compat.py+2 added-2 removed
504 unmodified lines
505 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 color514515516# double check is needed so mypy does not analyze this on Linux516# Double check is needed so mypy does not analyze this on Linux.517if sys.platform.startswith("win") and WIN:518 from ._winconsole import _get_windows_console_stream519520 def _get_argv_encoding() -> str:
70 unmodified lines
modified:src/click/_termui_impl.py+172 added-145 removed
6 unmodified lines
7from __future__ import annotations89import collections.abc as cabc10import contextlib11import io11import math12import os13import shlex14import sys
11 unmodified lines
26from ._compat import strip_ansi27from ._compat import term_len28from ._compat import WIN29from .exceptions import ClickException31from .utils import _KeepOpenFile30from .utils import echo3132V = t.TypeVar("V")333437class _BufferedTextPagerStream(t.Protocol):38 buffer: t.BinaryIO394041def _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 None474835if os.name == "nt":36 BEFORE_BAR = "\r"37 AFTER_BAR = "\n"38else:
100 unmodified lines
139 # twice works and does "what you want".140 return next(iter(self))141142 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()150151 if self.hidden or not self._is_atty:152 return153 self.file.write(AFTER_BAR)154 self.file.flush()
224 unmodified lines
379 self.finish()380 self.render_progress()381382389class MaybeStripAnsi(io.TextIOWrapper):390 def __init__(self, stream: t.IO[bytes], *, color: bool, **kwargs: t.Any):391 super().__init__(stream, **kwargs)383class _PagerWriter:384 """Wrap a pager's output stream to strip ANSI styling when colors are385 disabled.386387 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.391392 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 """396397 def __init__(self, stream: t.TextIO, color: bool) -> None:398 self._stream = stream399 self.color = color400401 def write(self, text: str) -> int:402 if not self.color:403 text = strip_ansi(text)397 return super().write(text)404405 return self._stream.write(text)406407 def writelines(self, lines: cabc.Iterable[str]) -> None:408 for line in lines:409 self.write(line)410411 def flush(self) -> None:412 self._stream.flush()413414 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()418419 def __getattr__(self, name: str) -> t.Any:420 return getattr(self._stream, name)421422423def _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.425426 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-constructor429430 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 None435436 import shutil437438 cmd_filepath = shutil.which(cmd_parts[0])439440 if not cmd_filepath:441 return None442443 # 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:]449450451def _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()456457 # There are no standard streams attached to write to. For example,
8 unmodified lines
466 # 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", ""))470471 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)478424 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"]481482 resolved = _resolve_pager_command(pager_cmd_parts)483484 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)487488 cmd_path, cmd_params = resolved489490 if use_tempfile:491 return _tempfilepager(cmd_path, cmd_params, color)492493 return _pipepager(cmd_path, cmd_params, color)494495496@contextlib.contextmanager497def get_pager_file(color: bool | None = None) -> t.Generator[t.TextIO, None, None]:498 """Context manager.499
3 unmodified lines
503504 :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()518519520def _less_uses_raw_mode(less_env: str, cmd_params: list[str]) -> bool:521 """Detect a raw-control-characters request in a ``less`` invocation.522523 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_params536537 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 True544545 return False546547548@contextlib.contextmanager549def _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.553475 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.555556 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 return492493 import shutil494495 cmd = cmd_parts[0]496 cmd_params = cmd_parts[1:]497498 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 return506507 # 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.name512560 import subprocess561562 # Make a local copy of the environment to not affect the global one.563 env = dict(os.environ)564565 # 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()577578 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 = True585528 if color is None:529 color = False530586 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 lines
633634635@contextlib.contextmanager636def _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.640641 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 return598599 import shutil646 import subprocess601602 cmd = cmd_parts[0]603604 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 return612613 # 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()617647 import tempfile648649 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)668669670@contextlib.contextmanager671def _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.675644 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, color681650 if color is None:651 color = False682653 yield _KeepOpenFile(stream), encoding, color # type: ignore[misc]654655683class Editor:684 def __init__(685 self,686 editor: str | None = None,
22 unmodified lines
709 if which(editor) is not None:710 return editor711 return "vi"712686 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 lines
modified:src/click/core.py+12 added-5 removed
1173 unmodified lines
11741175 return rv11761177 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.11791180 Drops duplicates and names already reserved by another parameter. Order of1181 :attr:`Context.help_option_names` is preserved, so the result is stable.11821183 .. 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)11911192 def get_help_option(self, ctx: Context) -> Option | None:1193 """Returns the help option object.
2474 unmodified lines
3668 All parameters are passed onwards to the constructor of :class:`Parameter`.36693670 :param help: the help string.36713665 .. versionchanged:: 8.53672 .. versionchanged:: 8.5.03673 Added the ``help`` parameter.3674 """36753676 param_type_name = "argument"
123 unmodified lines
modified:src/click/shell_completion.py+2 added-2 removed
519 unmodified lines
520521class PowerShellComplete(ShellComplete):522 """Shell completion for PowerShell (Windows PowerShell 5.1+ and pwsh 7+).523524 .. versionadded:: 8.5524 .. versionadded:: 8.5.0525 """526527 name: t.ClassVar[str] = "powershell"528 source_template: t.ClassVar[str] = _SOURCE_POWERSHELL
93 unmodified lines
622623 lex = shlex.shlex(string, posix=True)624 lex.whitespace_split = True625 lex.commenters = ""626 out = [] # type: list[str]626 out: list[str] = []627628 try:629 out.extend(lex)630 except ValueError:
171 unmodified lines
modified:src/click/termui.py+79 added-25 removed
2 unmodified lines
3import collections.abc as cabc4import inspect5import io6import itertools7import os8import re9import sys10import typing as t11from contextlib import AbstractContextManager
96 unmodified lines
108def _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}"126127125def _format_default(default: t.Any) -> t.Any:126 if isinstance(default, (io.IOBase, _LazyFile)) and hasattr(default, "name"):127 return default.name128def _format_default(default: V) -> V | str:129 if isinstance(default, (io.IOBase, _LazyFile)):130 name = getattr(default, "name", None)131132 if name is not None:133 return str(name)134135 return default136137138@t.overload139def 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: ...151152153@t.overload154def 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: ...166167168def 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.182183 If the user aborts the input by sending an interrupt signal, this
21 unmodified lines
205 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): ".208209 .. 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.213214 .. 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 lines
262 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 lines
712 :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.715672 .. 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.719720 .. versionchanged:: 8.0721 A non-string ``message`` is converted to a string.722
114 unmodified lines
837 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: ...846847848def edit(
1 unmodified line
850 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 overrides
18 unmodified lines
880 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.890891 .. 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.894895 .. versionchanged:: 8.5.0896 ``filename`` accepts ``os.PathLike`` values in addition to strings.897898 """899 from ._termui_impl import Editor900901 ed = Editor(editor=editor, env=env, require_save=require_save, extension=extension)902903 if filename is None:904 return ed.edit(text)905852 if isinstance(filename, str):906 if isinstance(filename, (str, os.PathLike)):907 filename = (filename,)908909 ed.edit_files(filenames=filename)910 return None
104 unmodified lines
modified:src/click/testing.py+26 added
745 unmodified lines
746 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.749750 .. 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`.760761 :param temp_dir: Create the temporary directory under this762 directory. If given, the created directory is not removed763 when exiting.764765 .. 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.769770 .. versionchanged:: 8.0771 Added the ``temp_dir`` parameter.772 """773 import warnings774775 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 )782783 cwd = os.getcwd()784 dt = tempfile.mkdtemp(dir=temp_dir)785 os.chdir(dt)786
12 unmodified lines
modified:src/click/types.py+50 added-3 removed
28 unmodified lines
29_ValueT = t.TypeVar("_ValueT")30_ValueT_contra = t.TypeVar("_ValueT_contra", contravariant=True)31_ValueT_co = t.TypeVar("_ValueT_co", covariant=True)3233# 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.38if t.TYPE_CHECKING:39 _InputT_contra = te.TypeVar("_InputT_contra", contravariant=True, default=t.Any)40elif sys.version_info >= (3, 13):41 _InputT_contra = t.TypeVar("_InputT_contra", contravariant=True, default=t.Any)42else:43 _InputT_contra = t.TypeVar("_InputT_contra", contravariant=True)4445_FloatValueT = t.TypeVar("_FloatValueT", bound=float)46_FloatValueT_co = t.TypeVar("_FloatValueT_co", bound=float, covariant=True)4748
1 unmodified line
50 param_type: str51 name: str525342class ParamType(t.Generic[_ValueT_co], abc.ABC):54class 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.5758 To implement a custom type, subclass and implement at least the
13 unmodified lines
72 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.7677 .. 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 """8283 is_composite: t.ClassVar[bool] = False84 arity: int = 1 # read-only
8 unmodified lines
93 #: are split by ``os.path.pathsep`` by default (":" on Unix and ";" on94 #: Windows).95 envvar_list_splitter: t.ClassVar[str | None] = None9697 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]110111 def to_info_dict(self) -> ParamTypeInfoDict:112 """Gather information that could be useful for a tool generating113 user-facing documentation.114
13 unmodified lines
128 name = param_type129130 return {"param_type": param_type, "name": name}131132 @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: ...139140 @t.overload141 def __call__(142 self,143 value: _InputT_contra,144 param: Parameter | None = None,145 ctx: Context | None = None,146 ) -> _ValueT_co: ...147148 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 None
8 unmodified lines
165 .. versionadded:: 2.0166 """167168 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 lines
modified:src/click/utils.py+1 added-1 removed
277 unmodified lines
278 :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.281282 .. versionchanged:: 8.5282 .. versionchanged:: 8.5.0283 Colorama is no longer used for color on Windows.284285 .. versionchanged:: 6.0286 Support Unicode output on the Windows console. Click does not
402 unmodified lines
modified:tests/test_utils/test_echo_via_pager.py+3 added-3 removed
195 unmodified lines
196 the pager stream before propagating the exception.197198 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)205206 writes: list[str] = []207 real_write = click._termui_impl.MaybeStripAnsi.write207 real_write = click._termui_impl._PagerWriter.write208209 def spy(self, text):210 writes.append(text)211 return real_write(self, text)212213 monkeypatch.setattr(click._termui_impl.MaybeStripAnsi, "write", spy)213 monkeypatch.setattr(click._termui_impl._PagerWriter, "write", spy)214215 pager_out_tmp = tmp_path / "pager_out.txt"216 with (217 pager_out_tmp.open("w") as f,
42 unmodified lines
modified:tests/test_utils/test_open_file.py+50 added-55 removed
6 unmodified lines
7import click8from click._compat import WIN91011def test_open_file(runner):11def 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())1718 click.echo("meep")1920 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")2224 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"2628 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"303132def test_open_file_pathlib_dash(runner):33 @click.command()
21 unmodified lines
55 result = runner.invoke(cli, ["-"], input=os.urandom(16))56 assert result.exception is None575860def test_open_file_respects_ignore(runner):61 with runner.isolated_filesystem():62 with open("test.txt", "w") as f:63 f.write("Hello world!")59def test_open_file_respects_ignore(tmp_path):60 path = tmp_path / "test.txt"61 path.write_text("Hello world!")6265 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"656669def 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")67def test_open_file_ignore_invalid_utf8(tmp_path):68 path = tmp_path / "test.txt"69 path.write_bytes(b"\xe2\x28\xa1")7074 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()737478def 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))75def test_open_file_ignore_no_encoding(tmp_path):76 path = tmp_path / "test.bin"77 path.write_bytes(os.urandom(16))7883 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()818283@pytest.mark.skipif(WIN, reason="os.chmod() is not fully supported on Windows.")84@pytest.mark.parametrize("permissions", [0o400, 0o444, 0o600, 0o644])89def 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)85def 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)8995 @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()94100 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) == permissions9899100@pytest.mark.skipif(WIN, reason="os.stat() is not fully supported on Windows.")106def test_open_file_atomic_permissions_new_file(runner):107 with runner.isolated_filesystem():101def 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()106109 @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)113114 # 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)119120 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) == permissions
modified:tests/test_utils/test_prompt.py+26 added
12 unmodified lines
13 capfd.readouterr()14 assert isinstance(value, int)151617def 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."""2122 class DoublingType(click.ParamType[int]):23 name = "doubling"2425 def convert(self, value, param, ctx):26 return int(value) * 22728 monkeypatch.setattr(sys, "stdin", StringIO("\n"))29 value = click.prompt("value", default=5, type=DoublingType())30 capfd.readouterr()31 assert value == 10323334def 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 == 7414243@pytest.mark.skipif(WIN, reason="Different behavior on windows.")44def test_prompts_abort(monkeypatch, capsys):45 def f(_):46 raise KeyboardInterrupt()
54 unmodified lines
added:tests/typing/typing_edit.py+10 added
1from pathlib import Path23from typing_extensions import assert_type45import click67# ``filename`` accepts a path or an iterable of paths.8assert_type(click.edit(filename="f.txt"), None)9assert_type(click.edit(filename=Path("f.txt")), None)10assert_type(click.edit(filename=["f.txt", Path("g.txt")]), None)
added:tests/typing/typing_prompt.py+50 added
1from typing_extensions import assert_type23import click45# Without ``type``, ``value_proc``, or a non-``str`` ``default``, the raw6# string input is returned.7assert_type(click.prompt("Name"), str)8assert_type(click.prompt("Name", default="bob"), str)910# 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.12assert_type(click.prompt("Age", type=click.INT), int)13assert_type(click.prompt("Age", type=click.IntRange(0, 130), default=18), int)14assert_type(click.prompt("Age", type=int), int)15assert_type(click.prompt("Age", type=int, default="100"), int)1617# The return type is narrowed by the ``value_proc`` argument.181920def to_float(value: str) -> float:21 return float(value)222324assert_type(click.prompt("Ratio", value_proc=to_float), float)2526# The return type is narrowed by the ``default`` argument alone.27assert_type(click.prompt("Age", default=18), int)282930# A custom type may declare both its converted value and accepted input31# types. Omitting the input type parameter defaults it to ``Any``.32class DoublingType(click.ParamType[int, str]):33 name = "doubling"3435 def convert(36 self, value: str, param: click.Parameter | None, ctx: click.Context | None37 ) -> int:38 return int(value) * 2394041assert_type(click.prompt("Num", type=DoublingType()), int)42assert_type(DoublingType()("21"), int)43assert_type(DoublingType()(None), None)444546class SimpleType(click.ParamType[int]):47 name = "simple"484950assert_type(SimpleType()("21"), int)
modified:tests/test_arguments.py+16 added-19 removed
100 unmodified lines
101 catch_exceptions=False,102 )103104105def test_file_args(runner):105def 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 lines
112 if not chunk:113 break114 output.write(chunk)115116 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!"121123 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 == 0125126127def test_path_allow_dash(runner):128 @click.command()
5 unmodified lines
134 assert result.output == "-\n"135 assert result.exit_code == 0136137139def test_file_atomics(runner):138def 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 line
144 with open(output.name, "rb") as f:145 old_content = f.read()146 assert old_content == b"OLD\n"147149 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"154155156def test_stdout_default(runner):157 @click.command()
583 unmodified lines
modified:tests/test_basic.py+38 added-40 removed
413 unmodified lines
414 result = runner.invoke(cli, args)415 assert result.output == repr(expected)416417418def test_file_option(runner):418def 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 lines
425 @click.option("--file", type=click.File("r"))426 def output(file):427 click.echo(file.read())428429 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}"])432433 assert not result_in.exception434 assert result_in.output == ""435 assert not result_out.exception436 assert result_out.output == "Hello World!\n\n"437438439def test_file_lazy_mode(runner):439def test_file_lazy_mode(runner, tmp_path):440 do_io = False441442 @click.command()443 @click.option("--file", type=click.File("w"))
5 unmodified lines
449 @click.option("--file", type=click.File("r"))450 def output(file):451 pass452453 with runner.isolated_filesystem():454 os.mkdir("example.txt")453 example = tmp_path / "example.txt"454 example.mkdir()455456 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 == 1459460 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 == 0463464 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.exception466467 @click.command()468 @click.option("--file", type=click.File("w", lazy=False))469 def input_non_lazy(file):470 file.write("Hello World!\n")471472 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.output477478479def test_path_option(runner):479def 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")485486 with runner.isolated_filesystem():487 os.mkdir("test")486 test_dir = tmp_path / "test"487 test_dir.mkdir()488489 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.exception491492 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"494495 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.output497498 @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)}")503504 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.output506508 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.output510511 @click.command()512 @click.option("-f", type=click.Path())513 def exists(f):514 click.echo(f"exists={os.path.exists(f)}")515517 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.output518521 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.output521522523def test_choice_option(runner):524 @click.command()
438 unmodified lines
modified:tests/test_commands.py+50 added
417 unmodified lines
418 == expected_params419 )420421422@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)462def test_get_help_option_names(help_option_names, params, expected):463 """Check help option names are deduplicated but keep stable order.464465 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) == expected470471472def 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 lines
modified:tests/test_deprecations.py+63 added-15 removed
1import importlib.metadata23import pytest45import click6import click.core7import click.parser8import click.shell_completion9import click.utils10116@pytest.mark.parametrize("module", [click, click.utils], ids=["click", "click.utils"])7@pytest.mark.parametrize("name", ["get_binary_stream", "get_text_stream"])8def test_stream_helper_deprecated(module, name):9 with pytest.warns(DeprecationWarning, match=name):10 getattr(module, name)111212@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)23def test_utilities_deprecated(name):46def test_attr_deprecated(module, name, target):47 with pytest.warns(DeprecationWarning, match=name):25 getattr(click.utils, name)48 value = getattr(module, name)4950 assert value == target515253@pytest.mark.parametrize(54 "module",55 [click, click.core, click.parser, click.utils],56 ids=lambda m: m.__name__,57)58def test_unknown_attribute_raises(module):59 with pytest.raises(AttributeError, match="no_such_attribute"):60 _ = module.no_such_attribute616263def test_context_protected_args_deprecated():64 ctx = click.Context(click.Command("cli"))6566 with pytest.warns(DeprecationWarning, match="protected_args"):67 assert ctx.protected_args == []686970def test_isolated_filesystem_deprecated(runner):71 with pytest.warns(DeprecationWarning, match="isolated_filesystem"):72 with runner.isolated_filesystem():73 pass
modified:tests/test_shell_completion.py+18 added-19 removed
572 unmodified lines
573 assert click.shell_completion._available_shells["mysh"] is MyshComplete574575576# Don't make the ResourceWarning give an error577@pytest.mark.filterwarnings("default")578def 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")578def 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")582584 @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 pass592594 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"597598599def test_fish_format_completion_escapes_help():600 fc = FishComplete(Command("x"), {}, "x", "_X_COMPLETE")
17 unmodified lines
modified:tests/test_termui.py+383 added-11 removed
1import contextlib2import gc3import io4import os5import pathlib6import platform7import shlex8import shutil9import subprocess10import sys11import tempfile12import time13from unittest.mock import patch
94 unmodified lines
108 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)109 assert runner.invoke(cli, []).output == ""110111112@pytest.mark.parametrize("update_min_steps", [1, 2, 3, 7, 20, 25])113@pytest.mark.parametrize("drive", ["iterate", "update"])114def test_progressbar_lands_on_final_position(monkeypatch, update_min_steps, drive):115 """The bar reaches its total whatever the ``update_min_steps`` threshold.116117 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()124125 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)137138 assert bar.pos == 20139 assert bar.finished140 assert "20/20" in stream.getvalue()141142143@pytest.mark.parametrize("avg, expected", [([], 0.0), ([1, 4], 2.5)])144def test_progressbar_time_per_iteration(runner, avg, expected):145 with _create_progress(2, avg=avg) as progress:146 assert progress.time_per_iteration == expected
273 unmodified lines
420 with pytest.raises(exc):421 click.getchar()422423390@pytest.mark.skipif(platform.system() == "Windows", reason="No sed on Windows.")424@pytest.mark.skipif(WIN, reason="No sed on Windows.")425def test_fast_edit(runner):426 result = click.edit("a\nb", editor="sed -i~ 's/$/Test/'")427 assert result == "aTest\nbTest\n"428429396@pytest.mark.skipif(platform.system() == "Windows", reason="No sed on Windows.")430@pytest.mark.skipif(WIN, reason="No sed on Windows.")431def 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 lines
447 # terminated by newline too.448 assert reopened_file.read() == "aTest\nbTest\n"449450451@pytest.mark.skipif(WIN, reason="No sed on Windows.")452@pytest.mark.parametrize("use_iterable", [False, True], ids=["single", "iterable"])453def 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_path458459 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"462463464@pytest.mark.parametrize(465 ("editor_cmd", "filenames", "expected_args"),466 [467 pytest.param(
305 unmodified lines
773 assert err == ""774 assert out == expected775776777@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)787def 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)797798 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)801802 with click.get_pager_file() as pager:803 assert pager.color is expected_color804805806@pytest.mark.skipif(WIN, reason="The fake pager is a shell script.")807def 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.810811 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)817818 monkeypatch.setattr(click._termui_impl, "WIN", True)819 monkeypatch.delitem(click._termui_impl.os.environ, "LESS", raising=False)820821 with click._termui_impl._pipepager(fake_pager, []) as (_, color):822 assert color is True823824825class _FakePagerProcess:826 """Stand-in for :class:`subprocess.Popen` recording argv and env without827 launching a process."""828829 def __init__(self, argv, *, env=None, **kwargs):830 self.argv = argv831 self.env = env832 self.returncode = 0833 self.stdin = io.StringIO()834835 def terminate(self):836 pass837838 def wait(self):839 return 0840841842@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)891def 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)904905 processes: list[_FakePagerProcess] = []906907 def fake_popen(*args, **kwargs):908 process = _FakePagerProcess(*args, **kwargs)909 processes.append(process)910 return process911912 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")916917 with click._termui_impl._pipepager(cmd_path, cmd_parts[1:]) as (_, color):918 pass919920 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_less926927928def 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 lines
1069)1070def 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"10761077 with pager_out.open("w", encoding="utf-8") as text_stream:1078 monkeypatch.setattr(
9 unmodified lines
1088 assert pager_out.read_text(encoding="utf-8") == expected108910901091def 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."""10931094 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)1098900 styled_text = click.style("hello", fg="red")9011099 with click.get_pager_file(color=False) as pager:903 pager.write(styled_text)1100 pager.write(click.style("hello", fg="red"))11011102 # 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"110611071108def test_get_pager_file_flushes_stream_on_exception(monkeypatch):1109 """Exceptions should still flush the yielded stream in ``finally``."""11101111 class FlushableTextStream(io.StringIO):1112 def __init__(self):1113 super().__init__()915 self.color = None1114 self.flush_calls = 011151116 def flush(self):1117 self.flush_calls += 1
1 unmodified line
1119 stream = FlushableTextStream()11201121 @contextlib.contextmanager1122 def pager_contextmanager(color=None):925 yield stream, "utf-8", color1123 yield stream, False11241125 monkeypatch.setattr(1126 click._termui_impl, "_pager_contextmanager", pager_contextmanager1127 )11281129 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")11331134 assert stream.flush_calls == 11135 assert stream.getvalue() == "partial"113611371138def test_get_pager_file_close_does_not_close_borrowed_stream(monkeypatch):1139 """Closing the yielded pager must not close a stream the caller owns.11401141 ``_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.11451146 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 )11601161 with click.get_pager_file() as pager:1162 pager.write("hello\n")1163 pager.close()1164 assert not stream.closed11651166 assert not stream.closed1167 assert stream.getvalue() == "hello\n"116811691170def _force_tempfile_pager(monkeypatch, pager_cmd="cat"):1171 """Route ``get_pager_file`` through the ``_tempfilepager`` backend.11721173 That backend is only reachable on Windows, so the platform flag and the tty1174 probes are faked to exercise it from any runner.11751176 ``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)118711881189def _page_with_get_pager_file():1190 with click.get_pager_file() as pager:1191 pager.write("hello\n")119211931194def _page_with_echo_via_pager():1195 click.echo_via_pager("hello")119611971198@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)1206def test_tempfile_pager_accepts_text(monkeypatch, capfd, page):1207 """The temp file backend must yield a text stream (issues #3731, #3740).12081209 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)12141215 page()12161217 out, err = capfd.readouterr()1218 assert err == ""1219 assert out.replace("\r\n", "\n") == "hello\n"122012211222@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)1230def test_tempfile_pager_handles_ansi(monkeypatch, capfd, color, expected):1231 """The temp file backend honors ``color`` like the pipe backend does.12321233 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)12371238 click.echo_via_pager(click.style("hello", fg="red"), color=color)12391240 out, err = capfd.readouterr()1241 assert err == ""1242 assert out.replace("\r\n", "\n") == expected124312441245@pytest.mark.skipif(shutil.which("head") is None, reason="head not available")1246def test_tempfile_pager_passes_pager_params(monkeypatch, capfd):1247 """The temp file backend forwards ``PAGER`` parameters to the command.12481249 ``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")12531254 click.echo_via_pager("line one\nline two\n")12551256 out, err = capfd.readouterr()1257 assert err == ""1258 assert out.replace("\r\n", "\n") == "line one\n"125912601261@pytest.mark.skipif(shutil.which("cat") is None, reason="cat not available")1262def test_tempfile_pager_closes_file_before_unlink(monkeypatch):1263 """An error while paging must not leave the temp file open at unlink time.12641265 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)12721273 temp_files = []1274 real_named_temporary_file = tempfile.NamedTemporaryFile12751276 def record(*args, **kwargs):1277 f = real_named_temporary_file(*args, **kwargs)1278 temp_files.append(f)1279 return f12801281 monkeypatch.setattr(tempfile, "NamedTemporaryFile", record)12821283 closed_at_unlink = []1284 real_unlink = os.unlink12851286 def spy_unlink(path, **kwargs):1287 closed_at_unlink.append([f.closed for f in temp_files])1288 return real_unlink(path, **kwargs)12891290 monkeypatch.setattr(os, "unlink", spy_unlink)12911292 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()13031304 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 )130913101311def 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 lines
modified:tests/test_testing.py+79 added
438 unmodified lines
439 result = runner.invoke(cli, ["-"])440 assert result.output == "<stdin>\nr"441442443@pytest.mark.filterwarnings("ignore:'isolated_filesystem':DeprecationWarning")444def test_isolated_runner(runner):445 with runner.isolated_filesystem() as d:446 assert os.path.exists(d)447448 assert not os.path.exists(d)449450451@pytest.mark.filterwarnings("ignore:'isolated_filesystem':DeprecationWarning")452def 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)455456 assert os.path.exists(d)457 os.rmdir(d)458459460def test_tempdir_replacement_pattern(runner, tmp_path):461 """The replacement for ``isolated_filesystem()``: a temp dir and absolute paths.462463 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 """467468 @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")473474 target = tmp_path / "marker.txt"475 result = runner.invoke(write_marker, [str(target)])476477 assert result.exit_code == 0478 assert target.read_text() == "written"479480481def test_tempdir_isolation_is_thread_safe():482 """The recommended replacement is thread-safe, unlike ``isolated_filesystem()``.483484 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).487488 ``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 threading495496 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()501502 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 )519520 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)525526 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 )535536537def test_isolation_stderr_errors():538 """Writing to stderr should escape invalid characters instead of539 raising a UnicodeEncodeError.540 """
300 unmodified lines
modified:tests/test_types.py+22 added
2 unmodified lines
3import platform4import subprocess5import sys6import tempfile7import typing as t89import pytest1011import click
296 unmodified lines
308def 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'."312313314def 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)321322323def test_param_type_subclass_omitting_input_parameter():324 class DoublingType(click.ParamType[int]):325 name = "doubling"326327 def convert(self, value, param, ctx):328 return int(value) * 2329330 doubling = DoublingType()331 assert doubling("21") == 42332 assert doubling(None) is None
modified:CHANGES.md+53 added-5 removed
1## Version 8.5.023Unreleased3Released 2026-08-2445- 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 line
14 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's
1 unmodified line
33 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`9495## Version 8.4.29697Released 2026-06-24
1561 unmodified lines
modified:pyproject.toml+2 added-2 removed
1[project]2name = "click"3version = "8.5.0.dev"3version = "8.5.0"4description = "Composable command line interface toolkit"5readme = "README.md"6license = "BSD-3-Clause"7license-files = ["LICENSE.txt"]
61 unmodified lines
69[tool.flit.sdist]70include = [71 "docs/",72 "tests/",73 "CHANGES.rst",73 "CHANGES.md",74 "uv.lock"75]76exclude = [77 "docs/_build/",
154 unmodified lines
modified:uv.lock+1 added-1 removed
171 unmodified lines
172]173174[[package]]175name = "click"176version = "8.5.0.dev0"176version = "8.5.0"177source = { editable = "." }178179[package.dev-dependencies]180dev = [
1481 unmodified lines