Skip to content
Myr

Merge stable into main

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Kevin Deldycke · committed by Kevin Deldycke · parents 4fc0e90, 8929d39 · 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

17 files+549 added−180 removed

modified:.github/workflows/nightly.yaml+7 added-5 removed
modified:docs/conf.py+1 added
29 unmodified lines
30}31intersphinx_mapping = {32 "python": ("https://docs.python.org/3/", None),33}34myst_enable_extensions = ["attrs_block"]35myst_heading_anchors = 33637# HTML -----------------------------------------------------------------38
21 unmodified lines
modified:docs/index.md+2 added-1 removed
modified:docs/parameters.md+1 added-1 removed
17 unmodified lines
18- Can be pulled from environment variables.1920## Arguments2122- 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 lines
modified:src/click/_compat.py-1 removed
10 unmodified lines
11from weakref import WeakKeyDictionary1213CYGWIN = sys.platform.startswith("cygwin")14WIN = sys.platform.startswith("win")15MAC = sys.platform == "darwin"15_ansi_re = re.compile(r"\033\[[;?0-9]*[a-zA-Z]")161718def _make_text_stream(
568 unmodified lines
modified:src/click/_termui_impl.py+44 added-28 removed
27 unmodified lines
28from ._compat import term_len29from ._compat import WIN30from .exceptions import ClickException31from .utils import echo32from .utils import KeepOpenFile3334V = t.TypeVar("V")3536
393 unmodified lines
430431@contextlib.contextmanager432def get_pager_file(color: bool | None = None) -> t.Generator[t.TextIO, None, None]:433 """Context manager.434435 Yields a writable file-like object which can be used as an output pager.436434 .. versionadded:: 8.4437 .. versionadded:: 8.4.0438439 :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()467468469@contextlib.contextmanager470def _pipepager(
11 unmodified lines
482 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 return492493 import shutil494
1 unmodified line
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()483 yield stdout, "utf-8", False503 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 symlink
79 unmodified lines
588 :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 return598599 import shutil600 import subprocess
1 unmodified line
602 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()583 yield stdout, "utf-8", False609 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 symlink
17 unmodified lines
632 finally:633 os.unlink(f.name)634635609class _SkipClose:610 def __init__(self, stream: t.IO[t.Any]) -> None:611 self.stream = stream612613 def __getattr__(self, name: str) -> t.Any:614 return getattr(self.stream, name)615616 @property617 def buffer(self) -> t.BinaryIO:618 return _SkipClose(self.stream.buffer) # type: ignore[attr-defined, return-value]619620 def close(self) -> None:621 pass622623636@contextlib.contextmanager637def _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.643644 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)649650 if color is None:651 color = False652637 yield _SkipClose(stream), encoding, color # type: ignore[misc]653 yield KeepOpenFile(stream), encoding, color # type: ignore[misc]654655656class Editor:657 def __init__(
288 unmodified lines
modified:src/click/core.py+124 added-40 removed
46 unmodified lines
47from .utils import make_str48from .utils import PacifyFlushWrapper4950if t.TYPE_CHECKING:51 from typing_extensions import Self5253 from .shell_completion import CompletionItem5455F = t.TypeVar("F", bound="t.Callable[..., t.Any]")56V = t.TypeVar("V")
61 unmodified lines
118119@contextmanager120def 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 lines
304 #:305 #: .. versionadded:: 8.0306 formatter_class: type[HelpFormatter] = HelpFormatter307308 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: ExitStack335336 def __init__(337 self,338 command: Command,339 parent: Context | None = None,
19 unmodified lines
359 #: 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()373374 if obj is None and parent is not None:375 obj = parent.obj376377 #: 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", {})380381 #: A dictionary (-like object) with defaults for parameters.382 if (383 default_map is None
2 unmodified lines
386 and parent.default_map is not None387 ):388 default_map = parent.default_map.get(info_name)389360 self.default_map: cabc.MutableMapping[str, t.Any] | None = default_map390 self.default_map = default_map391392 #: 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 passes
3 unmodified lines
398 #: 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 = None403404 if terminal_width is None and parent is not None:405 terminal_width = parent.terminal_width406407 #: The width of the terminal (None is autodetection).378 self.terminal_width: int | None = terminal_width408 self.terminal_width = terminal_width409410 if max_content_width is None and parent is not None:411 max_content_width = parent.max_content_width412413 #: 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_width416417 if allow_extra_args is None:418 allow_extra_args = command.allow_extra_args419
9 unmodified lines
429 #: 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_args434435 if ignore_unknown_options is None:436 ignore_unknown_options = command.ignore_unknown_options437
4 unmodified lines
442 #: 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_options447448 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"]453454 #: The names for the help options.425 self.help_option_names: list[str] = help_option_names455 self.help_option_names = help_option_names456457 if token_normalize_func is None and parent is not None:458 token_normalize_func = parent.token_normalize_func459460 #: 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_func463464 #: 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_parsing468469 # 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 lines
483484 if auto_envvar_prefix is not None:485 auto_envvar_prefix = auto_envvar_prefix.replace("-", "_")486457 self.auto_envvar_prefix: str | None = auto_envvar_prefix487 self.auto_envvar_prefix = auto_envvar_prefix488489 if color is None and parent is not None:490 color = parent.color491492 #: Controls if styling output is wanted or not.463 self.color: bool | None = color493 self.color = color494495 if show_default is None and parent is not None:496 show_default = parent.show_default497498 #: Show option default values when formatting help text.469 self.show_default: bool | None = show_default499 self.show_default = show_default500471 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()511512 @property513 def protected_args(self) -> list[str]:
27 unmodified lines
541 "ignore_unknown_options": self.ignore_unknown_options,542 "auto_envvar_prefix": self.auto_envvar_prefix,543 }544515 def __enter__(self) -> Context:545 def __enter__(self) -> Self:546 self._depth += 1547 push_context(self)548 return self549
11 unmodified lines
561562 return exit_result563564 @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 cleanup
444 unmodified lines
10141015 #: the default for the :attr:`Context.ignore_unknown_options` flag.1016 ignore_unknown_options = False10171018 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 | str10311032 def __init__(1033 self,1034 name: str | None,1035 context_settings: cabc.MutableMapping[str, t.Any] | None = None,
17 unmodified lines
1053 if context_settings is None:1054 context_settings = {}10551056 #: an optional dictionary with defaults passed to the context.1013 self.context_settings: cabc.MutableMapping[str, t.Any] = context_settings1057 self.context_settings = context_settings10581059 #: 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_help
580 unmodified lines
1650 #: .. versionadded:: 8.01651 group_class: type[Group] | type[type] | None = None1652 # Literal[type] isn't valid, so use Type[type]16531654 commands: cabc.MutableMapping[str, Command]1655 invoke_without_command: bool1656 subcommand_metavar: str1657 chain: bool1658 _result_callback: t.Callable[..., t.Any] | None16591660 def __init__(1661 self,1662 name: str | None = None,1663 commands: cabc.MutableMapping[str, Command]
13 unmodified lines
1677 elif isinstance(commands, abc.Sequence):1678 commands = {c.name: c for c in commands if c.name is not None}16791680 #: The registered subcommands by their exported names.1631 self.commands: cabc.MutableMapping[str, Command] = commands1681 self.commands = commands16821683 if no_args_is_help is None:1684 no_args_is_help = not invoke_without_command1685
397 unmodified lines
2083 This is a subclass of ``Group``. Commands are looked up first on this2084 group, then each of its sources.2085 """20862087 sources: list[Group]20882089 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 []20982099 def add_source(self, group: Group) -> None:2100 """Add a group as a source of commands."""2101 self.sources.append(group)
23 unmodified lines
21252126 return sorted(rv)212721282077def _check_iter(value: t.Any) -> cabc.Iterator[t.Any]:2129def _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 lines
2228 """22292230 param_type_name = "parameter"22312232 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 | str22502251 def __init__(2252 self,2253 param_decls: cabc.Sequence[str] | None = None,2254 type: types.ParamType[t.Any] | t.Any | None = None,
21 unmodified lines
2276 ]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 lines
2294 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_complete
566 unmodified lines
2875 """28762877 param_type_name = "option"28782879 prompt: str | None2880 confirmation_prompt: bool | str2881 prompt_required: bool2882 hide_input: bool2883 hidden: bool28842885 _flag_needs_value: bool2886 is_flag: bool2887 is_bool_flag: bool2888 flag_value: t.Any28892890 count: bool2891 allow_from_autoenv: bool2892 help: str | None2893 show_default: bool | str | None2894 show_choices: bool2895 show_envvar: bool28962897 def __init__(2898 self,2899 param_decls: cabc.Sequence[str] | None = None,2900 show_default: bool | str | None = None,
24 unmodified lines
2925 if prompt is True:2926 if not self.name:2927 raise TypeError("'name' is required with 'prompt=True'.")29282843 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 = prompt
65 unmodified lines
2999 self.type = types.UNPROCESSED3000 else:3001 self.type = guessed30022917 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_value30063007 # 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 lines
modified:src/click/termui.py+4 added
333 unmodified lines
334335 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()342343344@t.overload345def progressbar(
589 unmodified lines
modified:src/click/testing.py+4 added-1 removed
20 unmodified lines
21 from _typeshed import ReadableBuffer2223 from .core import Command2425if sys.platform == "win32":26 CaptureMode: t.TypeAlias = t.Literal["sys"] # pyright: ignore[reportRedeclaration]27else:25CaptureMode: t.TypeAlias = t.Literal["sys", "fd"]28 CaptureMode: t.TypeAlias = t.Literal["sys", "fd"] # pyright: ignore[reportRedeclaration]29ExceptionInfo: t.TypeAlias = tuple[type[BaseException], BaseException, TracebackType]303132class EchoingStdin:
740 unmodified lines
modified:src/click/types.py+148 added-83 removed
24 unmodified lines
25 from .core import Context26 from .core import Parameter27 from .shell_completion import CompletionItem2829ParamTypeValue = 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)3233_FloatValueT = t.TypeVar("_FloatValueT", bound=float)34_FloatValueT_co = t.TypeVar("_FloatValueT_co", bound=float, covariant=True)353637class ParamTypeInfoDict(t.TypedDict):38 param_type: str39 name: str404137class ParamType(t.Generic[ParamTypeValue], abc.ABC):42class 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.4546 To implement a custom type, subclass and implement at least the
16 unmodified lines
63 narrowed return type.64 """6566 is_composite: t.ClassVar[bool] = False62 arity: t.ClassVar[int] = 167 arity: int = 1 # read-only6869 #: the descriptive name of this type70 name: str71
30 unmodified lines
102 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 lines
119 """120121 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).126127 This must accept string values from the command line, as well as
13 unmodified lines
141 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)146147 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 lines
180 """181 return []182183179class CompositeParamType(ParamType[ParamTypeValue]):180 is_composite = True184class CompositeParamType(ParamType[_ValueT_co]):185 is_composite: t.ClassVar[bool] = True186187 @property188 @abc.abstractmethod189 def arity(self) -> int: ... # type: ignore[override]190191187class FuncParamTypeInfoDict(ParamTypeInfoDict):188 func: t.Callable[[t.Any], t.Any]192if t.TYPE_CHECKING:193 # on Python 3.10 this will raise a TypeError194195 class FuncParamTypeInfoDict(196 ParamTypeInfoDict,197 t.Generic[_ValueT_contra, _ValueT_co],198 ):199 func: t.Callable[[_ValueT_contra], _ValueT_co]200else:201191class 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]204205206class FuncParamType(ParamType[_ValueT_co], t.Generic[_ValueT_contra, _ValueT_co]):207 name: str208 func: t.Callable[[_ValueT_contra], _ValueT_co]209210 def __init__(self, func: t.Callable[[_ValueT_contra], _ValueT_co]) -> None:211 self.name = func.__name__212 self.func = func213196 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()}216217 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 line
225 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")230231 self.fail(message, param, ctx)232233234class UnprocessedParamType(ParamType[t.Any]):235 name = "text"236237 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 value241242 def __repr__(self) -> str:243 return "UNPROCESSED"
7 unmodified lines
251 ) -> 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)266267 def __repr__(self) -> str:268 return "STRING"269270254class ChoiceInfoDict(ParamTypeInfoDict):255 choices: cabc.Sequence[t.Any]256 case_sensitive: bool271if t.TYPE_CHECKING:272 # on Python 3.10 this will raise a TypeError273274 class ChoiceInfoDict(ParamTypeInfoDict, t.Generic[_ValueT_co]):275 choices: tuple[_ValueT_co, ...]276 case_sensitive: bool277else:278259class Choice(ParamType[ParamTypeValue], t.Generic[ParamTypeValue]):279 class ChoiceInfoDict(ParamTypeInfoDict):280 choices: tuple[t.Any, ...]281 case_sensitive: bool282283284class 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.287288 You may pass any iterable value which will be converted to a tuple
19 unmodified lines
308 .. versionadded:: 8.2.0309 Choice normalization can be overridden via :meth:`normalize_choice`.310 """311287 name = "choice"312 name: str = "choice"313314 choices: tuple[_ValueT_co, ...]315 case_sensitive: bool316317 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_sensitive322295 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 }329330 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 lines
344 )345 for choice in self.choices346 }347320 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 lines
365366 return normed_value367368 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 lines
394 )395396 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 lines
483 """484485 name = "datetime"486487 formats: cabc.Sequence[str]488489 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 ]495496 def to_info_dict(self) -> DateTimeInfoDict:497 return {"formats": self.formats, **super().to_info_dict()}498469 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)}]"501502 def _try_to_convert_date(self, value: t.Any, format: str) -> datetime | None:503 try:
27 unmodified lines
531 def __repr__(self) -> str:532 return "DateTime"533534505class _NumberParamTypeBase(ParamType[ParamTypeValue]):506 _number_class: t.Callable[[t.Any], ParamTypeValue]535class _NumberParamTypeBase(536 ParamType[_ValueT_co], t.Generic[_ValueT_contra, _ValueT_co]537):538 _number_class: t.Callable[[_ValueT_contra], _ValueT_co]539540 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 lines
551 ctx,552 )553554555if t.TYPE_CHECKING:556 # on Python 3.10 this will raise a TypeError557558 class NumberRangeInfoDict(ParamTypeInfoDict, t.Generic[_FloatValueT_co]):559 min: _FloatValueT_co | None560 max: _FloatValueT_co | None561 min_open: bool562 max_open: bool563 clamp: bool564else:565523class 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: bool572573574class _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: bool583530531class _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 lines
594 self.min_open = min_open595 self.max_open = max_open596 self.clamp = clamp597546 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 lines
605 **super().to_info_dict(),606 }607608 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 operator612613 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)622623 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)626627 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)629630 if lt_min or gt_max:631 self.fail(632 _("{value} is not in the range {range}.").format(
6 unmodified lines
639 return rv640641 @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.652653 :param bound: The boundary value.
20 unmodified lines
674 clamp = " clamped" if self.clamp else ""675 return f"<{type(self).__name__} {self._describe_range()}{clamp}>"676677621class IntParamType(_NumberParamTypeBase[int]):678class IntParamType(_NumberParamTypeBase[t.SupportsInt | t.SupportsIndex, int]):679 name = "integer"680 _number_class = int681682 def __repr__(self) -> str:683 return "INT"684685629class IntRange(_NumberRangeBase[int], IntParamType):686class IntRange(_NumberRangeBase[int, int], IntParamType):687 """Restrict an :data:`click.INT` value to a range of accepted688 values. See :ref:`ranges`.689690 If ``min`` or ``max`` are not passed, any value is accepted in that
15 unmodified lines
706707 return bound + dir708709653class FloatParamType(_NumberParamTypeBase[float]):710class FloatParamType(_NumberParamTypeBase[t.SupportsFloat | t.SupportsIndex, float]):711 name = "float"712 _number_class = float713714 def __repr__(self) -> str:715 return "FLOAT"716717661class FloatRange(_NumberRangeBase[float], FloatParamType):718class FloatRange(_NumberRangeBase[float, float], FloatParamType):719 """Restrict a :data:`click.FLOAT` value to a range of accepted720 values. See :ref:`ranges`.721722 If ``min`` or ``max`` are not passed, any value is accepted in that
107 unmodified lines
830class UUIDParameterType(ParamType[uuid.UUID]):831 name = "uuid"832833 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 lines
886887 name = "filename"888 envvar_list_splitter: t.ClassVar[str] = os.path.pathsep889890 mode: str891 encoding: str | None892 errors: str | None893 lazy: bool | None894 atomic: bool895896 def __init__(897 self,898 mode: str = "r",899 encoding: str | None = None,
31 unmodified lines
931 ) -> t.IO[t.Any]:932 if _is_file_like(value):933 return value934872 value = t.cast("str | os.PathLike[str]", value)873935 try:936 lazy = self.resolve_lazy_flag(value)937938 if lazy:
45 unmodified lines
984985 return [CompletionItem(incomplete, type="file")]986987927def _is_file_like(value: t.Any) -> te.TypeGuard[t.IO[t.Any]]:988def _is_file_like(value: t.Any) -> te.TypeIs[t.IO[t.Any]]:989 return hasattr(value, "read") or hasattr(value, "write")990991992class PathInfoDict(ParamTypeInfoDict):
39 unmodified lines
1032 """10331034 envvar_list_splitter: t.ClassVar[str] = os.path.pathsep10351036 exists: bool1037 file_okay: bool1038 dir_okay: bool1039 readable: bool1040 writable: bool1041 executable: bool1042 resolve_path: bool1043 allow_dash: bool1044 name: str10451046 def __init__(1047 self,1048 exists: bool = False,1049 file_okay: bool = True,
1 unmodified line
1051 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_type10671068 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 lines
128112821283@t.overload1284def convert_type(ty: None, default: None = None) -> StringParamType: ...121412151285@t.overload1286def 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]: ...122012211289@t.overload1290def convert_type(1291 ty: t.Any | None, default: t.Any | None = None1292) -> ParamType[t.Any]: ...122612271293def 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 Python
47 unmodified lines
1344#: there are situations where an unprocessed type is useful which is why1345#: it is provided.1346#:1347#: .. versionadded:: 4.01283UNPROCESSED = UnprocessedParamType()1348UNPROCESSED: t.Final[UnprocessedParamType] = UnprocessedParamType()13491350#: A unicode string parameter type which is the implicit default. This1351#: can also be selected by using ``str`` as type.1287STRING = StringParamType()1352STRING: t.Final[StringParamType] = StringParamType()13531354#: An integer parameter. This can also be selected by using ``int`` as1355#: type.1291INT = IntParamType()1356INT: t.Final[IntParamType] = IntParamType()13571358#: A floating point value parameter. This can also be selected by using1359#: ``float`` as type.1295FLOAT = FloatParamType()1360FLOAT: t.Final[FloatParamType] = FloatParamType()13611362#: A boolean parameter. This is the default for boolean flags. This can1363#: also be selected by using ``bool`` as a type.1299BOOL = BoolParamType()1364BOOL: t.Final[BoolParamType] = BoolParamType()13651366#: A UUID parameter.1302UUID = UUIDParameterType()1367UUID: t.Final[UUIDParameterType] = UUIDParameterType()136813691370class OptionHelpExtra(t.TypedDict, total=False):1371 envvars: tuple[str, ...]
3 unmodified lines
modified:src/click/utils.py+12 added
202 unmodified lines
203 return iter(self._f) # type: ignore204205206class KeepOpenFile:207 """Proxy a file object but keep it open across a ``with`` block.208209 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.213214 Dunder methods are proxied explicitly: implicit special-method lookups215 bypass :meth:`__getattr__`, because Python resolves them on the type rather216 than the instance.217 """218219 _file: t.IO[t.Any]220221 def __init__(self, file: t.IO[t.Any]) -> None:222 self._file = file
425 unmodified lines
modified:tests/test_stream_lifecycle.py+3 added-1 removed
482 unmodified lines
483# ---------------------------------------------------------------------------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# ---------------------------------------------------------------------------491492493@pytest.mark.stress
47 unmodified lines
modified:tests/test_termui.py+94 added
1import contextlib2import gc3import io4import platform5import shlex6import shutil
719 unmodified lines
726 assert err == ""727 assert out == expected728729730def 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 = []735736 class RecordingStream(io.StringIO):737 def __init__(self):738 super().__init__()739 self.color = None740741 def write(self, s):742 calls.append("write")743 return super().write(s)744745 def flush(self):746 calls.append("flush")747748 stream = RecordingStream()749 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: False)750 monkeypatch.setattr(click._termui_impl, "_default_text_stdout", lambda: stream)751752 def generate():753 yield "a\n"754 yield "b\n"755 yield "c\n"756757 click.echo_via_pager(generate())758759 # 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"766767768def 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 lines
806807 assert pager_out.read_text(encoding="utf-8") == "hello\n"808809810def test_get_pager_file_missing_pager_keeps_borrowed_stream_open(monkeypatch):811 """A missing ``PAGER`` must not close the borrowed stdout (issue #3449).812813 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")819820 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)827828 with click.get_pager_file() as pager:829 pager.write("hello\n")830831 # 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()836837 assert not buffer.closed838 assert not stream.closed839 assert buffer.getvalue().replace(b"\r\n", b"\n") == b"hello\n"840841842def test_echo_via_pager_tty_pager_missing(runner, monkeypatch):843 """``echo_via_pager`` through the tty fallback keeps ``CliRunner`` working.844845 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 )855856 @click.command()857 def cli():858 click.echo_via_pager("Hello, Click!")859860 result = runner.invoke(cli)861 assert not result.exception862 assert result.output == "Hello, Click!\n"863864865@pytest.mark.parametrize(866 ("color", "expected"),867 [868 pytest.param(False, "hello\n", id="strip ansi"),
694 unmodified lines
modified:tests/test_types.py+15 added-6 removed
241 unmodified lines
242 click.File(mode="r", lazy=True),243 ],244)245def test_file_surrogates(type, tmp_path):246 path = tmp_path / "\udcff"246 """Ensures that the error handling in ``click.File`` is robust.247248 # - 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``.250251 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)264265
20 unmodified lines
modified:tests/test_utils.py+74 added-5 removed
14 unmodified lines
15import pytest1617import click._termui_impl18import click.utils19from click._compat import MAC19from click._compat import WIN20from click._utils import UNSET2122
261 unmodified lines
284 yield "abc"285286287def _test_gen_func_fails():288 raise RuntimeError("This is a test.")289 yield # unreachable, keeps this a generator function290291292def _test_gen_func_yields_then_fails():293 yield "test"294 raise RuntimeError("This is a test.")295296
21 unmodified lines
318)319320321@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 lines
455 f"Unexpected stderr in test case '{test.description}'"456 )457458459@pytest.mark.skipif(WIN, reason="Different behavior on windows.")460def 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.463464 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)471472 writes: list[str] = []473 real_write = click._termui_impl.MaybeStripAnsi.write474475 def spy(self, text):476 writes.append(text)477 return real_write(self, text)478479 monkeypatch.setattr(click._termui_impl.MaybeStripAnsi, "write", spy)480481 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())488489 assert "".join(writes) == "test", (490 f"click should have written the yielded chunk before exception, got {writes!r}"491 )492493494@pytest.mark.stress495@pytest.mark.skipif(WIN, reason="Different behavior on windows.")496@pytest.mark.parametrize("_", range(1000))497def test_stress_echo_via_pager_exception_cleanup(_, monkeypatch, tmp_path):498 """Repeated exceptions during ``echo_via_pager`` must not leak subprocesses.499500 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)506507 spawned: list[subprocess.Popen] = []508 real_popen = subprocess.Popen509510 def tracking_popen(*args, **kwargs):511 p = real_popen(*args, **kwargs)512 spawned.append(p)513 return p514515 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())522523 assert spawned, "pager subprocess was never started"524 for p in spawned:525 assert p.returncode is not None, "pager subprocess not reaped"526527528def test_echo_color_flag(monkeypatch, capfd):529 isatty = True530 monkeypatch.setattr(click._compat, "isatty", lambda x: isatty)531
326 unmodified lines
modified:CHANGES.md+15 added-6 removed
18 unmodified lines
19 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`3031## Version 8.4.13233Released 2026-05-213435- `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`4445## Version 8.4.04647Released 2026-05-17
46 unmodified lines
94 {pr}`2969`9596- 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`99100- Fix Fish shell completion errors when option help text contains newlines.101 {issue}`3043` {pr}`3126`102
1463 unmodified lines
modified:pyproject.toml+1 added-2 removed
174 unmodified lines
175 {replace = "posargs", default = [], extend = true},176]]177178[tool.tox.env.stress]179description = "stress tests for stream lifecycle race conditions"179description = "high-iteration stress tests for race conditions"180commands = [[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]]186187[tool.tox.env.style]
44 unmodified lines