Skip to content
Myr

Merge branch 'stable'

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

authored by David Lord · committed by David Lord · parents dbf4d14, a42300a · Browse files · 18 files+338 added−41 removed
This commit

State

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

Diff stats

18 files+338 added−41 removed

  • tests:+233 added−11 removed
  • other:+105 added−30 removed

18 files+338 added−41 removed

modified:docs/advanced.md+12 added-2 removed
142 unmodified lines
143 if fp is not None:144 click.echo(f"{url}: {fp.code}")145146In this case the callback returns the URL unchanged but also passes a147second `fp` value to the callback. What's more recommended is to pass148the information in a wrapper, however:147second `fp` value to the callback.148149.. caution::150151 Writing to :attr:`~click.Context.params` directly bypasses Click's152 per-parameter pipeline: :meth:`~click.Context.get_parameter_source` returns153 ``None`` for it, the value is never run through any :class:`~click.ParamType`154 conversion. And if the key collides with a declared parameter, then the155 shared-name arbitration loses information about where the value came from.156 Prefer the wrapper pattern below when any of those semantics matter.157158What's more recommended is to pass the information in a wrapper, however:159160.. click:example::161162 import urllib163
262 unmodified lines
modified:docs/api.md+4 added
282 unmodified lines
283.. autoexception:: FileError284```285286```{eval-rst}287.. autoexception:: NoSuchCommand288```289290```{eval-rst}291.. autoexception:: NoSuchOption292```293294```{eval-rst}
67 unmodified lines
modified:docs/options.md+7 added-1 removed
561 unmodified lines
562##### Arbitration rules563564When several options in a group resolve their values simultaneously, only one565wins the parameter slot. The full arbitration policy (source precedence,566explicit-beats-auto tie-break, first-declared fallback) is enumerated under566explicit-beats-auto tie-break, last-declared fallback) is enumerated under567[Option value resolution](#option-value-resolution).568569## Option value resolution570
49 unmodified lines
620The first source that produces a value wins. Environment variables and621`default_map` entries set to `Sentinel.UNSET` are skipped, so they fall through622to the next source rather than supplying `UNSET` to the function.623624If after the four sources above no explicit value was found (or only a625`default_map`/`default` value was) and the option declares `prompt=`, Click626prompts the user for one. The resulting value is recorded as627{attr}`ParameterSource.PROMPT`, which ranks above every source listed above628for arbitration purposes (see [Slot arbitration](#slot-arbitration)).629630### Slot arbitration631632Several options can target the same `name` to form a feature switch group. When633they do, only one option's value reaches the function. Arbitration applies
167 unmodified lines
modified:src/click/_termui_impl.py+22 added-2 removed
604 unmodified lines
605 finally:606 os.unlink(f.name)607608609class _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 pass622623624@contextlib.contextmanager625def _nullpager(626 stream: t.TextIO, color: bool | None = None627) -> t.Iterator[tuple[t.TextIO, str, bool]]:613 """Simply print unformatted text. This is the ultimate fallback."""628 """Simply print unformatted text. This is the ultimate fallback. Don't close the629 output stream in this case, since it's coming from elsewhere rather than our630 internal helpers.631 """632 encoding = get_best_encoding(stream)633634 if color is None:635 color = False617 yield stream, encoding, color636637 yield _SkipClose(stream), encoding, color # type: ignore[misc]638639640class Editor:641 def __init__(642 self,643 editor: str | None = None,
286 unmodified lines
modified:src/click/core.py+13 added-6 removed
2607 unmodified lines
26082609 with augment_usage_errors(ctx, param=self):2610 value, source = self.consume_value(ctx, opts)26112612 # Record the source before processing so eager callbacks and type2613 # conversion can inspect it. Restored after arbitration if this2614 # option loses a feature-switch group.2615 ctx.set_parameter_source(self.name, source)26162617 # Display a deprecation warning if necessary.2618 if (2619 self.deprecated2620 and value is not UNSET
37 unmodified lines
2658 or (same_source and not auto_would_downgrade_explicit)2659 )26602661 if is_winner:2657 ctx.set_parameter_source(self.name, source)2662 if self.expose_value:2663 ctx.params[self.name] = value2664 ctx._param_default_explicit[self.name] = self._default_explicit2661 elif existing_source is None:2662 # Nothing has claimed the slot yet. Record at least our source so downstream2663 # lookups don't return ``None``.2664 ctx.set_parameter_source(self.name, source)2665 elif existing_source is not None:2666 # Lost arbitration; restore the winning option's source.2667 ctx.set_parameter_source(self.name, existing_source)2668 # else: ctx.params[self.name] was populated by code that bypassed2669 # handle_parse_result (from another option's callback for example). Keep2670 # the provisional source recorded before process_value so downstream2671 # lookups don't return ``None``.26722673 return value, args26742675 def get_help_record(self, ctx: Context) -> tuple[str, str] | None:
81 unmodified lines
2757 :param help: the help string.2758 :param hidden: hide this option from help outputs.2759 :param attrs: Other command arguments described in :class:`Parameter`.27602754 .. versionchanged:: 8.42761 .. versionchanged:: 8.4.02762 Non-basic ``flag_value`` types (not ``str``, ``int``, ``float``, or2763 ``bool``) are passed through unchanged instead of being stringified.2764 Previously, ``type=click.UNPROCESSED`` was required to preserve them.2765
777 unmodified lines
modified:src/click/exceptions.py+4 added-1 removed
247 unmodified lines
248 return f"{self.message} {_format_possibilities(self.possibilities)}"249250251class NoSuchCommand(UsageError):252 """Raised if Click attempted to handle a command that does not exist."""252 """Raised if Click attempted to handle a command that does not exist.253254 .. versionadded:: 8.4.0255 """256257 def __init__(258 self,259 command_name: str,260 message: str | None = None,
87 unmodified lines
modified:src/click/formatting.py+1 added-1 removed
51 unmodified lines
52 each consecutive line.53 :param preserve_paragraphs: if this flag is set then the wrapping will54 intelligently handle paragraphs.5556 .. versionchanged:: 8.456 .. versionchanged:: 8.4.057 Width is measured in visible characters. ANSI escape sequences in58 ``text``, ``initial_indent``, or ``subsequent_indent`` no longer59 count toward the width budget, so styled input wraps based on what60 the user sees instead of raw byte length.
255 unmodified lines
modified:src/click/shell_completion.py+1 added-1 removed
421 unmodified lines
422 return args, incomplete423424 def format_completion(self, item: CompletionItem) -> str:425 """426 .. versionchanged:: 8.4426 .. versionchanged:: 8.4.0427 Escape newlines in value and help to fix completion errors with428 multi-line help strings.429 """430 # The fish completion script splits each response line on literal
250 unmodified lines
modified:src/click/termui.py+1 added-1 removed
303 unmodified lines
304 """Context manager.305306 Yields a writable file-like object which can be used as an output pager.307308 .. versionadded:: 8.2308 .. versionadded:: 8.4.0309310 :param color: controls if the pager supports ANSI colors or not. The311 default is autodetection.312 """
629 unmodified lines
modified:src/click/types.py+11 added
48 unmodified lines
49 type.50 - It must be able to convert a value if the ``ctx`` and ``param``51 arguments are ``None``. This can occur when converting prompt52 input.5354 .. versionchanged:: 8.4.055 Now a generic abstract base class. Parameterize with the56 converted value type (``ParamType[int]`` for an integer-returning57 type) so that :meth:`convert` and downstream consumers carry the58 narrowed return type.59 """6061 is_composite: t.ClassVar[bool] = False62 arity: t.ClassVar[int] = 1
206 unmodified lines
269270 :param case_sensitive: Set to false to make choices case271 insensitive. Defaults to true.272273 .. versionchanged:: 8.4.0274 Now generic in the choice value type. Parameterize with the type of275 the choice values (``Choice[HashType]`` for an enum, ``Choice[str]``276 for plain strings) to enable type-checked consumers.277278 .. versionchanged:: 8.2.0279 Non-``str`` ``choices`` are now supported. It can additionally be any280 iterable. Before you were not recommended to pass anything but a list or281 tuple.
1028 unmodified lines
modified:src/click/utils.py+8 added-8 removed
230 unmodified lines
231 return iter(self._file)232233234def echo(235 message: t.Any | None = None,235 message: object = None,236 file: t.IO[t.Any] | None = None,237 nl: bool = True,238 err: bool = False,239 color: bool | None = None,
46 unmodified lines
286 # pythonw on Windows.287 if file is None:288 return289290 # Convert non bytes/text into the native string type.291 if message is not None and not isinstance(message, (str, bytes, bytearray)):292 out: str | bytes | bytearray | None = str(message)293 else:294 out = message290 match message:291 case str() | bytes() | bytearray():292 out = message293 case None:294 out = ""295 case _:296 out = str(message)297298 if nl:297 out = out or ""299 if isinstance(out, str):300 out += "\n"301 else:302 out += b"\n"
7 unmodified lines
310 # This is done separately so that most stream types will work as you311 # would expect. Eg: you can write to StringIO for other cases.312 if isinstance(out, (bytes, bytearray)):313 binary_file = _find_binary_writer(file)313314 if binary_file is not None:315 file.flush()316 binary_file.write(out)317 binary_file.flush()
324 unmodified lines
modified:tests/test_defaults.py+150 added
1import os23import pytest45import click6from click import UNPROCESSED7from click._utils import UNSET8from click.core import ParameterSource91011@pytest.mark.parametrize(12 ("default", "type", "expected_output", "expected_type"),
254 unmodified lines
267 assert f"name={expected_value!r}" in result.output268 assert f"source={expected_source}" in result.output269270271def test_parameter_source_during_paramtype_convert(runner):272 """``get_parameter_source()`` is available during ``ParamType.convert``.273274 Uses the reproducer from https://github.com/pallets/click/issues/3458.275 """276277 class Source(click.ParamType):278 name = "source"279280 def convert(self, value, param, ctx):281 return {282 "value": value,283 "source": ctx.get_parameter_source(param.name),284 }285286 @click.command()287 @click.option("--default", type=Source(), default="/tmp/file")288 @click.option("--nodefault", type=Source())289 def cli(default, nodefault):290 click.echo(f"default: {default}")291 click.echo(f"nodefault: {nodefault}")292293 result = runner.invoke(cli, [])294 assert not result.exception295 assert "default: {'value': '/tmp/file', 'source': " in result.output296 assert "'source': None}" not in result.output.split("default:")[1].split("\n")[0]297 assert (298 result.output == "default: {'value': '/tmp/file', 'source': "299 f"{ParameterSource.DEFAULT!r}}}\nnodefault: None\n"300 )301302 result = runner.invoke(cli, ["--default", "cli", "--nodefault", "also"])303 assert not result.exception304 assert (305 "default: {'value': 'cli', 'source': "306 f"{ParameterSource.COMMANDLINE!r}}}" in result.output307 )308 assert (309 "nodefault: {'value': 'also', 'source': "310 f"{ParameterSource.COMMANDLINE!r}}}" in result.output311 )312313314def test_parameter_source_during_eager_callback(runner):315 """``get_parameter_source()`` is available during eager callbacks.316317 Regression test for https://github.com/pallets/click/issues/3458.318 """319320 def eager_cb(ctx, param, value):321 source = ctx.get_parameter_source(param.name)322 click.echo(f"callback source={source.name if source else None}")323324 @click.command()325 @click.option(326 "--flag/--no-flag",327 default=False,328 is_eager=True,329 callback=eager_cb,330 expose_value=False,331 )332 def cli():333 source = click.get_current_context().get_parameter_source("flag")334 click.echo(f"final source={source.name}")335336 result = runner.invoke(cli, [])337 assert not result.exception338 assert "callback source=DEFAULT" in result.output339 assert "final source=DEFAULT" in result.output340341 result = runner.invoke(cli, ["--flag"])342 assert not result.exception343 assert "callback source=COMMANDLINE" in result.output344 assert "final source=COMMANDLINE" in result.output345346347def test_flask_debug_env_not_stomped_by_default_flag(runner, monkeypatch):348 """Eager callback must not overwrite env when the flag used its default.349350 Covers the Flask ``_set_debug`` pattern (pallets/flask#6025). Regression test351 for https://github.com/pallets/click/issues/3458.352 """353354 monkeypatch.delenv("APP_DEBUG", raising=False)355356 def set_debug(ctx, param, value):357 source = ctx.get_parameter_source(param.name)358 if source is not None and source in (359 ParameterSource.DEFAULT,360 ParameterSource.DEFAULT_MAP,361 ):362 return None363 os.environ["APP_DEBUG"] = "1" if value else "0"364 return value365366 @click.command()367 @click.option(368 "--debug/--no-debug",369 default=False,370 is_eager=True,371 expose_value=False,372 callback=set_debug,373 )374 def cli():375 click.echo(f"APP_DEBUG={os.environ.get('APP_DEBUG', '')}")376377 monkeypatch.setenv("APP_DEBUG", "1")378 result = runner.invoke(cli, [])379 assert result.exit_code == 0380 assert result.output.strip() == "APP_DEBUG=1"381382 result = runner.invoke(cli, ["--debug"])383 assert result.exit_code == 0384 assert result.output.strip() == "APP_DEBUG=1"385386 result = runner.invoke(cli, ["--no-debug"])387 assert result.exit_code == 0388 assert result.output.strip() == "APP_DEBUG=0"389390391def test_parameter_source_on_parse_result_bypass(runner):392 """A losing option keeps its provisional source when ``ctx.params[name]``393 is populated by code that bypassed ``handle_parse_result``.394395 This replicate the pattern documented in the "Parameter Modifications" section396 of ``docs/advanced.md``. This test highlight the current behavior of397 ``get_parameter_source()`` but is not intended as a contract enforcement.398 """399400 def hijack(ctx, param, value):401 ctx.params["target"] = "hijacked"402 return value403404 @click.command()405 @click.option("--hijacker", is_eager=True, callback=hijack, expose_value=False)406 @click.option("--target", default="default_value")407 @click.pass_context408 def cli(ctx, target):409 source = ctx.get_parameter_source("target")410 click.echo(f"value={target} source={source.name if source else 'None'}")411412 result = runner.invoke(cli, ["--hijacker", "anything"])413 assert result.exit_code == 0, result.output414 assert "value=hijacked" in result.output415 assert "source=DEFAULT" in result.output416417418def test_lookup_default_override_respected(runner):419 """A subclass override of ``lookup_default()`` should be called by Click420 internals, not bypassed by a private method.421
142 unmodified lines
modified:tests/test_options.py+62 added
2894 unmodified lines
2895 assert result.output == repr(expected)289628972898@pytest.mark.parametrize(2899 ("opts", "args", "invoke_kwargs", "expected_value", "expected_source"),2900 [2901 # https://github.com/pallets/click/issues/34582902 pytest.param(2903 [2904 ("--without-xyz", {"flag_value": False}),2905 ("--with-xyz", {"flag_value": True, "default": True}),2906 ],2907 [],2908 {},2909 True,2910 "DEFAULT",2911 id="explicit-default-wins",2912 ),2913 pytest.param(2914 [2915 ("--without-xyz", {"flag_value": False}),2916 ("--with-xyz", {"flag_value": True, "default": True}),2917 ],2918 ["--without-xyz"],2919 {},2920 False,2921 "COMMANDLINE",2922 id="cmdline-wins",2923 ),2924 pytest.param(2925 [2926 ("--without-xyz", {"flag_value": False}),2927 ("--with-xyz", {"flag_value": True, "default": True}),2928 ],2929 ["--without-xyz"],2930 {"default_map": {"enable_xyz": True}},2931 False,2932 "COMMANDLINE",2933 id="loser-default-map-restores-winner-source",2934 ),2935 ],2936)2937def test_bool_flag_group_parameter_source(2938 runner, opts, args, invoke_kwargs, expected_value, expected_source2939):2940 """``get_parameter_source()`` stays correct for feature-switch groups.29412942 Regression test for https://github.com/pallets/click/issues/3458.2943 """29442945 @click.command()2946 @click.pass_context2947 def cli(ctx, enable_xyz):2948 source = ctx.get_parameter_source("enable_xyz")2949 click.echo(f"value={enable_xyz!r} source={source.name}")29502951 for opt_name, opt_kwargs in opts:2952 cli = click.option(opt_name, "enable_xyz", **opt_kwargs)(cli)29532954 result = runner.invoke(cli, args, **invoke_kwargs)2955 assert result.exit_code == 0, result.output2956 assert f"value={expected_value!r}" in result.output2957 assert f"source={expected_source}" in result.output295829592960@pytest.mark.parametrize(2961 ("opts", "args", "expected"),2962 [2963 # Non-boolean feature switch group: classic --upper/--lower2964 # pattern. The option with ``default=True`` acts as the default
539 unmodified lines
modified:tests/test_termui.py+4 added-10 removed
796 unmodified lines
797798def test_get_pager_file_nullpager_keeps_stringio_stream(monkeypatch):799 """The no-stdout fallback should keep a text-only stream and set ``.color``."""800801 created = []802803 def make_stringio():804 stream = io.StringIO()801 stream = io.StringIO()805 created.append(stream)806 return stream807802 monkeypatch.setattr(sys, "stdout", None)809 monkeypatch.setattr(click._termui_impl, "StringIO", make_stringio)803 monkeypatch.setattr(click._termui_impl, "StringIO", lambda: stream)804 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: False)805806 styled_text = click.style("hello", fg="red")807808 with click.get_pager_file(color=False) as pager:815 assert pager is created[0]809 pager.write(styled_text)810811 assert not stream.closed818 assert created[0].getvalue() == styled_text812 assert stream.getvalue() == styled_text813814815def test_get_pager_file_flushes_stream_on_exception(monkeypatch):816 """Exceptions should still flush the yielded stream in ``finally``."""
652 unmodified lines
modified:tests/test_testing.py+11 added
254 unmodified lines
255 assert not result.exception256 assert result.output == ""257258259def test_with_echo_via_pager():260 @click.command()261 def cli():262 click.echo_via_pager("Hello, Click!")263264 runner = CliRunner()265 result = runner.invoke(cli)266 assert not result.exception267 assert result.output == "Hello, Click!\n"268269270def test_exit_code_and_output_from_sys_exit():271 # See issue #362272 @click.command()273 def cli_string():
487 unmodified lines
modified:tests/test_utils.py+6 added-1 removed
6 unmodified lines
7from contextlib import nullcontext8from decimal import Decimal9from fractions import Fraction10from functools import partial11from io import BytesIO12from io import StringIO13from unittest.mock import patch1415import pytest
81 unmodified lines
97 f = StringIO()98 click.echo("hello", file=f)99 assert f.getvalue() == "hello\n"100101 b = BytesIO()102 click.echo(b"", b)103 assert b.getvalue() == b"\n"104105106def test_echo_no_streams(monkeypatch, runner):107 """echo should not fail when stdout and stderr are None with pythonw on Windows."""108 with runner.isolation():109 sys.stdout = None
205 unmodified lines
315316317@pytest.mark.skipif(WIN, reason="Different behavior on windows.")318@pytest.mark.skipif(314 MAC and sys.version_info >= (3, 13) and sys._is_gil_enabled(),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 "]
469 unmodified lines
modified:CHANGES.rst+16 added-7 removed
4 unmodified lines
56Unreleased789Version 8.4.19Version 8.4.210-------------1112Unreleased131415Version 8.4.116-------------1718Released 2026-05-211920- ``get_parameter_source()`` is available during eager callbacks and type21 conversion again. :issue:`3458` :issue:`3484`14- Zsh completion scripts parse correctly on Windows. :issue:`3277`22- Zsh completion scripts parse correctly on Windows. :issue:`3277` :pr:`3466`23- Shell completion of `Choice` `Enum` values produces a valid completion24 result. :issue:`3015`25- Fix empty byte-string handling in echo. :issue:`3487`26- Fix closed file error with `echo_via_pager`. :issue:`3449`2728Version 8.4.029-------------30
32 unmodified lines
63 instead of being stringified. Previously ``type=click.UNPROCESSED`` had64 to be set explicitly. :issue:`2012` :pr:`3363`65- The error hint now uses :meth:`Command.get_help_option_names` to pick66 non-shadowed help option names, so ``Try '... -h'`` no longer points to a57 subcommand option that shadows ``-h``. All surviving names are shown58 (``-h/--help``). :issue:`2790` :pr:`3208`67 subcommand option that shadows ``-h``. The longest surviving name is68 shown (``--help`` over ``-h``) for readability. :issue:`2790` :pr:`3208`69- Fix readline functionality on non-Windows platforms. Prompt text is now70 passed directly to readline instead of being printed separately, allowing71 proper backspace, line editing, and line wrapping behavior. :issue:`2968`72 :pr:`2969`
7 unmodified lines
80- Use :class:`ValueError` message when conversion in :class:`FuncParamType` would81 fail. :issue:`3105` :pr:`3211`82- Add ``click.get_pager_file`` for file-like access to an output83 pager. :pr:`1572` :pr:`3405`74- :class:`~click.formatting.TextWrapper` and75 :func:`~click.formatting.wrap_text` now measure line width in visible84- :func:`~click.formatting.wrap_text` now measures line width in visible85 characters, ignoring ANSI escape sequences. :pr:`3420`86- Fix :meth:`HelpFormatter.write_usage` emitting only a blank line when87 called without ``args``. The usage prefix and program name are now88 written even when no arguments follow, and the trailing separator
7 unmodified lines
96 (default) and ``fd``. ``fd`` redirects file descriptors ``1`` and ``2``97 via :func:`os.dup2` so output that bypasses ``sys.stdout`` (stale stream98 references, C extensions, subprocesses, ``faulthandler``) is captured99 with proper isolation. :issue:`854` :issue:`2412` :issue:`2468`91 :issue:`2497` :issue:`2761` :issue:`2827` :issue:`2865`100 :issue:`2497` :issue:`2761` :issue:`2827` :issue:`2865` :pr:`3391`101- Revert the ``8.3.3`` change that exposed the original file descriptor102 via ``fileno()`` on the redirected ``CliRunner`` streams in the default103 capture mode. ``os.dup2(w, sys.stdout.fileno())`` calls inside a CLI no104 longer mutate the host runner's stdout, which broke Pytest's ``fd``-level
1387 unmodified lines
modified:pyproject.toml+5 added
138 unmodified lines
139 "F", # pyflakes140 "I", # isort141 "UP", # pyupgrade142 "W", # pycodestyle warning143 "ICN", #flake8-import-conventions (ICN)144]145146[tool.ruff.lint.flake8-import-conventions.aliases]147# Declare the default aliases.148typing = "t"149150[tool.ruff.lint.isort]151force-single-line = true152order-by-type = false153
88 unmodified lines