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
Provenance
- Commit
bc36cd1- Tree
f5b8f1e- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent 1
dbf4d14- Parent 2
a42300a
18 files changed+338 added−41 removed
modified:docs/advanced.md+12 added-2 removed
142 unmodified lines143 if fp is not None:144 click.echo(f"{url}: {fp.code}")145 146 In this case the callback returns the URL unchanged but also passes a147-second `fp` value to the callback. What's more recommended is to pass148-the information in a wrapper, however:147+second `fp` value to the callback.148 149+.. caution::150+151+ 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.157+158+What's more recommended is to pass the information in a wrapper, however:159+160 .. click:example::161 162 import urllib163 262 unmodified linesmodified:docs/api.md+4 added
282 unmodified lines283 .. autoexception:: FileError284 ```285 286 ```{eval-rst}287+.. autoexception:: NoSuchCommand288+```289+290+```{eval-rst}291 .. autoexception:: NoSuchOption292 ```293 294 ```{eval-rst}67 unmodified linesmodified:docs/options.md+7 added-1 removed
561 unmodified lines562 ##### Arbitration rules563 564 When several options in a group resolve their values simultaneously, only one565 wins the parameter slot. The full arbitration policy (source precedence,566-explicit-beats-auto tie-break, first-declared fallback) is enumerated under566+explicit-beats-auto tie-break, last-declared fallback) is enumerated under567 [Option value resolution](#option-value-resolution).568 569 ## Option value resolution570 49 unmodified lines620 The first source that produces a value wins. Environment variables and621 `default_map` entries set to `Sentinel.UNSET` are skipped, so they fall through622 to the next source rather than supplying `UNSET` to the function.623 624+If after the four sources above no explicit value was found (or only a625+`default_map`/`default` value was) and the option declares `prompt=`, Click626+prompts the user for one. The resulting value is recorded as627+{attr}`ParameterSource.PROMPT`, which ranks above every source listed above628+for arbitration purposes (see [Slot arbitration](#slot-arbitration)).629+630 ### Slot arbitration631 632 Several options can target the same `name` to form a feature switch group. When633 they do, only one option's value reaches the function. Arbitration applies167 unmodified linesmodified:src/click/_termui_impl.py+22 added-2 removed
604 unmodified lines605 finally:606 os.unlink(f.name)607 608 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+624 @contextlib.contextmanager625 def _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)633+634 if color is None:635 color = False617- yield stream, encoding, color636 637+ yield _SkipClose(stream), encoding, color # type: ignore[misc]638 639+640 class Editor:641 def __init__(642 self,643 editor: str | None = None,286 unmodified linesmodified:src/click/core.py+13 added-6 removed
2607 unmodified lines2608 2609 with augment_usage_errors(ctx, param=self):2610 value, source = self.consume_value(ctx, opts)2611 2612+ # 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)2616+2617 # Display a deprecation warning if necessary.2618 if (2619 self.deprecated2620 and value is not UNSET37 unmodified lines2658 or (same_source and not auto_would_downgrade_explicit)2659 )2660 2661 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``.2672 2673 return value, args2674 2675 def get_help_record(self, ctx: Context) -> tuple[str, str] | None:81 unmodified lines2757 :param help: the help string.2758 :param hidden: hide this option from help outputs.2759 :param attrs: Other command arguments described in :class:`Parameter`.2760 2754- .. 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 linesmodified:src/click/exceptions.py+4 added-1 removed
247 unmodified lines248 return f"{self.message} {_format_possibilities(self.possibilities)}"249 250 251 class 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.253 254+ .. versionadded:: 8.4.0255+ """256+257 def __init__(258 self,259 command_name: str,260 message: str | None = None,87 unmodified linesmodified:src/click/formatting.py+1 added-1 removed
51 unmodified lines52 each consecutive line.53 :param preserve_paragraphs: if this flag is set then the wrapping will54 intelligently handle paragraphs.55 56- .. 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 linesmodified:src/click/shell_completion.py+1 added-1 removed
421 unmodified lines422 return args, incomplete423 424 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 literal250 unmodified linesmodified:src/click/termui.py+1 added-1 removed
303 unmodified lines304 """Context manager.305 306 Yields a writable file-like object which can be used as an output pager.307 308- .. versionadded:: 8.2308+ .. versionadded:: 8.4.0309 310 :param color: controls if the pager supports ANSI colors or not. The311 default is autodetection.312 """629 unmodified linesmodified:src/click/types.py+11 added
48 unmodified lines49 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.53+54+ .. 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 """60 61 is_composite: t.ClassVar[bool] = False62 arity: t.ClassVar[int] = 1206 unmodified lines269 270 :param case_sensitive: Set to false to make choices case271 insensitive. Defaults to true.272 273+ .. 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.277+278 .. 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 linesmodified:src/click/utils.py+8 added-8 removed
230 unmodified lines231 return iter(self._file)232 233 234 def 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 lines286 # pythonw on Windows.287 if file is None:288 return289 290- # 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)297 298 if nl:297- out = out or ""299 if isinstance(out, str):300 out += "\n"301 else:302 out += b"\n"7 unmodified lines310 # 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)313-314 if binary_file is not None:315 file.flush()316 binary_file.write(out)317 binary_file.flush()324 unmodified linesmodified:tests/test_defaults.py+150 added
1+import os2+3 import pytest4 5 import click6 from click import UNPROCESSED7 from click._utils import UNSET8+from click.core import ParameterSource9 10 11 @pytest.mark.parametrize(12 ("default", "type", "expected_output", "expected_type"),254 unmodified lines267 assert f"name={expected_value!r}" in result.output268 assert f"source={expected_source}" in result.output269 270 271+def test_parameter_source_during_paramtype_convert(runner):272+ """``get_parameter_source()`` is available during ``ParamType.convert``.273+274+ Uses the reproducer from https://github.com/pallets/click/issues/3458.275+ """276+277+ class Source(click.ParamType):278+ name = "source"279+280+ def convert(self, value, param, ctx):281+ return {282+ "value": value,283+ "source": ctx.get_parameter_source(param.name),284+ }285+286+ @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}")292+293+ 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+ )301+302+ 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+ )312+313+314+def test_parameter_source_during_eager_callback(runner):315+ """``get_parameter_source()`` is available during eager callbacks.316+317+ Regression test for https://github.com/pallets/click/issues/3458.318+ """319+320+ 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}")323+324+ @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}")335+336+ result = runner.invoke(cli, [])337+ assert not result.exception338+ assert "callback source=DEFAULT" in result.output339+ assert "final source=DEFAULT" in result.output340+341+ result = runner.invoke(cli, ["--flag"])342+ assert not result.exception343+ assert "callback source=COMMANDLINE" in result.output344+ assert "final source=COMMANDLINE" in result.output345+346+347+def test_flask_debug_env_not_stomped_by_default_flag(runner, monkeypatch):348+ """Eager callback must not overwrite env when the flag used its default.349+350+ Covers the Flask ``_set_debug`` pattern (pallets/flask#6025). Regression test351+ for https://github.com/pallets/click/issues/3458.352+ """353+354+ monkeypatch.delenv("APP_DEBUG", raising=False)355+356+ 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 value365+366+ @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', '')}")376+377+ monkeypatch.setenv("APP_DEBUG", "1")378+ result = runner.invoke(cli, [])379+ assert result.exit_code == 0380+ assert result.output.strip() == "APP_DEBUG=1"381+382+ result = runner.invoke(cli, ["--debug"])383+ assert result.exit_code == 0384+ assert result.output.strip() == "APP_DEBUG=1"385+386+ result = runner.invoke(cli, ["--no-debug"])387+ assert result.exit_code == 0388+ assert result.output.strip() == "APP_DEBUG=0"389+390+391+def 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``.394+395+ 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+ """399+400+ def hijack(ctx, param, value):401+ ctx.params["target"] = "hijacked"402+ return value403+404+ @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'}")411+412+ 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.output416+417+418 def 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 linesmodified:tests/test_options.py+62 added
2894 unmodified lines2895 assert result.output == repr(expected)2896 2897 2898 @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+)2937+def 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.2941+2942+ Regression test for https://github.com/pallets/click/issues/3458.2943+ """2944+2945+ @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}")2950+2951+ for opt_name, opt_kwargs in opts:2952+ cli = click.option(opt_name, "enable_xyz", **opt_kwargs)(cli)2953+2954+ 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.output2958+2959+2960+@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 default539 unmodified linesmodified:tests/test_termui.py+4 added-10 removed
796 unmodified lines797 798 def test_get_pager_file_nullpager_keeps_stringio_stream(monkeypatch):799 """The no-stdout fallback should keep a text-only stream and set ``.color``."""800 801- created = []802-803- def make_stringio():804- stream = io.StringIO()801+ stream = io.StringIO()805- created.append(stream)806- return stream807-802 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)805 806 styled_text = click.style("hello", fg="red")807 808 with click.get_pager_file(color=False) as pager:815- assert pager is created[0]809 pager.write(styled_text)810 811+ assert not stream.closed818- assert created[0].getvalue() == styled_text812+ assert stream.getvalue() == styled_text813 814 815 def test_get_pager_file_flushes_stream_on_exception(monkeypatch):816 """Exceptions should still flush the yielded stream in ``finally``."""652 unmodified linesmodified:tests/test_testing.py+11 added
254 unmodified lines255 assert not result.exception256 assert result.output == ""257 258 259+def test_with_echo_via_pager():260+ @click.command()261+ def cli():262+ click.echo_via_pager("Hello, Click!")263+264+ runner = CliRunner()265+ result = runner.invoke(cli)266+ assert not result.exception267+ assert result.output == "Hello, Click!\n"268+269+270 def test_exit_code_and_output_from_sys_exit():271 # See issue #362272 @click.command()273 def cli_string():487 unmodified linesmodified:tests/test_utils.py+6 added-1 removed
6 unmodified lines7 from contextlib import nullcontext8 from decimal import Decimal9 from fractions import Fraction10 from functools import partial11+from io import BytesIO12 from io import StringIO13 from unittest.mock import patch14 15 import pytest81 unmodified lines97 f = StringIO()98 click.echo("hello", file=f)99 assert f.getvalue() == "hello\n"100 101+ b = BytesIO()102+ click.echo(b"", b)103+ assert b.getvalue() == b"\n"104 105+106 def 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 = None205 unmodified lines315 316 317 @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 linesmodified:CHANGES.rst+16 added-7 removed
4 unmodified lines5 6 Unreleased7 8 9-Version 8.4.19+Version 8.4.210 -------------11 12 Unreleased13 14+15+Version 8.4.116+-------------17+18+Released 2026-05-2119+20+- ``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`27 28 Version 8.4.029 -------------30 32 unmodified lines63 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 lines80 - 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 separator7 unmodified lines96 (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``-level1387 unmodified linesmodified:pyproject.toml+5 added
138 unmodified lines139 "F", # pyflakes140 "I", # isort141 "UP", # pyupgrade142 "W", # pycodestyle warning143+ "ICN", #flake8-import-conventions (ICN)144 ]145 146+[tool.ruff.lint.flake8-import-conventions.aliases]147+# Declare the default aliases.148+typing = "t"149+150 [tool.ruff.lint.isort]151 force-single-line = true152 order-by-type = false153 88 unmodified lines