Skip to content
Myr

Merge branch 'pallets:main' into main

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

authored by Rowlando13 · committed by GitHub · parents 2357253, 0e0c003 · Browse files · 7 files+256 added−98 removed
This commit

State

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

Diff stats

7 files+256 added−98 removed

  • tests:+83 added−33 removed
  • other:+173 added−65 removed

7 files+256 added−98 removed

modified:src/click/core.py+37 added-15 removed
2668 unmodified lines
2669 if self.secondary_opts:2670 rv.append(_write_opts(self.secondary_opts))26712672 help = self.help or ""2673 extra = []26732674 extra = self.get_help_extra(ctx)2675 extra_items = []2676 if "envvars" in extra:2677 extra_items.append(2678 _("env var: {var}").format(var=", ".join(extra["envvars"]))2679 )2680 if "default" in extra:2681 extra_items.append(_("default: {default}").format(default=extra["default"]))2682 if "range" in extra:2683 extra_items.append(extra["range"])2684 if "required" in extra:2685 extra_items.append(_(extra["required"]))26862687 if extra_items:2688 extra_str = "; ".join(extra_items)2689 help = f"{help} [{extra_str}]" if help else f"[{extra_str}]"26902691 return ("; " if any_prefix_is_slash else " / ").join(rv), help26922693 def get_help_extra(self, ctx: Context) -> types.OptionHelpExtra:2694 extra: types.OptionHelpExtra = {}26952696 if self.show_envvar:2697 envvar = self.envvar26982699 if envvar is None:
4 unmodified lines
2704 ):2705 envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}"27062707 if envvar is not None:2687 var_str = (2688 envvar2689 if isinstance(envvar, str)2690 else ", ".join(str(d) for d in envvar)2691 )2692 extra.append(_("env var: {var}").format(var=var_str))2708 if isinstance(envvar, str):2709 extra["envvars"] = (envvar,)2710 else:2711 extra["envvars"] = tuple(str(d) for d in envvar)27122713 # Temporarily enable resilient parsing to avoid type casting2714 # failing for the default. Might be possible to extend this to2715 # help formatting in general.
36 unmodified lines
2752 else:2753 default_string = str(default_value)27542755 if default_string:2737 extra.append(_("default: {default}").format(default=default_string))2756 extra["default"] = default_string27572758 if (2759 isinstance(self.type, types._NumberRangeBase)2760 # skip count with default range type
1 unmodified line
2762 ):2763 range_str = self.type._describe_range()27642765 if range_str:2747 extra.append(range_str)2766 extra["range"] = range_str27672768 if self.required:2750 extra.append(_("required"))2769 extra["required"] = "required"27702752 if extra:2753 extra_str = "; ".join(extra)2754 help = f"{help} [{extra_str}]" if help else f"[{extra_str}]"2771 return extra27722756 return ("; " if any_prefix_is_slash else " / ").join(rv), help27572773 @t.overload2774 def get_default(2775 self, ctx: Context, call: t.Literal[True] = True2776 ) -> t.Any | None: ...
34 unmodified lines
2811 # differently.2812 if self.is_bool_flag:2813 return confirm(self.prompt, default)28142815 # If show_default is set to True/False, provide this to `prompt` as well. For2816 # non-bool values of `show_default`, we use `prompt`'s default behavior2817 prompt_kwargs: t.Any = {}2818 if isinstance(self.show_default, bool):2819 prompt_kwargs["show_default"] = self.show_default28202821 return prompt(2822 self.prompt,2823 default=default,2824 type=self.type,2825 hide_input=self.hide_input,2826 show_choices=self.show_choices,2827 confirmation_prompt=self.confirmation_prompt,2828 value_proc=lambda x: self.process_value(ctx, x),2829 **prompt_kwargs,2830 )28312832 def resolve_envvar_value(self, ctx: Context) -> str | None:2833 rv = super().resolve_envvar_value(ctx)
169 unmodified lines
modified:src/click/testing.py+110 added-49 removed
16 unmodified lines
17from . import utils18from ._compat import _find_binary_reader1920if t.TYPE_CHECKING:21 from _typeshed import ReadableBuffer2223 from .core import Command242526class EchoingStdin:
39 unmodified lines
66 yield67 stream._paused = False686970class BytesIOCopy(io.BytesIO):71 """Patch ``io.BytesIO`` to let the written stream be copied to another.7273 .. versionadded:: 8.274 """7576 def __init__(self, copy_to: io.BytesIO) -> None:77 super().__init__()78 self.copy_to = copy_to7980 def flush(self) -> None:81 super().flush()82 self.copy_to.flush()8384 def write(self, b: ReadableBuffer) -> int:85 self.copy_to.write(b)86 return super().write(b)878889class StreamMixer:90 """Mixes `<stdout>` and `<stderr>` streams.9192 The result is available in the ``output`` attribute.9394 .. versionadded:: 8.295 """9697 def __init__(self) -> None:98 self.output: io.BytesIO = io.BytesIO()99 self.stdout: io.BytesIO = BytesIOCopy(copy_to=self.output)100 self.stderr: io.BytesIO = BytesIOCopy(copy_to=self.output)101102103class _NamedTextIOWrapper(io.TextIOWrapper):104 def __init__(105 self, buffer: t.BinaryIO, name: str, mode: str, **kwargs: t.Any106 ) -> None:
30 unmodified lines
137 return io.BytesIO(input)138139140class Result:106 """Holds the captured result of an invoked CLI script."""141 """Holds the captured result of an invoked CLI script.142143 :param runner: The runner that created the result144 :param stdout_bytes: The standard output as bytes.145 :param stderr_bytes: The standard error as bytes.146 :param output_bytes: A mix of ``stdout_bytes`` and ``stderr_bytes``, as the147 user would see it in its terminal.148 :param return_value: The value returned from the invoked command.149 :param exit_code: The exit code as integer.150 :param exception: The exception that happened if one did.151 :param exc_info: Exception information (exception type, exception instance,152 traceback type).153154 .. versionchanged:: 8.2155 ``stderr_bytes`` no longer optional, ``output_bytes`` introduced and156 ``mix_stderr`` has been removed.157158 .. versionadded:: 8.0159 Added ``return_value``.160 """161162 def __init__(163 self,164 runner: CliRunner,165 stdout_bytes: bytes,112 stderr_bytes: bytes | None,166 stderr_bytes: bytes,167 output_bytes: bytes,168 return_value: t.Any,169 exit_code: int,170 exception: BaseException | None,171 exc_info: tuple[type[BaseException], BaseException, TracebackType]172 | None = None,173 ):119 #: The runner that created the result174 self.runner = runner121 #: The standard output as bytes.175 self.stdout_bytes = stdout_bytes123 #: The standard error as bytes, or None if not available176 self.stderr_bytes = stderr_bytes125 #: The value returned from the invoked command.126 #:127 #: .. versionadded:: 8.0177 self.output_bytes = output_bytes178 self.return_value = return_value129 #: The exit code as integer.179 self.exit_code = exit_code131 #: The exception that happened if one did.180 self.exception = exception133 #: The traceback181 self.exc_info = exc_info182183 @property184 def output(self) -> str:138 """The (standard) output as unicode string."""139 return self.stdout185 """The terminal output as unicode string, as the user would see it.186187 .. versionchanged:: 8.2188 No longer a proxy for ``self.stdout``. Now has its own independent stream189 that is mixing `<stdout>` and `<stderr>`, in the order they were written.190 """191 return self.output_bytes.decode(self.runner.charset, "replace").replace(192 "\r\n", "\n"193 )194195 @property196 def stdout(self) -> str:197 """The standard output as unicode string."""198 return self.stdout_bytes.decode(self.runner.charset, "replace").replace(
1 unmodified line
200 )201202 @property203 def stderr(self) -> str:150 """The standard error as unicode string."""151 if self.stderr_bytes is None:152 raise ValueError("stderr not separately captured")204 """The standard error as unicode string.205206 .. versionchanged:: 8.2207 No longer raise an exception, always returns the `<stderr>` string.208 """209 return self.stderr_bytes.decode(self.runner.charset, "replace").replace(210 "\r\n", "\n"211 )212
9 unmodified lines
222 global interpreter state.223224 :param charset: the character set for the input and output data.225 :param env: a dictionary with environment variables for overriding.170 :param echo_stdin: if this is set to `True`, then reading from stdin writes171 to stdout. This is useful for showing examples in226 :param echo_stdin: if this is set to `True`, then reading from `<stdin>` writes227 to `<stdout>`. This is useful for showing examples in228 some circumstances. Note that regular prompts229 will automatically echo the input.174 :param mix_stderr: if this is set to `False`, then stdout and stderr are175 preserved as independent streams. This is useful for176 Unix-philosophy apps that have predictable stdout and177 noisy stderr, such that each may be measured178 independently230231 .. versionchanged:: 8.2232 ``mix_stderr`` parameter has been removed.233 """234235 def __init__(236 self,237 charset: str = "utf-8",238 env: cabc.Mapping[str, str | None] | None = None,239 echo_stdin: bool = False,186 mix_stderr: bool = True,240 ) -> None:241 self.charset = charset242 self.env: cabc.Mapping[str, str | None] = env or {}243 self.echo_stdin = echo_stdin191 self.mix_stderr = mix_stderr244245 def get_default_prog_name(self, cli: Command) -> str:246 """Given a command object it will return the default program name247 for it. The default is the `name` attribute or ``"root"`` if not
15 unmodified lines
263 self,264 input: str | bytes | t.IO[t.Any] | None = None,265 env: cabc.Mapping[str, str | None] | None = None,266 color: bool = False,215 ) -> cabc.Iterator[tuple[io.BytesIO, io.BytesIO | None]]:267 ) -> cabc.Iterator[tuple[io.BytesIO, io.BytesIO, io.BytesIO]]:268 """A context manager that sets up the isolation for invoking of a217 command line tool. This sets up stdin with the given input data269 command line tool. This sets up `<stdin>` with the given input data270 and `os.environ` with the overrides from the given dictionary.271 This also rebinds some internals in Click to be mocked (like the272 prompt functionality).273274 This is automatically done in the :meth:`invoke` method.275224 :param input: the input stream to put into sys.stdin.276 :param input: the input stream to put into `sys.stdin`.277 :param env: the environment overrides as dictionary.278 :param color: whether the output should contain color codes. The279 application can still override this explicitly.280281 .. versionadded:: 8.2282 An additional output stream is returned, which is a mix of283 `<stdout>` and `<stderr>` streams.284285 .. versionchanged:: 8.2286 Always returns the `<stderr>` stream.287288 .. versionchanged:: 8.0230 ``stderr`` is opened with ``errors="backslashreplace"``289 `<stderr>` is opened with ``errors="backslashreplace"``290 instead of the default ``"strict"``.291292 .. versionchanged:: 4.0293 Added the ``color`` parameter.
8 unmodified lines
302 formatting.FORCED_WIDTH = 80303304 env = self.make_env(env)305247 bytes_output = io.BytesIO()306 stream_mixer = StreamMixer()307308 if self.echo_stdin:309 bytes_input = echo_input = t.cast(251 t.BinaryIO, EchoingStdin(bytes_input, bytes_output)310 t.BinaryIO, EchoingStdin(bytes_input, stream_mixer.stdout)311 )312313 sys.stdin = text_input = _NamedTextIOWrapper(314 bytes_input, encoding=self.charset, name="<stdin>", mode="r"
4 unmodified lines
319 # large chunk which is echoed early.320 text_input._CHUNK_SIZE = 1 # type: ignore321322 sys.stdout = _NamedTextIOWrapper(264 bytes_output, encoding=self.charset, name="<stdout>", mode="w"323 stream_mixer.stdout, encoding=self.charset, name="<stdout>", mode="w"324 )325267 bytes_error = None268 if self.mix_stderr:269 sys.stderr = sys.stdout270 else:271 bytes_error = io.BytesIO()272 sys.stderr = _NamedTextIOWrapper(273 bytes_error,274 encoding=self.charset,275 name="<stderr>",276 mode="w",277 errors="backslashreplace",278 )326 sys.stderr = _NamedTextIOWrapper(327 stream_mixer.stderr,328 encoding=self.charset,329 name="<stderr>",330 mode="w",331 errors="backslashreplace",332 )333334 @_pause_echo(echo_input) # type: ignore335 def visible_input(prompt: str | None = None) -> str:336 sys.stdout.write(prompt or "")
47 unmodified lines
384 except Exception:385 pass386 else:387 os.environ[key] = value334 yield (bytes_output, bytes_error)388 yield (stream_mixer.stdout, stream_mixer.stderr, stream_mixer.output)389 finally:390 for key, value in old_env.items():391 if value is None:392 try:
40 unmodified lines
433 :param extra: the keyword arguments to pass to :meth:`main`.434 :param color: whether the output should contain color codes. The435 application can still override this explicitly.436437 .. versionadded:: 8.2438 The result object has the ``output_bytes`` attribute with439 the mix of ``stdout_bytes`` and ``stderr_bytes``, as the user would440 see it in its terminal.441442 .. versionchanged:: 8.2443 The result object always returns the ``stderr_bytes`` stream.444445 .. versionchanged:: 8.0446 The result object has the ``return_value`` attribute with447 the value returned from the invoked command.448
48 unmodified lines
497 exc_info = sys.exc_info()498 finally:499 sys.stdout.flush()500 stdout = outstreams[0].getvalue()439 if self.mix_stderr:440 stderr = None441 else:442 stderr = outstreams[1].getvalue() # type: ignore501 stderr = outstreams[1].getvalue()502 output = outstreams[2].getvalue()503504 return Result(505 runner=self,506 stdout_bytes=stdout,507 stderr_bytes=stderr,508 output_bytes=output,509 return_value=return_value,510 exit_code=exit_code,511 exception=exception,512 exc_info=exc_info, # type: ignore
32 unmodified lines
modified:src/click/types.py+14 added-1 removed
257 unmodified lines
258 info_dict["case_sensitive"] = self.case_sensitive259 return info_dict260261 def get_metavar(self, param: Parameter) -> str:262 choices_str = "|".join(self.choices)262 if param.param_type_name == "option" and not param.show_choices: # type: ignore263 choice_metavars = [264 convert_type(type(choice)).name.upper() for choice in self.choices265 ]266 choices_str = "|".join([*dict.fromkeys(choice_metavars)])267 else:268 choices_str = "|".join([str(i) for i in self.choices])269270 # Use curly braces to indicate a required argument.271 if param.required and param.param_type_name == "argument":272 return f"{{{choices_str}}}"
821 unmodified lines
1094BOOL = BoolParamType()10951096#: A UUID parameter.1097UUID = UUIDParameterType()109810991100class OptionHelpExtra(t.TypedDict, total=False):1101 envvars: tuple[str, ...]1102 default: str1103 range: str1104 required: str
modified:tests/test_options.py+59 added-12 removed
314 unmodified lines
315 return "special value"316317 opt = click.Option(["-a"], default=Value(), show_default=True)318 ctx = click.Context(click.Command("cli"))319 assert opt.get_help_extra(ctx) == {"default": "special value"}320 assert "special value" in opt.get_help_record(ctx)[1]321322323@pytest.mark.parametrize(
7 unmodified lines
331)332def test_intrange_default_help_text(type, expect):333 option = click.Option(["--num"], type=type, show_default=True, default=2)334 context = click.Context(click.Command("test"))335 assert option.get_help_extra(context) == {"default": "2", "range": expect}336 result = option.get_help_record(context)[1]337 assert expect in result338339340def test_count_default_type_help():341 """A count option with the default type should not show >=0 in help."""342 option = click.Option(["--count"], count=True, help="some words")343 context = click.Context(click.Command("test"))344 assert option.get_help_extra(context) == {}345 result = option.get_help_record(context)[1]346 assert result == "some words"347348
7 unmodified lines
356 option = click.Option(357 ["--in"], type=click.File(), default=__file__, show_default=True358 )359 context = click.Context(click.Command("test"))360 assert option.get_help_extra(context) == {"default": __file__}361 result = option.get_help_record(context)[1]362 assert __file__ in result363364
379 unmodified lines
744 show_default=True,745 help="Enable/Disable the cache.",746 )747 ctx = click.Context(click.Command("test"))748 assert opt.get_help_extra(ctx) == {"default": expect}749 message = opt.get_help_record(ctx)[1]750 assert f"[default: {expect}]" in message751752
8 unmodified lines
761 default=True,762 help="Enable the cache.",763 )764 ctx = click.Context(click.Command("test"))765 assert opt.get_help_extra(ctx) == {"default": "True"}766 message = opt.get_help_record(ctx)[1]767 assert "[default: True]" in message768769
9 unmodified lines
779 default=default,780 help="Enable the cache.",781 )782 ctx = click.Context(click.Command("test"))783 assert opt.get_help_extra(ctx) == {}784 message = opt.get_help_record(ctx)[1]785 assert "[default: " not in message786787788def test_show_default_string(runner):789 """When show_default is a string show that value as default."""790 opt = click.Option(["--limit"], show_default="unlimited")791 ctx = click.Context(click.Command("cli"))792 assert opt.get_help_extra(ctx) == {"default": "(unlimited)"}793 message = opt.get_help_record(ctx)[1]794 assert "[default: (unlimited)]" in message795796
8 unmodified lines
805def test_do_not_show_no_default(runner):806 """When show_default is True and no default is set do not show None."""807 opt = click.Option(["--limit"], show_default=True)808 ctx = click.Context(click.Command("cli"))809 assert opt.get_help_extra(ctx) == {}810 message = opt.get_help_record(ctx)[1]811 assert "[default: None]" not in message812813
2 unmodified lines
816 print empty default value in --help output.817 """818 opt = click.Option(["-a"], multiple=True, help="values", show_default=True)819 ctx = click.Context(click.Command("cli"))820 assert opt.get_help_extra(ctx) == {}821 message = opt.get_help_record(ctx)[1]822 assert message == "values"823824825@pytest.mark.parametrize(816 ("ctx_value", "opt_value", "expect"),826 ("ctx_value", "opt_value", "extra_value", "expect"),827 [818 (None, None, False),819 (None, False, False),820 (None, True, True),821 (False, None, False),822 (False, False, False),823 (False, True, True),824 (True, None, True),825 (True, False, False),826 (True, True, True),827 (False, "one", True),828 (None, None, {}, False),829 (None, False, {}, False),830 (None, True, {"default": "1"}, True),831 (False, None, {}, False),832 (False, False, {}, False),833 (False, True, {"default": "1"}, True),834 (True, None, {"default": "1"}, True),835 (True, False, {}, False),836 (True, True, {"default": "1"}, True),837 (False, "one", {"default": "(one)"}, True),838 ],839)830def test_show_default_precedence(ctx_value, opt_value, expect):840def test_show_default_precedence(ctx_value, opt_value, extra_value, expect):841 ctx = click.Context(click.Command("test"), show_default=ctx_value)842 opt = click.Option("-a", default=1, help="value", show_default=opt_value)843 assert opt.get_help_extra(ctx) == extra_value844 help = opt.get_help_record(ctx)[1]845 assert ("default:" in help) is expect846847
88 unmodified lines
936 with pytest.raises(TypeError) as e:937 click.Option(["-a"], **kwargs)938939 assert message in str(e.value)940941942@pytest.mark.parametrize(943 ("choices", "metavars"),944 [945 pytest.param(["foo", "bar"], "[TEXT]", id="text choices"),946 pytest.param([1, 2], "[INTEGER]", id="int choices"),947 pytest.param([1.0, 2.0], "[FLOAT]", id="float choices"),948 pytest.param([True, False], "[BOOLEAN]", id="bool choices"),949 pytest.param(["foo", 1], "[TEXT|INTEGER]", id="text/int choices"),950 ],951)952def test_usage_show_choices(runner, choices, metavars):953 """When show_choices=False is set, the --help output954 should print choice metavars instead of values.955 """956957 @click.command()958 @click.option("-g", type=click.Choice(choices))959 def cli_with_choices(g):960 pass961962 @click.command()963 @click.option(964 "-g",965 type=click.Choice(choices),966 show_choices=False,967 )968 def cli_without_choices(g):969 pass970971 result = runner.invoke(cli_with_choices, ["--help"])972 assert f"[{'|'.join([str(i) for i in choices])}]" in result.output973974 result = runner.invoke(cli_without_choices, ["--help"])975 assert metavars in result.output
modified:tests/test_termui.py+13 added-1 removed
244 unmodified lines
245@pytest.mark.parametrize(246 ("value", "expect"), [(123, b"\x1b[45m123\x1b[0m"), (b"test", b"test")]247)248def test_secho_non_text(runner, value, expect):249 with runner.isolation() as (out, _):249 with runner.isolation() as (out, _, _):250 click.secho(value, nl=False, color=True, bg="magenta")251 result = out.getvalue()252 assert result == expect253
192 unmodified lines
446 assert result.return_value == expect447448 if prompt == "Confirm Password":449 assert "Confirm Password: " in result.output450451452def test_false_show_default_cause_no_default_display_in_prompt(runner):453 @click.command()454 @click.option("--arg1", show_default=False, prompt=True, default="my-default-value")455 def cmd(arg1):456 pass457458 # Confirm that the default value is not included in the output when `show_default`459 # is False460 result = runner.invoke(cmd, input="my-input", standalone_mode=False)461 assert "my-default-value" not in result.output
modified:tests/test_testing.py+11 added-20 removed
320 unmodified lines
321322def test_stderr():323 @click.command()324 def cli_stderr():325 click.echo("stdout")326 click.echo("stderr", err=True)325 click.echo("1 - stdout")326 click.echo("2 - stderr", err=True)327 click.echo("3 - stdout")328 click.echo("4 - stderr", err=True)329328 runner = CliRunner(mix_stderr=False)329330 result = runner.invoke(cli_stderr)331332 assert result.output == "stdout\n"333 assert result.stdout == "stdout\n"334 assert result.stderr == "stderr\n"335336 runner_mix = CliRunner(mix_stderr=True)330 runner_mix = CliRunner()331 result_mix = runner_mix.invoke(cli_stderr)332339 assert result_mix.output == "stdout\nstderr\n"340 assert result_mix.stdout == "stdout\nstderr\n"333 assert result_mix.output == "1 - stdout\n2 - stderr\n3 - stdout\n4 - stderr\n"334 assert result_mix.stdout == "1 - stdout\n3 - stdout\n"335 assert result_mix.stderr == "2 - stderr\n4 - stderr\n"336342 with pytest.raises(ValueError):343 assert result_mix.stderr # noqa B018344337 @click.command()338 def cli_empty_stderr():339 click.echo("stdout")340349 runner = CliRunner(mix_stderr=False)350341 runner = CliRunner()342 result = runner.invoke(cli_empty_stderr)343344 assert result.output == "stdout\n"345 assert result.stdout == "stdout\n"
75 unmodified lines
421def test_isolation_stderr_errors():422 """Writing to stderr should escape invalid characters instead of423 raising a UnicodeEncodeError.424 """434 runner = CliRunner(mix_stderr=False)425 runner = CliRunner()426436 with runner.isolation() as (_, err):427 with runner.isolation() as (_, err, _):428 click.echo("\udce2", err=True, nl=False)429430 assert err.getvalue() == b"\\udce2"
modified:CHANGES.rst+12 added
29 unmodified lines
30 ``from __future__ import annotations``. :pr:`2270`31- When generating a command's name from a decorated function's name, the32 suffixes ``_command``, ``_cmd``, ``_group``, and ``_grp`` are removed.33 :issue:`2322`34- Show the ``types.ParamType.name`` for ``types.Choice`` options within35 ``--help`` message if ``show_choices=False`` is specified.36 :issue:`2356`37- Do not display default values in prompts when ``Option.show_default`` is38 ``False``. :pr:`2509`39- Add ``get_help_extra`` method on ``Option`` to fetch the generated extra40 items used in ``get_help_record`` to render help text. :issue:`2516`41 :pr:`2517`42- Keep stdout and stderr streams independent in ``CliRunner``. Always43 collect stderr output and never raise an exception. Add a new44 output` stream to simulate what the user sees in its terminal. Removes45 the ``mix_stderr`` parameter in ``CliRunner``. :issue:`2522` :pr:`2523`464748Version 8.1.849-------------
1118 unmodified lines