Merge `stable` into `main` after `CHANGES` rST to Markdown conversion (#3563)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Divergence were introduced while migrating `CHANGES.rst` to `CHANGES.md` in #3559 (`stable`) and #3560 (`main`).
authored by Kevin Deldycke · committed by GitHub · parents 4fc0e90, 1ca1cea · Browse files · 17 files·+549 added−180 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
17 files+549 added−180 removed
- tests:+186 added−12 removed
- other:+363 added−168 removed
Provenance
- Commit
8a1b1a3- Tree
d07b856- Author
Kevin Deldycke <kdeldycke@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent 1
4fc0e90- Parent 2
1ca1cea
17 files changed+549 added−180 removed
modified:.github/workflows/nightly.yaml+7 added-5 removed
7 unmodified lines89101112131213141516171718192021227 unmodified lines30313233343536373839403941424342447 unmodified lines group: ${{ github.workflow }} cancel-in-progress: falsejobs: race-tests: name: ${{ matrix.name }} runs-on: ${{ matrix.os || 'ubuntu-latest' }} name: ${{ matrix.config.name }} (${{ matrix.branch }}) runs-on: ${{ matrix.config.os || 'ubuntu-latest' }} strategy: fail-fast: false matrix: include: branch: [main, stable] config: - {name: Random 3.14, python: '3.14', tox: random} - {name: Random 3.14t, python: '3.14t', tox: random} - {name: Random 3.13, python: '3.13', tox: random} - {name: Random 3.12, python: '3.12', tox: random}7 unmodified lines steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: persist-credentials: false ref: ${{ matrix.branch }} - uses: astral-sh/setup-uv@cec208311dfd045dd5311c1add060b2062131d57 # v8.0.0 with: enable-cache: true prune-cache: false - uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 with: python-version: ${{ matrix.python }} python-version: ${{ matrix.config.python }} - run: uv run --locked --no-default-groups --group dev tox run env: TOX_ENV: ${{ matrix.tox }} TOX_ENV: ${{ matrix.config.tox }}modified:docs/conf.py+1 added
29 unmodified lines30 }31 intersphinx_mapping = {32 "python": ("https://docs.python.org/3/", None),33 }34+myst_enable_extensions = ["attrs_block"]35 myst_heading_anchors = 336 37 # HTML -----------------------------------------------------------------38 21 unmodified linesmodified:docs/index.md+2 added-1 removed
1123456147 unmodified linesExpand all#{.hide-header}# Welcome to Click
```{image} _static/click-name.svg:align: center:height: 200px147 unmodified linesExpand allmodified:docs/parameters.md+1 added-1 removed
17 unmodified lines18 - Can be pulled from environment variables.19 20 ## Arguments21 22-- Are optional with in reason, but not entirely so.22+- Are optional within reason, but not entirely so.23 - Recommended to use for subcommands, urls, or files.24 - Can take an arbitrary number of arguments.25 - Are not fully documented by the help page since they may be too specific to be automatically documented. For more see {ref}`documenting-arguments`.26 - Can be pulled from environment variables but only explicitly named ones. For more see {ref}`environment-variables`.29 unmodified linesmodified:src/click/_compat.py-1 removed
10 unmodified lines11 from weakref import WeakKeyDictionary12 13 CYGWIN = sys.platform.startswith("cygwin")14 WIN = sys.platform.startswith("win")15-MAC = sys.platform == "darwin"15 _ansi_re = re.compile(r"\033\[[;?0-9]*[a-zA-Z]")16 17 18 def _make_text_stream(568 unmodified linesmodified:src/click/_termui_impl.py+44 added-28 removed
27 unmodified lines28 from ._compat import term_len29 from ._compat import WIN30 from .exceptions import ClickException31 from .utils import echo32+from .utils import KeepOpenFile33 34 V = t.TypeVar("V")35 36 393 unmodified lines430 431 @contextlib.contextmanager432 def get_pager_file(color: bool | None = None) -> t.Generator[t.TextIO, None, None]:433 """Context manager.434+435 Yields a writable file-like object which can be used as an output pager.436+434- .. versionadded:: 8.4437+ .. versionadded:: 8.4.0438+439 :param color: controls if the pager supports ANSI colors or not. The440 default is autodetection.441 """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,441- # while text-only streams are yielded as-is.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.444- stream = MaybeStripAnsi(stream.buffer, color=color, encoding=encoding)445- elif isinstance(stream, t.BinaryIO):446- # Binary stream447- stream = MaybeStripAnsi(stream, color=color, encoding=encoding)449+ wrapper = MaybeStripAnsi(stream.buffer, color=color, encoding=encoding)450+ stream = wrapper451 try:449- yield stream452+ # Narrow the BinaryIO | TextIO union that _pager_contextmanager453+ # yields; the caller writes text to the pager.454+ yield t.cast(t.TextIO, stream)455 finally:456+ try:451- stream.flush()457+ stream.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()467 468 469 @contextlib.contextmanager470 def _pipepager(11 unmodified lines482 automatically.483 """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()472- yield stdout, "utf-8", False489+ with _nullpager(stdout, color) as rv:490+ yield rv491 return492 493 import shutil494 1 unmodified line496 cmd_params = cmd_parts[1:]497 498 cmd_filepath = shutil.which(cmd)499 if not cmd_filepath:500+ # No usable pager: fall back to stdout through _nullpager so it gets the501+ # same borrowed-stream handling and the caller's stream is not closed.502 stdout = _default_text_stdout() or StringIO()483- yield stdout, "utf-8", False503+ with _nullpager(stdout, color) as rv:504+ yield rv505 return506 507 # Produces a normalized absolute path string.508 # multi-call binaries such as busybox derive their identity from the symlink79 unmodified lines588 :func:`shutil.which`.589 """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()572- yield stdout, "utf-8", False595+ with _nullpager(stdout, color) as rv:596+ yield rv597 return598 599 import shutil600 import subprocess1 unmodified line602 cmd = cmd_parts[0]603 604 cmd_filepath = shutil.which(cmd)605 if not cmd_filepath:606+ # No usable pager: fall back to stdout through _nullpager so it gets the607+ # same borrowed-stream handling and the caller's stream is not closed.608 stdout = _default_text_stdout() or StringIO()583- yield stdout, "utf-8", False609+ with _nullpager(stdout, color) as rv:610+ yield rv611 return612 613 # Produces a normalized absolute path string.614 # multi-call binaries such as busybox derive their identity from the symlink17 unmodified lines632 finally:633 os.unlink(f.name)634 635 609-class _SkipClose:610- def __init__(self, stream: t.IO[t.Any]) -> None:611- self.stream = stream612-613- def __getattr__(self, name: str) -> t.Any:614- return getattr(self.stream, name)615-616- @property617- def buffer(self) -> t.BinaryIO:618- return _SkipClose(self.stream.buffer) # type: ignore[attr-defined, return-value]619-620- def close(self) -> None:621- pass622-623-636 @contextlib.contextmanager637 def _nullpager(638 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.643+644+ The stream is wrapped in :class:`~click.utils.KeepOpenFile` so that, as a645+ borrowed stream, it is not closed by a ``with`` block. The wrapper that646+ :func:`get_pager_file` builds around it is detached rather than closed.647 """648 encoding = get_best_encoding(stream)649 650 if color is None:651 color = False652 637- yield _SkipClose(stream), encoding, color # type: ignore[misc]653+ yield KeepOpenFile(stream), encoding, color # type: ignore[misc]654 655 656 class Editor:657 def __init__(288 unmodified linesmodified:src/click/core.py+124 added-40 removed
46 unmodified lines47 from .utils import make_str48 from .utils import PacifyFlushWrapper49 50 if t.TYPE_CHECKING:51+ from typing_extensions import Self52+53 from .shell_completion import CompletionItem54 55 F = t.TypeVar("F", bound="t.Callable[..., t.Any]")56 V = t.TypeVar("V")61 unmodified lines118 119 @contextmanager120 def augment_usage_errors(121 ctx: Context, param: Parameter | None = None120-) -> cabc.Iterator[None]:122+) -> cabc.Generator[None]:123 """Context manager that attaches extra information to exceptions."""124 try:125 yield126 except BadParameter as e:177 unmodified lines304 #:305 #: .. versionadded:: 8.0306 formatter_class: type[HelpFormatter] = HelpFormatter307 308+ parent: Context | None309+ command: Command310+ info_name: str | None311+ params: dict[str, t.Any]312+ args: list[str]313+ _protected_args: list[str]314+ _opt_prefixes: set[str]315+ obj: t.Any316+ _meta: dict[str, t.Any]317+ default_map: cabc.MutableMapping[str, t.Any] | None318+ invoked_subcommand: str | None319+ terminal_width: int | None320+ max_content_width: int | None321+ allow_extra_args: bool322+ allow_interspersed_args: bool323+ ignore_unknown_options: bool324+ help_option_names: list[str]325+ token_normalize_func: t.Callable[[str], str] | None326+ resilient_parsing: bool327+ auto_envvar_prefix: str | None328+ color: bool | None329+ show_default: bool | None330+ _close_callbacks: list[t.Callable[[], t.Any]]331+ _depth: int332+ _parameter_source: dict[str, ParameterSource]333+ _param_default_explicit: dict[str, bool]334+ _exit_stack: ExitStack335+336 def __init__(337 self,338 command: Command,339 parent: Context | None = None,19 unmodified lines359 #: the descriptive information name360 self.info_name = info_name361 #: Map of parameter names to their parsed values. Parameters362 #: with ``expose_value=False`` are not stored.333- self.params: dict[str, t.Any] = {}363+ self.params = {}364 #: the leftover arguments.335- self.args: list[str] = []365+ self.args = []366 #: protected arguments. These are arguments that are prepended367 #: to `args` when certain parsing scenarios are encountered but368 #: must be never propagated to another arguments. This is used369 #: to implement nested parsing.340- self._protected_args: list[str] = []370+ self._protected_args = []371 #: the collected prefixes of the command's options.342- self._opt_prefixes: set[str] = set(parent._opt_prefixes) if parent else set()372+ self._opt_prefixes = set(parent._opt_prefixes) if parent else set()373 374 if obj is None and parent is not None:375 obj = parent.obj376 377 #: the user object stored.348- self.obj: t.Any = obj349- self._meta: dict[str, t.Any] = getattr(parent, "meta", {})378+ self.obj = obj379+ self._meta = getattr(parent, "meta", {})380 381 #: A dictionary (-like object) with defaults for parameters.382 if (383 default_map is None2 unmodified lines386 and parent.default_map is not None387 ):388 default_map = parent.default_map.get(info_name)389 360- self.default_map: cabc.MutableMapping[str, t.Any] | None = default_map390+ self.default_map = default_map391 392 #: This flag indicates if a subcommand is going to be executed. A393 #: group callback can use this information to figure out if it's394 #: being executed directly or because the execution flow passes3 unmodified lines398 #: If chaining is enabled this will be set to ``'*'`` in case399 #: any commands are executed. It is however not possible to400 #: figure out which ones. If you require this knowledge you401 #: should use a :func:`result_callback`.372- self.invoked_subcommand: str | None = None402+ self.invoked_subcommand = None403 404 if terminal_width is None and parent is not None:405 terminal_width = parent.terminal_width406 407 #: The width of the terminal (None is autodetection).378- self.terminal_width: int | None = terminal_width408+ self.terminal_width = terminal_width409 410 if max_content_width is None and parent is not None:411 max_content_width = parent.max_content_width412 413 #: The maximum width of formatted content (None implies a sensible414 #: default which is 80 for most things).385- self.max_content_width: int | None = max_content_width415+ self.max_content_width = max_content_width416 417 if allow_extra_args is None:418 allow_extra_args = command.allow_extra_args419 9 unmodified lines429 #: Indicates if the context allows mixing of arguments and430 #: options or not.431 #:432 #: .. versionadded:: 3.0403- self.allow_interspersed_args: bool = allow_interspersed_args433+ self.allow_interspersed_args = allow_interspersed_args434 435 if ignore_unknown_options is None:436 ignore_unknown_options = command.ignore_unknown_options437 4 unmodified lines442 #: strongly discouraged because it's not possibly to losslessly443 #: forward all arguments.444 #:445 #: .. versionadded:: 4.0416- self.ignore_unknown_options: bool = ignore_unknown_options446+ self.ignore_unknown_options = ignore_unknown_options447 448 if help_option_names is None:449 if parent is not None:450 help_option_names = parent.help_option_names451 else:452 help_option_names = ["--help"]453 454 #: The names for the help options.425- self.help_option_names: list[str] = help_option_names455+ self.help_option_names = help_option_names456 457 if token_normalize_func is None and parent is not None:458 token_normalize_func = parent.token_normalize_func459 460 #: An optional normalization function for tokens. This is461 #: options, choices, commands etc.432- self.token_normalize_func: t.Callable[[str], str] | None = token_normalize_func462+ self.token_normalize_func = token_normalize_func463 464 #: Indicates if resilient parsing is enabled. In that case Click465 #: will do its best to not cause any failures and default values466 #: will be ignored. Useful for completion.437- self.resilient_parsing: bool = resilient_parsing467+ self.resilient_parsing = resilient_parsing468 469 # If there is no envvar prefix yet, but the parent has one and470 # the command on this level has a name, we can expand the envvar471 # prefix automatically.11 unmodified lines483 484 if auto_envvar_prefix is not None:485 auto_envvar_prefix = auto_envvar_prefix.replace("-", "_")486 457- self.auto_envvar_prefix: str | None = auto_envvar_prefix487+ self.auto_envvar_prefix = auto_envvar_prefix488 489 if color is None and parent is not None:490 color = parent.color491 492 #: Controls if styling output is wanted or not.463- self.color: bool | None = color493+ self.color = color494 495 if show_default is None and parent is not None:496 show_default = parent.show_default497 498 #: Show option default values when formatting help text.469- self.show_default: bool | None = show_default499+ self.show_default = show_default500 471- self._close_callbacks: list[t.Callable[[], t.Any]] = []501+ self._close_callbacks = []502 self._depth = 0473- self._parameter_source: dict[str, ParameterSource] = {}503+ self._parameter_source = {}504 # Tracks whether the option that currently owns each parameter slot in505 # :attr:`params` had its ``default`` set explicitly by the user. Used506 # to tie-break feature-switch groups where multiple options share a507 # parameter name and both fall back to their default value.508 # Refs: https://github.com/pallets/click/issues/3403479- self._param_default_explicit: dict[str, bool] = {}509+ self._param_default_explicit = {}510 self._exit_stack = ExitStack()511 512 @property513 def protected_args(self) -> list[str]:27 unmodified lines541 "ignore_unknown_options": self.ignore_unknown_options,542 "auto_envvar_prefix": self.auto_envvar_prefix,543 }544 515- def __enter__(self) -> Context:545+ def __enter__(self) -> Self:546 self._depth += 1547 push_context(self)548 return self549 11 unmodified lines561 562 return exit_result563 564 @contextmanager535- def scope(self, cleanup: bool = True) -> cabc.Iterator[Context]:565+ def scope(self, cleanup: bool = True) -> cabc.Generator[Context]:566 """This helper method can be used with the context object to promote567 it to the current thread local (see :func:`get_current_context`).568 The default behavior of this is to invoke the cleanup functions which569 can be disabled by setting `cleanup` to `False`. The cleanup444 unmodified lines1014 1015 #: the default for the :attr:`Context.ignore_unknown_options` flag.1016 ignore_unknown_options = False1017 1018+ name: str | None1019+ context_settings: cabc.MutableMapping[str, t.Any]1020+ callback: t.Callable[..., t.Any] | None1021+ params: list[Parameter]1022+ help: str | None1023+ epilog: str | None1024+ options_metavar: str | None1025+ short_help: str | None1026+ add_help_option: bool1027+ _help_option: Option | None1028+ no_args_is_help: bool1029+ hidden: bool1030+ deprecated: bool | str1031+1032 def __init__(1033 self,1034 name: str | None,1035 context_settings: cabc.MutableMapping[str, t.Any] | None = None,17 unmodified lines1053 if context_settings is None:1054 context_settings = {}1055 1056 #: an optional dictionary with defaults passed to the context.1013- self.context_settings: cabc.MutableMapping[str, t.Any] = context_settings1057+ self.context_settings = context_settings1058 1059 #: the callback to execute when the command fires. This might be1060 #: `None` in which case nothing happens.1061 self.callback = callback1062 #: the list of parameters for this command in the order they1063 #: should show up in the help page and execute. Eager parameters1064 #: will automatically be handled before non eager ones.1021- self.params: list[Parameter] = params or []1065+ self.params = params or []1066 self.help = help1067 self.epilog = epilog1068 self.options_metavar = options_metavar1069 self.short_help = short_help580 unmodified lines1650 #: .. versionadded:: 8.01651 group_class: type[Group] | type[type] | None = None1652 # Literal[type] isn't valid, so use Type[type]1653 1654+ commands: cabc.MutableMapping[str, Command]1655+ invoke_without_command: bool1656+ subcommand_metavar: str1657+ chain: bool1658+ _result_callback: t.Callable[..., t.Any] | None1659+1660 def __init__(1661 self,1662 name: str | None = None,1663 commands: cabc.MutableMapping[str, Command]13 unmodified lines1677 elif isinstance(commands, abc.Sequence):1678 commands = {c.name: c for c in commands if c.name is not None}1679 1680 #: The registered subcommands by their exported names.1631- self.commands: cabc.MutableMapping[str, Command] = commands1681+ self.commands = commands1682 1683 if no_args_is_help is None:1684 no_args_is_help = not invoke_without_command1685 397 unmodified lines2083 This is a subclass of ``Group``. Commands are looked up first on this2084 group, then each of its sources.2085 """2086 2087+ sources: list[Group]2088+2089 def __init__(2090 self,2091 name: str | None = None,2092 sources: list[Group] | None = None,2093 **kwargs: t.Any,2094 ) -> None:2095 super().__init__(name, **kwargs)2096 #: The list of registered groups.2045- self.sources: list[Group] = sources or []2097+ self.sources = sources or []2098 2099 def add_source(self, group: Group) -> None:2100 """Add a group as a source of commands."""2101 self.sources.append(group)23 unmodified lines2125 2126 return sorted(rv)2127 2128 2077-def _check_iter(value: t.Any) -> cabc.Iterator[t.Any]:2129+def _check_iter(value: cabc.Iterable[V]) -> cabc.Iterator[V]:2130 """Check if the value is iterable but not a string. Raises a type2131 error, or return an iterator over the value.2132 """2133 if isinstance(value, str):94 unmodified lines2228 """2229 2230 param_type_name = "parameter"2231 2232+ name: str2233+ opts: list[str]2234+ secondary_opts: list[str]2235+ # `Parameter.type` is annotated in `__init__` to avoid confusing mypy2236+ required: bool2237+ callback: t.Callable[[Context, Parameter, t.Any], t.Any] | None2238+ nargs: int2239+ multiple: bool2240+ expose_value: bool2241+ default: t.Any | t.Callable[[], t.Any] | None2242+ _default_explicit: bool2243+ is_eager: bool2244+ metavar: str | None2245+ envvar: str | cabc.Sequence[str] | None2246+ _custom_shell_complete: (2247+ t.Callable[[Context, Parameter, str], list[CompletionItem] | list[str]] | None2248+ )2249+ deprecated: bool | str2250+2251 def __init__(2252 self,2253 param_decls: cabc.Sequence[str] | None = None,2254 type: types.ParamType[t.Any] | t.Any | None = None,21 unmodified lines2276 ]2277 | None = None,2278 deprecated: bool | str = False,2279 ) -> None:2209- self.name: str2210- self.opts: list[str]2211- self.secondary_opts: list[str]2280 self.name, self.opts, self.secondary_opts = self._parse_decls(2281 param_decls or (), expose_value2282 )2283 self.type: types.ParamType[t.Any] = types.convert_type(type, default)10 unmodified lines2294 self.callback = callback2295 self.nargs = nargs2296 self.multiple = multiple2297 self.expose_value = expose_value2230- self.default: t.Any | t.Callable[[], t.Any] | None = default2298+ self.default = default2299 # Whether the user passed ``default`` explicitly to the constructor.2300 # Captured before any auto-derived default (like ``False`` for boolean2301 # flags in :class:`Option`) replaces the :data:`UNSET` sentinel, so it2302 # remains ``False`` when the default was inferred rather than chosen.2303 # Refs: https://github.com/pallets/click/issues/34032236- self._default_explicit: bool = default is not UNSET2304+ self._default_explicit = default is not UNSET2305 self.is_eager = is_eager2306 self.metavar = metavar2307 self.envvar = envvar2308 self._custom_shell_complete = shell_complete566 unmodified lines2875 """2876 2877 param_type_name = "option"2878 2879+ prompt: str | None2880+ confirmation_prompt: bool | str2881+ prompt_required: bool2882+ hide_input: bool2883+ hidden: bool2884+2885+ _flag_needs_value: bool2886+ is_flag: bool2887+ is_bool_flag: bool2888+ flag_value: t.Any2889+2890+ count: bool2891+ allow_from_autoenv: bool2892+ help: str | None2893+ show_default: bool | str | None2894+ show_choices: bool2895+ show_envvar: bool2896+2897 def __init__(2898 self,2899 param_decls: cabc.Sequence[str] | None = None,2900 show_default: bool | str | None = None,24 unmodified lines2925 if prompt is True:2926 if not self.name:2927 raise TypeError("'name' is required with 'prompt=True'.")2928 2843- prompt_text: str | None = self.name.replace("_", " ").capitalize()2929+ prompt_text = self.name.replace("_", " ").capitalize()2930 elif prompt is False:2931 prompt_text = None2932 else:2933 prompt_text = prompt65 unmodified lines2999 self.type = types.UNPROCESSED3000 else:3001 self.type = guessed3002 2917- self.is_flag: bool = bool(is_flag)2918- self.is_bool_flag: bool = bool(2919- is_flag and isinstance(self.type, types.BoolParamType)2920- )2921- self.flag_value: t.Any = flag_value3003+ self.is_flag = bool(is_flag)3004+ self.is_bool_flag = self.is_flag and isinstance(self.type, types.BoolParamType)3005+ self.flag_value = flag_value3006 3007 # Set boolean flag default to False if unset and not required.3008 if self.is_bool_flag:3009 if self.default is UNSET and not self.required:667 unmodified linesmodified:src/click/termui.py+4 added
333 unmodified lines334 335 with get_pager_file(color=color) as pager:336 for text in itertools.chain(text_generator, "\n"):337 pager.write(text)338+ # Flush after each write so a slow generator streams to the pager339+ # incrementally rather than staying invisible until the pipe buffer340+ # fills (~8 KB).341+ pager.flush()342 343 344 @t.overload345 def progressbar(589 unmodified linesmodified:src/click/testing.py+4 added-1 removed
20 unmodified lines21 from _typeshed import ReadableBuffer22 23 from .core import Command24 25+if sys.platform == "win32":26+ CaptureMode: t.TypeAlias = t.Literal["sys"] # pyright: ignore[reportRedeclaration]27+else:25-CaptureMode: t.TypeAlias = t.Literal["sys", "fd"]28+ CaptureMode: t.TypeAlias = t.Literal["sys", "fd"] # pyright: ignore[reportRedeclaration]29 ExceptionInfo: t.TypeAlias = tuple[type[BaseException], BaseException, TracebackType]30 31 32 class EchoingStdin:740 unmodified linesmodified:src/click/types.py+148 added-83 removed
24 unmodified lines25 from .core import Context26 from .core import Parameter27 from .shell_completion import CompletionItem28 29-ParamTypeValue = t.TypeVar("ParamTypeValue")29+_ValueT = t.TypeVar("_ValueT")30+_ValueT_contra = t.TypeVar("_ValueT_contra", contravariant=True)31+_ValueT_co = t.TypeVar("_ValueT_co", covariant=True)32 33+_FloatValueT = t.TypeVar("_FloatValueT", bound=float)34+_FloatValueT_co = t.TypeVar("_FloatValueT_co", bound=float, covariant=True)35 36+37 class ParamTypeInfoDict(t.TypedDict):38 param_type: str39 name: str40 41 37-class ParamType(t.Generic[ParamTypeValue], abc.ABC):42+class ParamType(t.Generic[_ValueT_co], abc.ABC):43 """Represents the type of a parameter. Validates and converts values44 from the command line or Python into the correct type.45 46 To implement a custom type, subclass and implement at least the16 unmodified lines63 narrowed return type.64 """65 66 is_composite: t.ClassVar[bool] = False62- arity: t.ClassVar[int] = 167+ arity: int = 1 # read-only68 69 #: the descriptive name of this type70 name: str71 30 unmodified lines102 self,103 value: t.Any,104 param: Parameter | None = None,105 ctx: Context | None = None,101- ) -> ParamTypeValue | None:106+ ) -> _ValueT_co | None:107 if value is not None:108 return self.convert(value, param, ctx)109 return None110 8 unmodified lines119 """120 121 def convert(122 self, value: t.Any, param: Parameter | None, ctx: Context | None118- ) -> ParamTypeValue:123+ ) -> _ValueT_co:124 """Convert the value to the correct type. This is not called if125 the value is ``None`` (the missing value).126 127 This must accept string values from the command line, as well as13 unmodified lines141 be ``None``.142 """143 # The default returns the value as-is so subclasses that only customize144 # metadata are not forced to redeclare ``convert``.140- return t.cast("ParamTypeValue", value)145+ return t.cast("_ValueT_co", value)146 147 def split_envvar_value(self, rv: str) -> cabc.Sequence[str]:148 """Given a value from an environment variable this splits it up149 into small chunks depending on the defined envvar list splitter.30 unmodified lines180 """181 return []182 183 179-class CompositeParamType(ParamType[ParamTypeValue]):180- is_composite = True184+class CompositeParamType(ParamType[_ValueT_co]):185+ is_composite: t.ClassVar[bool] = True186 187 @property188 @abc.abstractmethod189 def arity(self) -> int: ... # type: ignore[override]190 191 187-class FuncParamTypeInfoDict(ParamTypeInfoDict):188- func: t.Callable[[t.Any], t.Any]192+if t.TYPE_CHECKING:193+ # on Python 3.10 this will raise a TypeError194 195+ class FuncParamTypeInfoDict(196+ ParamTypeInfoDict,197+ t.Generic[_ValueT_contra, _ValueT_co],198+ ):199+ func: t.Callable[[_ValueT_contra], _ValueT_co]200+else:201 191-class FuncParamType(ParamType[ParamTypeValue]):192- def __init__(self, func: t.Callable[[t.Any], ParamTypeValue]) -> None:193- self.name: str = func.__name__202+ class FuncParamTypeInfoDict(ParamTypeInfoDict):203+ func: t.Callable[[t.Any], t.Any]204+205+206+class FuncParamType(ParamType[_ValueT_co], t.Generic[_ValueT_contra, _ValueT_co]):207+ name: str208+ func: t.Callable[[_ValueT_contra], _ValueT_co]209+210+ def __init__(self, func: t.Callable[[_ValueT_contra], _ValueT_co]) -> None:211+ self.name = func.__name__212 self.func = func213 196- def to_info_dict(self) -> FuncParamTypeInfoDict:214+ def to_info_dict(self) -> FuncParamTypeInfoDict[_ValueT_contra, _ValueT_co]:215 return {"func": self.func, **super().to_info_dict()}216 217 def convert(200- self, value: t.Any, param: Parameter | None, ctx: Context | None201- ) -> ParamTypeValue:218+ self, value: _ValueT_contra, param: Parameter | None, ctx: Context | None219+ ) -> _ValueT_co:220 try:221 return self.func(value)222 except ValueError as exc:223 message = str(exc)1 unmodified line225 if not message:226 try:227 message = str(value)228 except UnicodeError:211- message = value.decode("utf-8", "replace")229+ message = t.cast("bytes", value).decode("utf-8", "replace")230 231 self.fail(message, param, ctx)232 233 234 class UnprocessedParamType(ParamType[t.Any]):235 name = "text"236 237 def convert(220- self, value: t.Any, param: Parameter | None, ctx: Context | None221- ) -> t.Any:238+ self, value: _ValueT, param: Parameter | None, ctx: Context | None239+ ) -> _ValueT:240 return value241 242 def __repr__(self) -> str:243 return "UNPROCESSED"7 unmodified lines251 ) -> str:252 if isinstance(value, bytes):253 enc = _get_argv_encoding()254 try:237- value = value.decode(enc)255+ return value.decode(enc)256 except UnicodeError:257 fs_enc = sys.getfilesystemencoding()258 if fs_enc != enc:259 try:242- value = value.decode(fs_enc)260+ return value.decode(fs_enc)261 except UnicodeError:244- value = value.decode("utf-8", "replace")262+ return value.decode("utf-8", "replace")263 else:246- value = value.decode("utf-8", "replace")247- return value # type: ignore[no-any-return]264+ return value.decode("utf-8", "replace")265 return str(value)266 267 def __repr__(self) -> str:268 return "STRING"269 270 254-class ChoiceInfoDict(ParamTypeInfoDict):255- choices: cabc.Sequence[t.Any]256- case_sensitive: bool271+if t.TYPE_CHECKING:272+ # on Python 3.10 this will raise a TypeError273 274+ class ChoiceInfoDict(ParamTypeInfoDict, t.Generic[_ValueT_co]):275+ choices: tuple[_ValueT_co, ...]276+ case_sensitive: bool277+else:278 259-class Choice(ParamType[ParamTypeValue], t.Generic[ParamTypeValue]):279+ class ChoiceInfoDict(ParamTypeInfoDict):280+ choices: tuple[t.Any, ...]281+ case_sensitive: bool282+283+284+class Choice(ParamType[_ValueT_co], t.Generic[_ValueT_co]):285 """The choice type allows a value to be checked against a fixed set286 of supported values.287 288 You may pass any iterable value which will be converted to a tuple19 unmodified lines308 .. versionadded:: 8.2.0309 Choice normalization can be overridden via :meth:`normalize_choice`.310 """311 287- name = "choice"312+ name: str = "choice"313 314+ choices: tuple[_ValueT_co, ...]315+ case_sensitive: bool316+317 def __init__(290- self, choices: cabc.Iterable[ParamTypeValue], case_sensitive: bool = True318+ self, choices: cabc.Iterable[_ValueT_co], case_sensitive: bool = True319 ) -> None:292- self.choices: cabc.Sequence[ParamTypeValue] = tuple(choices)320+ self.choices = tuple(choices)321 self.case_sensitive = case_sensitive322 295- def to_info_dict(self) -> ChoiceInfoDict:323+ def to_info_dict(self) -> ChoiceInfoDict[_ValueT_co]:324 return {325 "choices": self.choices,326 "case_sensitive": self.case_sensitive,327 **super().to_info_dict(),328 }329 330 def _normalized_mapping(331 self, ctx: Context | None = None304- ) -> cabc.Mapping[ParamTypeValue, str]:332+ ) -> cabc.Mapping[_ValueT_co, str]:333 """334 Returns mapping where keys are the original choices and the values are335 the normalized values that are accepted via the command line.336 7 unmodified lines344 )345 for choice in self.choices346 }347 320- def normalize_choice(self, choice: ParamTypeValue, ctx: Context | None) -> str:348+ def normalize_choice(self, choice: object, ctx: Context | None) -> str:349 """350 Normalize a choice value, used to map a passed string to a choice.351 Each choice must have a unique normalized value.352 12 unmodified lines365 366 return normed_value367 368 def get_metavar(self, param: Parameter, ctx: Context) -> str | None:341- if param.param_type_name == "option" and not param.show_choices: # type: ignore369+ if param.param_type_name == "option" and not param.show_choices: # type: ignore[attr-defined]370 choice_metavars = [371 convert_type(type(choice)).name.upper() for choice in self.choices372 ]373 choices_str = "|".join([*dict.fromkeys(choice_metavars)])20 unmodified lines394 )395 396 def convert(397 self, value: t.Any, param: Parameter | None, ctx: Context | None370- ) -> ParamTypeValue:398+ ) -> _ValueT_co:399 """400 For a given value from the parser, normalize it and find its401 matching normalized value in the list of choices. Then return the402 matched "original" choice.80 unmodified lines483 """484 485 name = "datetime"486 487+ formats: cabc.Sequence[str]488+489 def __init__(self, formats: cabc.Sequence[str] | None = None):460- self.formats: cabc.Sequence[str] = formats or [490+ self.formats = formats or [491 "%Y-%m-%d",492 "%Y-%m-%dT%H:%M:%S",493 "%Y-%m-%d %H:%M:%S",494 ]495 496 def to_info_dict(self) -> DateTimeInfoDict:497 return {"formats": self.formats, **super().to_info_dict()}498 469- def get_metavar(self, param: Parameter, ctx: Context) -> str | None:499+ def get_metavar(self, param: Parameter, ctx: Context) -> str:500 return f"[{'|'.join(self.formats)}]"501 502 def _try_to_convert_date(self, value: t.Any, format: str) -> datetime | None:503 try:27 unmodified lines531 def __repr__(self) -> str:532 return "DateTime"533 534 505-class _NumberParamTypeBase(ParamType[ParamTypeValue]):506- _number_class: t.Callable[[t.Any], ParamTypeValue]535+class _NumberParamTypeBase(536+ ParamType[_ValueT_co], t.Generic[_ValueT_contra, _ValueT_co]537+):538+ _number_class: t.Callable[[_ValueT_contra], _ValueT_co]539 540 def convert(509- self, value: t.Any, param: Parameter | None, ctx: Context | None510- ) -> ParamTypeValue:541+ self, value: _ValueT_contra, param: Parameter | None, ctx: Context | None542+ ) -> _ValueT_co:543 try:544 return self._number_class(value)545 except ValueError:546 self.fail(4 unmodified lines551 ctx,552 )553 554 555+if t.TYPE_CHECKING:556+ # on Python 3.10 this will raise a TypeError557+558+ class NumberRangeInfoDict(ParamTypeInfoDict, t.Generic[_FloatValueT_co]):559+ min: _FloatValueT_co | None560+ max: _FloatValueT_co | None561+ min_open: bool562+ max_open: bool563+ clamp: bool564+else:565+523-class NumberRangeInfoDict(ParamTypeInfoDict):524- min: float | None525- max: float | None566+ class NumberRangeInfoDict(ParamTypeInfoDict):567+ min: t.Any | None568+ max: t.Any | None569+ min_open: bool570+ max_open: bool571+ clamp: bool572+573+574+class _NumberRangeBase(575+ _NumberParamTypeBase[_ValueT_contra, _FloatValueT_co],576+ t.Generic[_ValueT_contra, _FloatValueT_co],577+):578+ min: _FloatValueT_co | None579+ max: _FloatValueT_co | None580 min_open: bool581 max_open: bool582 clamp: bool583 530-531-class _NumberRangeBase(_NumberParamTypeBase[ParamTypeValue]):584 def __init__(585 self,534- min: float | None = None,535- max: float | None = None,586+ min: _FloatValueT_co | None = None,587+ max: _FloatValueT_co | None = None,588 min_open: bool = False,589 max_open: bool = False,590 clamp: bool = False,591 ) -> None:2 unmodified lines594 self.min_open = min_open595 self.max_open = max_open596 self.clamp = clamp597 546- def to_info_dict(self) -> NumberRangeInfoDict:598+ def to_info_dict(self) -> NumberRangeInfoDict[_FloatValueT_co]:599 return {600 "min": self.min,601 "max": self.max,602 "min_open": self.min_open,2 unmodified lines605 **super().to_info_dict(),606 }607 608 def convert(557- self, value: t.Any, param: Parameter | None, ctx: Context | None558- ) -> ParamTypeValue:609+ self, value: _ValueT_contra, param: Parameter | None, ctx: Context | None610+ ) -> _FloatValueT_co:611 import operator612 613 rv = super().convert(value, param, ctx)614 min = self.min615 max = self.max616 lt_min: bool = min is not None and (617 operator.le if self.min_open else operator.lt566- )(rv, min) # type: ignore[arg-type]618+ )(rv, min)619 gt_max: bool = max is not None and (620 operator.ge if self.max_open else operator.gt569- )(rv, max) # type: ignore[arg-type]621+ )(rv, max)622 623 if self.clamp:624 if min is not None and lt_min:573- return self._clamp(min, 1, self.min_open) # type: ignore[arg-type]625+ return self._clamp(min, 1, self.min_open)626 627 if max is not None and gt_max:576- return self._clamp(max, -1, self.max_open) # type: ignore[arg-type]628+ return self._clamp(max, -1, self.max_open)629 630 if lt_min or gt_max:631 self.fail(632 _("{value} is not in the range {range}.").format(6 unmodified lines639 return rv640 641 @abc.abstractmethod642 def _clamp(591- self, bound: ParamTypeValue, dir: t.Literal[1, -1], open: bool592- ) -> ParamTypeValue:643+ # Covariant type variables cannot be used in input positions, so we use a644+ # separate method-scoped type variable instead.645+ self: _NumberRangeBase[t.Any, _FloatValueT],646+ bound: _FloatValueT,647+ dir: t.Literal[1, -1],648+ open: bool,649+ ) -> _FloatValueT:650 """Find the valid value to clamp to bound in the given651 direction.652 653 :param bound: The boundary value.20 unmodified lines674 clamp = " clamped" if self.clamp else ""675 return f"<{type(self).__name__} {self._describe_range()}{clamp}>"676 677 621-class IntParamType(_NumberParamTypeBase[int]):678+class IntParamType(_NumberParamTypeBase[t.SupportsInt | t.SupportsIndex, int]):679 name = "integer"680 _number_class = int681 682 def __repr__(self) -> str:683 return "INT"684 685 629-class IntRange(_NumberRangeBase[int], IntParamType):686+class IntRange(_NumberRangeBase[int, int], IntParamType):687 """Restrict an :data:`click.INT` value to a range of accepted688 values. See :ref:`ranges`.689 690 If ``min`` or ``max`` are not passed, any value is accepted in that15 unmodified lines706 707 return bound + dir708 709 653-class FloatParamType(_NumberParamTypeBase[float]):710+class FloatParamType(_NumberParamTypeBase[t.SupportsFloat | t.SupportsIndex, float]):711 name = "float"712 _number_class = float713 714 def __repr__(self) -> str:715 return "FLOAT"716 717 661-class FloatRange(_NumberRangeBase[float], FloatParamType):718+class FloatRange(_NumberRangeBase[float, float], FloatParamType):719 """Restrict a :data:`click.FLOAT` value to a range of accepted720 values. See :ref:`ranges`.721 722 If ``min`` or ``max`` are not passed, any value is accepted in that107 unmodified lines830 class UUIDParameterType(ParamType[uuid.UUID]):831 name = "uuid"832 833 def convert(777- self, value: t.Any, param: Parameter | None, ctx: Context | None834+ self, value: uuid.UUID | str, param: Parameter | None, ctx: Context | None835 ) -> uuid.UUID:836 if isinstance(value, uuid.UUID):837 return value838 47 unmodified lines886 887 name = "filename"888 envvar_list_splitter: t.ClassVar[str] = os.path.pathsep889 890+ mode: str891+ encoding: str | None892+ errors: str | None893+ lazy: bool | None894+ atomic: bool895+896 def __init__(897 self,898 mode: str = "r",899 encoding: str | None = None,31 unmodified lines931 ) -> t.IO[t.Any]:932 if _is_file_like(value):933 return value934 872- value = t.cast("str | os.PathLike[str]", value)873-935 try:936 lazy = self.resolve_lazy_flag(value)937 938 if lazy:45 unmodified lines984 985 return [CompletionItem(incomplete, type="file")]986 987 927-def _is_file_like(value: t.Any) -> te.TypeGuard[t.IO[t.Any]]:988+def _is_file_like(value: t.Any) -> te.TypeIs[t.IO[t.Any]]:989 return hasattr(value, "read") or hasattr(value, "write")990 991 992 class PathInfoDict(ParamTypeInfoDict):39 unmodified lines1032 """1033 1034 envvar_list_splitter: t.ClassVar[str] = os.path.pathsep1035 1036+ exists: bool1037+ file_okay: bool1038+ dir_okay: bool1039+ readable: bool1040+ writable: bool1041+ executable: bool1042+ resolve_path: bool1043+ allow_dash: bool1044+ name: str1045+1046 def __init__(1047 self,1048 exists: bool = False,1049 file_okay: bool = True,1 unmodified line1051 writable: bool = False,1052 readable: bool = True,1053 resolve_path: bool = False,1054 allow_dash: bool = False,984- path_type: type[t.Any] | None = None,1055+ path_type: type | None = None,1056 executable: bool = False,986- ):1057+ ) -> None:1058 self.exists = exists1059 self.file_okay = file_okay1060 self.dir_okay = dir_okay1061 self.readable = readable1062 self.writable = writable1063 self.executable = executable1064 self.resolve_path = resolve_path1065 self.allow_dash = allow_dash995- self.type = path_type1066+ self.type: type | None = path_type1067 1068 if self.file_okay and not self.dir_okay:998- self.name: str = _("file")1069+ self.name = _("file")1070 elif self.dir_okay and not self.file_okay:1071 self.name = _("directory")1072 else:1073 self.name = _("path")207 unmodified lines1281 1282 1283 @t.overload1284 def convert_type(ty: None, default: None = None) -> StringParamType: ...1214-1215-1285 @t.overload1286 def convert_type(1218- ty: type[t.Any] | ParamType[t.Any], default: t.Any | None = None1287+ ty: type | ParamType[t.Any], default: t.Any | None = None1288 ) -> ParamType[t.Any]: ...1220-1221-1289 @t.overload1290 def convert_type(1291 ty: t.Any | None, default: t.Any | None = None1292 ) -> ParamType[t.Any]: ...1226-1227-1293 def convert_type(1294 ty: t.Any | None = None, default: t.Any | None = None1295 ) -> ParamType[t.Any]:1296 """Find the most appropriate :class:`ParamType` for the given Python47 unmodified lines1344 #: there are situations where an unprocessed type is useful which is why1345 #: it is provided.1346 #:1347 #: .. versionadded:: 4.01283-UNPROCESSED = UnprocessedParamType()1348+UNPROCESSED: t.Final[UnprocessedParamType] = UnprocessedParamType()1349 1350 #: A unicode string parameter type which is the implicit default. This1351 #: can also be selected by using ``str`` as type.1287-STRING = StringParamType()1352+STRING: t.Final[StringParamType] = StringParamType()1353 1354 #: An integer parameter. This can also be selected by using ``int`` as1355 #: type.1291-INT = IntParamType()1356+INT: t.Final[IntParamType] = IntParamType()1357 1358 #: A floating point value parameter. This can also be selected by using1359 #: ``float`` as type.1295-FLOAT = FloatParamType()1360+FLOAT: t.Final[FloatParamType] = FloatParamType()1361 1362 #: A boolean parameter. This is the default for boolean flags. This can1363 #: also be selected by using ``bool`` as a type.1299-BOOL = BoolParamType()1364+BOOL: t.Final[BoolParamType] = BoolParamType()1365 1366 #: A UUID parameter.1302-UUID = UUIDParameterType()1367+UUID: t.Final[UUIDParameterType] = UUIDParameterType()1368 1369 1370 class OptionHelpExtra(t.TypedDict, total=False):1371 envvars: tuple[str, ...]3 unmodified linesmodified:src/click/utils.py+12 added
202 unmodified lines203 return iter(self._f) # type: ignore204 205 206 class KeepOpenFile:207+ """Proxy a file object but keep it open across a ``with`` block.208+209+ Wraps a borrowed file (such as ``sys.stdin`` or ``sys.stdout``) so that210+ leaving a ``with`` block does not close it, as used by :func:`open_file`211+ for the ``-`` filename. The caller stays responsible for the file: an212+ explicit :meth:`close` still passes through to the wrapped object.213+214+ Dunder methods are proxied explicitly: implicit special-method lookups215+ bypass :meth:`__getattr__`, because Python resolves them on the type rather216+ than the instance.217+ """218+219 _file: t.IO[t.Any]220 221 def __init__(self, file: t.IO[t.Any]) -> None:222 self._file = file425 unmodified linesmodified:tests/test_stream_lifecycle.py+3 added-1 removed
482 unmodified lines483 # ---------------------------------------------------------------------------484 # Category 6: Stress tests - high-iteration reproducers for race conditions485 #486 # These are marked with ``pytest.mark.stress`` so they can be included or487-# excluded independently. The CI workflow runs them in a separate job.487+# excluded independently. The ``tox -e stress`` env collects every488+# ``pytest.mark.stress`` test across the suite (not just this file), so489+# stress regressions for other components live alongside their unit tests.490 # ---------------------------------------------------------------------------491 492 493 @pytest.mark.stress47 unmodified linesmodified:tests/test_termui.py+94 added
1 import contextlib2+import gc3 import io4 import platform5 import shlex6 import shutil719 unmodified lines726 assert err == ""727 assert out == expected728 729 730+def test_echo_via_pager_streams_each_write(monkeypatch):731+ """Each write is flushed so a slow generator streams to the pager732+ incrementally instead of buffering until the end (issues #3242, #2542).733+ """734+ calls = []735+736+ class RecordingStream(io.StringIO):737+ def __init__(self):738+ super().__init__()739+ self.color = None740+741+ def write(self, s):742+ calls.append("write")743+ return super().write(s)744+745+ def flush(self):746+ calls.append("flush")747+748+ stream = RecordingStream()749+ monkeypatch.setattr(click._termui_impl, "isatty", lambda _: False)750+ monkeypatch.setattr(click._termui_impl, "_default_text_stdout", lambda: stream)751+752+ def generate():753+ yield "a\n"754+ yield "b\n"755+ yield "c\n"756+757+ click.echo_via_pager(generate())758+759+ # No two writes are adjacent: every chunk is flushed before the next one,760+ # so the pager sees output as it is produced.761+ assert not any(762+ calls[i] == "write" and calls[i + 1] == "write" for i in range(len(calls) - 1)763+ )764+ assert calls.count("write") == 4 # three chunks plus the trailing newline765+ assert stream.getvalue() == "a\nb\nc\n\n"766+767+768 def test_get_pager_file_pager_missing_binary_falls_back(monkeypatch, tmp_path):769 """``PAGER`` pointing to a nonexistent binary falls back to the text stdout."""770 pager_out = tmp_path / "pager_out.txt"771 34 unmodified lines806 807 assert pager_out.read_text(encoding="utf-8") == "hello\n"808 809 810+def test_get_pager_file_missing_pager_keeps_borrowed_stream_open(monkeypatch):811+ """A missing ``PAGER`` must not close the borrowed stdout (issue #3449).812+813+ The ``8.4.0`` regression was only fixed for the no-tty ``_nullpager`` path;814+ the ``_pipepager``/``_tempfilepager`` fallbacks (reached in a tty when815+ ``PAGER`` resolves to nothing) used to close the borrowed stream too.816+ """817+ buffer = io.BytesIO()818+ stream = io.TextIOWrapper(buffer, encoding="utf-8")819+820+ monkeypatch.setitem(821+ click._termui_impl.os.environ,822+ "PAGER",823+ "click-tests-nonexistent-pager-9b3f2",824+ )825+ monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)826+ monkeypatch.setattr(click._termui_impl, "_default_text_stdout", lambda: stream)827+828+ with click.get_pager_file() as pager:829+ pager.write("hello\n")830+831+ # Drop the wrapper reference and force finalization: the old bug closed the832+ # borrowed buffer when the TextIOWrapper built by get_pager_file was833+ # garbage-collected.834+ del pager835+ gc.collect()836+837+ assert not buffer.closed838+ assert not stream.closed839+ assert buffer.getvalue().replace(b"\r\n", b"\n") == b"hello\n"840+841+842+def test_echo_via_pager_tty_pager_missing(runner, monkeypatch):843+ """``echo_via_pager`` through the tty fallback keeps ``CliRunner`` working.844+845+ Regression for issue #3449 via the pager fallback: a tty with ``PAGER``846+ pointing at a missing binary used to close the runner's stdout, breaking847+ ``CliRunner.invoke``.848+ """849+ monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)850+ monkeypatch.setitem(851+ click._termui_impl.os.environ,852+ "PAGER",853+ "click-tests-nonexistent-pager-9b3f2",854+ )855+856+ @click.command()857+ def cli():858+ click.echo_via_pager("Hello, Click!")859+860+ result = runner.invoke(cli)861+ assert not result.exception862+ assert result.output == "Hello, Click!\n"863+864+865 @pytest.mark.parametrize(866 ("color", "expected"),867 [868 pytest.param(False, "hello\n", id="strip ansi"),694 unmodified linesmodified:tests/test_types.py+15 added-6 removed
241 unmodified lines242 click.File(mode="r", lazy=True),243 ],244 )245 def test_file_surrogates(type, tmp_path):246- path = tmp_path / "\udcff"246+ """Ensures that the error handling in ``click.File`` is robust.247 248- # - common case: �': No such file or directory249- # - special case: Illegal byte sequence250- # The special case is seen with rootless Podman. The root cause is most251- # likely that the path is handled by a user-space program (FUSE).252- match = r"(�': No such file or directory|Illegal byte sequence)"248+ ``EILSEQ`` shows up with rootless Podman (FUSE-backed paths) and on filesystems249+ that reject non-UTF-8 names, like ZFS with ``utf8only=on``.250+251+ See: https://github.com/pallets/click/issues/2634252+ """253+ path = tmp_path / "\udcff"254+ match = (255+ # Common case: �': No such file or directory.256+ r"(�': No such file or directory"257+ # BSD/macOS libc special case (EILSEQ).258+ r"|Illegal byte sequence"259+ # glibc special case (EILSEQ).260+ r"|Invalid or incomplete multibyte or wide character)"261+ )262 with pytest.raises(click.BadParameter, match=match):263 type.convert(path, None, None)264 265 20 unmodified linesmodified:tests/test_utils.py+74 added-5 removed
14 unmodified lines15 import pytest16 17 import click._termui_impl18 import click.utils19-from click._compat import MAC19 from click._compat import WIN20 from click._utils import UNSET21 22 261 unmodified lines284 yield "abc"285 286 287 def _test_gen_func_fails():288+ raise RuntimeError("This is a test.")289+ yield # unreachable, keeps this a generator function290+291+292+def _test_gen_func_yields_then_fails():293 yield "test"294 raise RuntimeError("This is a test.")295 296 21 unmodified lines318 )319 320 321 @pytest.mark.skipif(WIN, reason="Different behavior on windows.")318-@pytest.mark.skipif(319- MAC and sys.version_info >= (3, 13) and not sys._is_gil_enabled(),320- reason="Generator exception tests are flaky in Python 3.14t on macOS.",321-)322 @pytest.mark.parametrize(323 "pager_cmd", ["cat", "cat ", " cat ", "less", " less", " less "]324 )325 @pytest.mark.parametrize(129 unmodified lines455 f"Unexpected stderr in test case '{test.description}'"456 )457 458 459+@pytest.mark.skipif(WIN, reason="Different behavior on windows.")460+def test_echo_via_pager_yields_before_exception(monkeypatch, tmp_path):461+ """A generator that yields then raises: click writes the partial output to462+ the pager stream before propagating the exception.463+464+ The pager file content is intentionally NOT asserted: pipe-drain timing465+ between click and the pager subprocess is outside click's control466+ (#2899, #3470). Spying on ``MaybeStripAnsi.write`` records what click sent467+ to the pager, which is deterministic regardless of scheduling.468+ """469+ monkeypatch.setitem(os.environ, "PAGER", "cat")470+ monkeypatch.setattr(click._termui_impl, "isatty", lambda x: True)471+472+ writes: list[str] = []473+ real_write = click._termui_impl.MaybeStripAnsi.write474+475+ def spy(self, text):476+ writes.append(text)477+ return real_write(self, text)478+479+ monkeypatch.setattr(click._termui_impl.MaybeStripAnsi, "write", spy)480+481+ pager_out_tmp = tmp_path / "pager_out.txt"482+ with (483+ pager_out_tmp.open("w") as f,484+ patch.object(subprocess, "Popen", partial(subprocess.Popen, stdout=f)),485+ pytest.raises(RuntimeError, match="This is a test."),486+ ):487+ click.echo_via_pager(_test_gen_func_yields_then_fails())488+489+ assert "".join(writes) == "test", (490+ f"click should have written the yielded chunk before exception, got {writes!r}"491+ )492+493+494+@pytest.mark.stress495+@pytest.mark.skipif(WIN, reason="Different behavior on windows.")496+@pytest.mark.parametrize("_", range(1000))497+def test_stress_echo_via_pager_exception_cleanup(_, monkeypatch, tmp_path):498+ """Repeated exceptions during ``echo_via_pager`` must not leak subprocesses.499+500+ Regression coverage for the cleanup path in ``_pipepager``'s exception501+ handler (issue #2899, PR #3470). Each iteration spawns a real pager502+ subprocess, raises before any data is written and check there is no leak.503+ """504+ monkeypatch.setitem(os.environ, "PAGER", "cat")505+ monkeypatch.setattr(click._termui_impl, "isatty", lambda x: True)506+507+ spawned: list[subprocess.Popen] = []508+ real_popen = subprocess.Popen509+510+ def tracking_popen(*args, **kwargs):511+ p = real_popen(*args, **kwargs)512+ spawned.append(p)513+ return p514+515+ pager_out_tmp = tmp_path / "pager_out.txt"516+ with (517+ pager_out_tmp.open("w") as f,518+ patch.object(subprocess, "Popen", partial(tracking_popen, stdout=f)),519+ pytest.raises(RuntimeError),520+ ):521+ click.echo_via_pager(_test_gen_func_fails())522+523+ assert spawned, "pager subprocess was never started"524+ for p in spawned:525+ assert p.returncode is not None, "pager subprocess not reaped"526+527+528 def test_echo_color_flag(monkeypatch, capfd):529 isatty = True530 monkeypatch.setattr(click._compat, "isatty", lambda x: isatty)531 326 unmodified linesmodified:CHANGES.md+15 added-6 removed
18 unmodified lines19 render a stray leading space before the `(DEPRECATED)` label. {pr}`3509`20 - A {class}`Group` with `invoke_without_command=True` marks its subcommand as21 optional in the usage help, showing `[COMMAND]` instead of `COMMAND`.22 {issue}`3059` {pr}`3507`23+- `echo_via_pager` flushes after each write, so passing a generator streams24+ output to the pager incrementally instead of staying hidden until the pipe25+ buffer fills. {issue}`3242` {issue}`2542` {pr}`3534`26+- `echo_via_pager` and `get_pager_file` no longer close a borrowed stdout27+ stream when no external pager runs, completing the partial28+ `I/O operation on closed file` fix from {pr}`3482`. {issue}`3449`29+ {pr}`3533`30 31 ## Version 8.4.132 33 Released 2026-05-2134 35 - `get_parameter_source()` is available during eager callbacks and type29- conversion again. {issue}`3458` {issue}`3484`36+ conversion again. {issue}`3458` {pr}`3484`37 - Zsh completion scripts parse correctly on Windows. {issue}`3277` {pr}`3466`31-- Shell completion of `Choice` `Enum` values produces a valid completion32- result. {issue}`3015`33-- Fix empty byte-string handling in echo. {issue}`3487`34-- Fix closed file error with `echo_via_pager`. {issue}`3449`38+- Shell completion of `Enum` values used as `Choice` options produces a39+ valid completion result. {issue}`3015` {pr}`3471`40+- Fix empty byte-string handling in echo. {issue}`3487` {pr}`3493`41+- Fix closed file error with `echo_via_pager`. {issue}`3449` {pr}`3482`42+- Fix `open_url` on Windows when the file path contains spaces.43+ {issue}`2994` {pr}`3478`44 45 ## Version 8.4.046 47 Released 2026-05-1746 unmodified lines94 {pr}`2969`95 96 - Use {func}`os.startfile` on Windows to open URLs in {func}`open_url`,97 replacing the `start` built-in which cannot be invoked without89- `shell=True`. {issue}`3164` {pr}`3186`98+ `shell=True`. {issue}`2868` {issue}`3164` {pr}`3186`99 100 - Fix Fish shell completion errors when option help text contains newlines.101 {issue}`3043` {pr}`3126`102 1463 unmodified linesmodified:pyproject.toml+1 added-2 removed
174 unmodified lines175 {replace = "posargs", default = [], extend = true},176 ]]177 178 [tool.tox.env.stress]179-description = "stress tests for stream lifecycle race conditions"179+description = "high-iteration stress tests for race conditions"180 commands = [[181 "pytest", "-v", "--tb=short", "-x", "-m", "stress",182 "--basetemp={env_tmp_dir}",183 "--override-ini=addopts=",184- "tests/test_stream_lifecycle.py",184 {replace = "posargs", default = [], extend = true},185 ]]186 187 [tool.tox.env.style]44 unmodified lines