Merge stable into main (#3521)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Rowlando13 · committed by GitHub · parents 6a141c3, 97210f2 · Browse files · 12 files·+232 added−58 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
12 files+232 added−58 removed
- tests:+83 added−0 removed
- other:+149 added−58 removed
Provenance
- Commit
1a994ad- Tree
f1d62ca- Author
Rowlando13 <67291205+Rowlando13@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent 1
6a141c3- Parent 2
97210f2
12 files changed+232 added−58 removed
modified:docs/advanced.md+11 added-15 removed
128 unmodified lines129 130 ```{eval-rst}131 .. click:example::132 133- import urllib133+ import urllib.request134 135 def open_url(ctx, param, value):136 if value is not None:137- ctx.params['fp'] = urllib.urlopen(value)137+ ctx.params['fp'] = urllib.request.urlopen(value)138 return value139 140 @click.command()141 @click.option('--url', callback=open_url)16 unmodified lines158 What's more recommended is to pass the information in a wrapper, however:159 160 .. click:example::161 162- import urllib162+ import urllib.request163 164- class URL(object):165-164+ class URL:165 def __init__(self, url, fp):166 self.url = url167 self.fp = fp168 169 def open_url(ctx, param, value):170 if value is not None:172- return URL(value, urllib.urlopen(value))171+ return URL(value, urllib.request.urlopen(value))172 173 @click.command()174 @click.option('--url', callback=open_url)175 def cli(url):18 unmodified lines194 195 ```{eval-rst}196 .. click:example::197 199- CONTEXT_SETTINGS = dict(token_normalize_func=lambda x: x.lower())198+ CONTEXT_SETTINGS = {'token_normalize_func': lambda x: x.lower()}199 200 @click.command(context_settings=CONTEXT_SETTINGS)201 @click.option('--name', default='Pete')202 def cli(name):86 unmodified lines289 290 ```{eval-rst}291 .. click:example::292 294- import sys293 from subprocess import call294 297- @click.command(context_settings=dict(298- ignore_unknown_options=True,299- ))295+ @click.command(context_settings={'ignore_unknown_options': True})296 @click.option('-v', '--verbose', is_flag=True, help='Enables verbose mode')297 @click.argument('timeit_args', nargs=-1, type=click.UNPROCESSED)298 def cli(verbose, timeit_args):299 """A fake wrapper around Python's timeit."""304- cmdline = ['echo', 'python', '-mtimeit'] + list(timeit_args)300+ cmdline = ['echo', 'python', '-mtimeit', *timeit_args]301 if verbose:302 click.echo(f"Invoking: {' '.join(cmdline)}")303 call(cmdline)304 21 unmodified lines326 handled as an argument.327 - Unknown short options might be partially handled and reassembled if328 necessary. For instance in the above example there is an option329 called `-v` which enables verbose mode. If the command would be334- ignored with `-va` then the `-v` part would be handled by Click330+ invoked with `-va` then the `-v` part would be handled by Click331 (as it is known) and `-a` would end up in the leftover parameters332 for further processing.333 - Depending on what you plan on doing you might have some success by334 disabling interspersed arguments69 unmodified lines404 ```python405 @click.group()406 @click.option("--name", default="repo.db")407 @click.pass_context412-def cli(ctx, repo_home):413- ctx.obj = db = open_db(repo_home)408+def cli(ctx, name):409+ ctx.obj = db = open_db(name)410 411 @ctx.call_on_close412 def close_db():413 db.record_use()8 unmodified linesmodified:docs/documentation.md+8 added
308 unmodified lines309 invoke(hello, args=['--help'])310 311 ```312 313+```{admonition} Optional elements are bracketed314+:class: note315+316+ The usage line follows a consistent convention: an element is optional when it is enclosed in square brackets and required when it appears outside them. A required argument appears as `FOO` and an optional one as `[FOO]`, with a variadic argument adding a trailing `...` (so `[FOO]...`). A single pair of brackets can group several tokens, so a chained group renders an extra command and its arguments as one optional, repeatable unit: `[COMMAND2 [ARGS]...]...`. A {class}`Group` that can run without naming a subcommand (`invoke_without_command=True`) also brackets the leading command, showing `[COMMAND]` instead of `COMMAND`. The `[OPTIONS]` placeholder is always bracketed, since adding options is itself optional.317+318+ This mirrors the conventional utility-argument syntax for optional arguments and operands ([POSIX §12.1](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap12.html), [`man-pages(7)`](https://man7.org/linux/man-pages/man7/man-pages.7.html)), where a bracketed expression followed by `...` denotes zero or more occurrences. A subcommand name is a positional operand, so Click brackets it under the same rule.319+```320+321 ## Help Parameter Customization322 323 Help parameters are automatically added by Click for any command. The default is `--help` but can be overridden by the context setting {attr}`~Context.help_option_names`. Click also performs automatic conflict resolution on the default help parameter, so if a command itself implements a parameter named `help` then the default help will not be run.324 17 unmodified linesmodified:docs/options.md+2 added-2 removed
350 unmodified lines351 * Shell scripts sometimes want to be explicit even when it's the default352 * Shell aliases can set a flag, then an invocation can add a negation of the353 flag354 355-If a forward slash(`/`) is contained in your option name already, you can split355+If a forward slash (`/`) is contained in your option name already, you can split356 the parameters using `;`. In Windows `/` is commonly used as the prefix357 character.358 359 ```{eval-rst}348 unmodified lines708 709 ```{caution}710 For boolean flags with a pair of values, the only recognized environment variable is the one provided to the `envvar` argument.711 712-So an option defined as `--flag\--no-flag`, with a `envvar="FLAG"` parameter, there is no magical `NO_FLAG=<anything>` variable that is recognized. Only the `FLAG=<anything>` environment variable is recognized.712+So an option defined as `--flag/--no-flag`, with an `envvar="FLAG"` parameter, there is no magical `NO_FLAG=<anything>` variable that is recognized. Only the `FLAG=<anything>` environment variable is recognized.713 ```714 715 If the flag is activated, its value is set to `flag_value`. Otherwise, the value716 defaults to `None`.84 unmodified linesmodified:src/click/core.py+11 added-3 removed
1187 unmodified lines1188 else:1189 text = ""1190 1191 if self.deprecated:1192- text = f"{_(text)} {_format_deprecated_label(self.deprecated)}"1192+ label = _format_deprecated_label(self.deprecated)1193+ text = f"{_(text)} {label}" if text else label1194 1195 if text:1196 formatter.write_paragraph()1197 424 unmodified lines1622 self.no_args_is_help = no_args_is_help1623 self.invoke_without_command = invoke_without_command1624 1625 if subcommand_metavar is None:1626+ # When the group can run without a subcommand, the leading command1627+ # token is optional, so wrap it in brackets to reflect that.1628 if chain:1629+ if invoke_without_command:1630+ subcommand_metavar = "[COMMAND1] [ARGS]... [COMMAND2 [ARGS]...]..."1631+ else:1626- subcommand_metavar = "COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]..."1632+ subcommand_metavar = "COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]..."1633+ elif invoke_without_command:1634+ subcommand_metavar = "[COMMAND] [ARGS]..."1635 else:1636 subcommand_metavar = "COMMAND [ARGS]..."1637 1638 self.subcommand_metavar = subcommand_metavar1194 unmodified lines2833 prompt_text = prompt2834 2835 if deprecated:2836 label = _format_deprecated_label(deprecated)2829- help = f"{help} {label}" if help is not None else label2837+ help = f"{help} {label}" if help else label2838 2839 self.prompt = prompt_text2840 self.confirmation_prompt = confirmation_prompt2841 self.prompt_required = prompt_required709 unmodified linesmodified:src/click/exceptions.py+42 added-11 removed
34 unmodified lines35 class ClickException(Exception):36 """An exception that Click can handle and show to the user."""37 38 #: The exit code for this exception.39- exit_code = 139+ exit_code: t.ClassVar[int] = 140 41+ show_color: t.Final[bool | None]42+ message: t.Final[str]43+44 def __init__(self, message: str) -> None:45 super().__init__(message)46 # The context will be removed by the time we print the message, so cache47 # the color settings here to be used later on (in `show`)45- self.show_color: bool | None = resolve_color_default()48+ self.show_color = resolve_color_default()49 self.message = message50 51 def format_message(self) -> str:52 return self.message20 unmodified lines73 :param ctx: optionally the context that caused this error. Click will74 fill in the context automatically in some situations.75 """76 74- exit_code = 277+ exit_code: t.ClassVar[int] = 278 79+ ctx: Context | None80+ cmd: t.Final[Command | None]81+82 def __init__(self, message: str, ctx: Context | None = None) -> None:83 super().__init__(message)84 self.ctx = ctx79- self.cmd: Command | None = self.ctx.command if self.ctx else None85+ self.cmd = self.ctx.command if self.ctx else None86 87 def show(self, file: t.IO[t.Any] | None = None) -> None:88 if file is None:89 file = get_text_stderr()38 unmodified lines128 a string it's used as such, if it's a list then129 each item is quoted and separated.130 """131 132+ param: Parameter | None133+ param_hint: cabc.Sequence[str] | str | None134+135 def __init__(136 self,137 message: str,138 ctx: Context | None = None,28 unmodified lines167 the given `param`. Valid values are ``'parameter'``,168 ``'option'`` or ``'argument'``.169 """170 171+ param_type: t.Final[str | None]172+173 def __init__(174 self,175 message: str | None = None,176 ctx: Context | None = None,57 unmodified lines234 235 .. versionadded:: 4.0236 """237 238+ option_name: t.Final[str]239+ possibilities: t.Final[list[str] | None]240+241 def __init__(242 self,243 option_name: str,244 message: str | None = None,4 unmodified lines249 message = _("No such option {name!r}.").format(name=option_name)250 251 super().__init__(message, ctx)252 self.option_name = option_name239- self.possibilities: list[str] | None = None253+254 if possibilities:255 from difflib import get_close_matches256 243- self.possibilities = get_close_matches(option_name, possibilities)257+ possibilities_ = get_close_matches(option_name, possibilities)258+ else:259+ possibilities_ = None260+ self.possibilities = possibilities_261 262 def format_message(self) -> str:263 if not self.possibilities:264 return self.message5 unmodified lines270 271 .. versionadded:: 8.4.0272 """273 274+ command_name: t.Final[str]275+ possibilities: t.Final[list[str] | None]276+277 def __init__(278 self,279 command_name: str,280 message: str | None = None,4 unmodified lines285 message = _("No such command {name!r}.").format(name=command_name)286 287 super().__init__(message, ctx)288 self.command_name = command_name269- self.possibilities: list[str] | None = None289+290 if possibilities:291 from difflib import get_close_matches292 273- self.possibilities = get_close_matches(command_name, possibilities)293+ possibilities_ = get_close_matches(command_name, possibilities)294+ else:295+ possibilities_ = None296+ self.possibilities = possibilities_297 298 def format_message(self) -> str:299 if not self.possibilities:300 return self.message9 unmodified lines310 311 :param option_name: the name of the option being used incorrectly.312 """313 314+ option_name: t.Final[str]315+316 def __init__(317 self, option_name: str, message: str, ctx: Context | None = None318 ) -> None:319 super().__init__(message, ctx)9 unmodified lines329 """330 331 332 class NoArgsIsHelpError(UsageError):333+ ctx: Context334+335 def __init__(self, ctx: Context) -> None:309- self.ctx: Context336 super().__init__(ctx.get_help(), ctx=ctx)337 338 def show(self, file: t.IO[t.Any] | None = None) -> None:339 echo(self.format_message(), file=file, err=True, color=self.ctx.color)1 unmodified line341 342 class FileError(ClickException):343 """Raised if a file cannot be opened."""344 345+ ui_filename: t.Final[str]346+ filename: t.Final[str]347+348 def __init__(self, filename: str, hint: str | None = None) -> None:349 if hint is None:350 hint = _("unknown error")351 352 super().__init__(hint)324- self.ui_filename: str = format_filename(filename)353+ self.ui_filename = format_filename(filename)354 self.filename = filename355 356 def format_message(self) -> str:357 return _("Could not open file {filename!r}: {message}").format(13 unmodified lines371 """372 373 __slots__ = ("exit_code",)374 375+ exit_code: t.Final[int]376+377 def __init__(self, code: int = 0) -> None:347- self.exit_code: int = code378+ self.exit_code = codemodified:src/click/formatting.py+11 added-6 removed
117 unmodified lines118 :param width: the width for the text. This defaults to the terminal119 width clamped to a maximum of 78.120 """121 122+ indent_increment: int123+ width: int124+ current_indent: int125+ buffer: list[str]126+127 def __init__(128 self,129 indent_increment: int = 2,130 width: int | None = None,8 unmodified lines139 width = FORCED_WIDTH140 if width is None:141 width = max(min(shutil.get_terminal_size().columns, max_width) - 2, 50)142 self.width = width138- self.current_indent: int = 0139- self.buffer: list[str] = []143+ self.current_indent = 0144+ self.buffer = []145 146 def write(self, string: str) -> None:147 """Writes a unicode string into the internal buffer."""148 self.buffer.append(string)78 unmodified lines227 self.write("\n")228 229 def write_dl(230 self,226- rows: cabc.Sequence[tuple[str, str]],231+ rows: cabc.Iterable[tuple[str, str]],232 col_max: int = 30,233 col_spacing: int = 2,234 ) -> None:235 """Writes a definition list into the buffer. This is how options34 unmodified lines270 else:271 self.write("\n")272 273 @contextmanager269- def section(self, name: str) -> cabc.Iterator[None]:274+ def section(self, name: str) -> cabc.Generator[None]:275 """Helpful context manager that writes a paragraph, a heading,276 and the indents.277 278 :param name: the section name that is written as heading.6 unmodified lines285 finally:286 self.dedent()287 288 @contextmanager284- def indentation(self) -> cabc.Iterator[None]:289+ def indentation(self) -> cabc.Generator[None]:290 """A context manager that increases the indentation."""291 self.indent()292 try:293 yield4 unmodified lines298 """Returns the buffer contents."""299 return "".join(self.buffer)300 301 297-def join_options(options: cabc.Sequence[str]) -> tuple[str, bool]:302+def join_options(options: cabc.Iterable[str]) -> tuple[str, bool]:303 """Given a list of option strings this joins them in the most appropriate304 way and returns them in the form ``(formatted_string,305 any_prefix_is_slash)`` where the second item in the tuple is a flag that306 indicates if any of the option prefixes was a slash.14 unmodified linesmodified:src/click/shell_completion.py+11 added-6 removed
220 unmodified lines221 """Completion script template formatted by :meth:`source`. This must222 be provided by subclasses.223 """224 225+ cli: Command226+ ctx_args: cabc.MutableMapping[str, t.Any]227+ prog_name: str228+ complete_var: str229+230 def __init__(231 self,232 cli: Command,233 ctx_args: cabc.MutableMapping[str, t.Any],75 unmodified lines309 310 class BashComplete(ShellComplete):311 """Shell completion for Bash."""312 308- name = "bash"309- source_template = _SOURCE_BASH313+ name: t.ClassVar[str] = "bash"314+ source_template: t.ClassVar[str] = _SOURCE_BASH315 316 @staticmethod317 def _check_version() -> None:318 import shutil49 unmodified lines368 369 class ZshComplete(ShellComplete):370 """Shell completion for Zsh."""371 367- name = "zsh"368- source_template = _SOURCE_ZSH372+ name: t.ClassVar[str] = "zsh"373+ source_template: t.ClassVar[str] = _SOURCE_ZSH374 375 def get_completion_args(self) -> tuple[list[str], str]:376 cwords = split_arg_string(os.environ["COMP_WORDS"])377 cword = int(os.environ["COMP_CWORD"])26 unmodified lines404 405 class FishComplete(ShellComplete):406 """Shell completion for Fish."""407 403- name = "fish"404- source_template = _SOURCE_FISH408+ name: t.ClassVar[str] = "fish"409+ source_template: t.ClassVar[str] = _SOURCE_FISH410 411 def get_completion_args(self) -> tuple[list[str], str]:412 cwords = split_arg_string(os.environ["COMP_WORDS"])413 incomplete = os.environ["COMP_CWORD"]268 unmodified linesmodified:src/click/testing.py+48 added-15 removed
20 unmodified lines21 from _typeshed import ReadableBuffer22 23 from .core import Command24 25-CaptureMode = t.Literal["sys", "fd"]25+CaptureMode: t.TypeAlias = t.Literal["sys", "fd"]26+ExceptionInfo: t.TypeAlias = tuple[type[BaseException], BaseException, TracebackType]27 28 29 class EchoingStdin:30+ _input: t.BinaryIO31+ _output: t.BinaryIO32+ _paused: bool33+34 def __init__(self, input: t.BinaryIO, output: t.BinaryIO) -> None:35 self._input = input36 self._output = output37 self._paused = False26 unmodified lines64 return repr(self._input)65 66 67 @contextlib.contextmanager63-def _pause_echo(stream: EchoingStdin | None) -> cabc.Iterator[None]:68+def _pause_echo(stream: EchoingStdin | None) -> cabc.Generator[None]:69 if stream is None:70 yield71 else:72 stream._paused = True11 unmodified lines84 85 .. versionadded:: 8.4.086 """87 88+ _targetfd: int89+ saved_fd: int90+ _tmpfile: t.BinaryIO | None91+92 def __init__(self, targetfd: int) -> None:93 self._targetfd = targetfd85- self.saved_fd: int = -186- self._tmpfile: t.BinaryIO | None = None94+ self.saved_fd = -195+ self._tmpfile = None96 97 def start(self) -> None:98 self.saved_fd = os.dup(self._targetfd)99 self._tmpfile = tempfile.TemporaryFile(buffering=0)16 unmodified lines116 117 .. versionadded:: 8.2118 """119 120+ copy_to: io.BytesIO121+122 def __init__(self, copy_to: io.BytesIO) -> None:123 super().__init__()124 self.copy_to = copy_to125 13 unmodified lines139 140 .. versionadded:: 8.2141 """142 143+ output: io.BytesIO144+ stdout: BytesIOCopy145+ stderr: BytesIOCopy146+147 def __init__(self) -> None:133- self.output: io.BytesIO = io.BytesIO()134- self.stdout: io.BytesIO = BytesIOCopy(copy_to=self.output)135- self.stderr: io.BytesIO = BytesIOCopy(copy_to=self.output)148+ self.output = io.BytesIO()149+ self.stdout = BytesIOCopy(copy_to=self.output)150+ self.stderr = BytesIOCopy(copy_to=self.output)151 152 153 class _NamedTextIOWrapper(io.TextIOWrapper):154 """A :class:`~io.TextIOWrapper` with custom ``name`` and ``mode``6 unmodified lines161 :meth:`fileno` raises :exc:`io.UnsupportedOperation`, matching the162 pre-``8.3.3`` behavior.163 """164 165+ _name: str166+ _mode: str167+ _original_fd: int168+169 def __init__(170 self,171 buffer: t.BinaryIO,172 name: str,2 unmodified lines175 ) -> None:176 super().__init__(buffer, **kwargs)177 self._name = name178 self._mode = mode160- self._original_fd: int = -1179+ self._original_fd = -1180 181 def close(self) -> None:182 """The buffer this object contains belongs to some other object,183 so prevent the default ``__del__`` implementation from closing62 unmodified lines246 .. versionadded:: 8.0247 Added ``return_value``.248 """249 250+ runner: CliRunner251+ stdout_bytes: bytes252+ stderr_bytes: bytes253+ output_bytes: bytes254+ return_value: t.Any255+ exit_code: int256+ exception: BaseException | None257+ exc_info: ExceptionInfo | None258+259 def __init__(260 self,261 runner: CliRunner,262 stdout_bytes: bytes,1 unmodified line264 output_bytes: bytes,265 return_value: t.Any,266 exit_code: int,267 exception: BaseException | None,240- exc_info: tuple[type[BaseException], BaseException, TracebackType]241- | None = None,242- ):268+ exc_info: ExceptionInfo | None = None,269+ ) -> None:270 self.runner = runner271 self.stdout_bytes = stdout_bytes272 self.stderr_bytes = stderr_bytes273 self.output_bytes = output_bytes73 unmodified lines347 .. versionchanged:: 8.2348 ``mix_stderr`` parameter has been removed.349 """350 351+ charset: str352+ env: cabc.Mapping[str, str | None]353+ echo_stdin: bool354+ catch_exceptions: bool355+ capture: CaptureMode356+357 def __init__(358 self,359 charset: str = "utf-8",360 env: cabc.Mapping[str, str | None] | None = None,9 unmodified lines370 raise ValueError(371 f"capture={capture!r} is not supported on Windows. Use 'sys'."372 )373 self.charset = charset341- self.env: cabc.Mapping[str, str | None] = env or {}374+ self.env = env or {}375 self.echo_stdin = echo_stdin376 self.catch_exceptions = catch_exceptions344- self.capture: CaptureMode = capture377+ self.capture = capture378 379 def get_default_prog_name(self, cli: Command) -> str:380 """Given a command object it will return the default program name381 for it. The default is the `name` attribute or ``"root"`` if not15 unmodified lines397 self,398 input: str | bytes | t.IO[t.Any] | None = None,399 env: cabc.Mapping[str, str | None] | None = None,400 color: bool = False,368- ) -> cabc.Iterator[tuple[io.BytesIO, io.BytesIO, io.BytesIO]]:401+ ) -> cabc.Generator[tuple[io.BytesIO, io.BytesIO, io.BytesIO]]:402 """A context manager that sets up the isolation for invoking of a403 command line tool. This sets up `<stdin>` with the given input data404 and `os.environ` with the overrides from the given dictionary.405 This also rebinds some internals in Click to be mocked (like the331 unmodified lines737 738 @contextlib.contextmanager739 def isolated_filesystem(740 self, temp_dir: str | os.PathLike[str] | None = None708- ) -> cabc.Iterator[str]:741+ ) -> cabc.Generator[str]:742 """A context manager that creates a temporary directory and743 changes the current working directory to it. This isolates tests744 that affect the contents of the CWD to prevent them from745 interfering with each other.24 unmodified linesmodified:tests/test_arguments.py+26 added
304 unmodified lines305 assert result.exit_code == 0, result.output306 assert "[F!]" in result.output307 308 309+@pytest.mark.parametrize(310+ ("kwargs", "expected"),311+ [312+ ({}, "FOO"),313+ ({"required": True}, "FOO"),314+ ({"required": False}, "[FOO]"),315+ ({"default": "x"}, "[FOO]"),316+ ({"nargs": -1}, "[FOO]..."),317+ ({"nargs": -1, "required": True}, "FOO..."),318+ ({"nargs": 2}, "FOO..."),319+ ({"nargs": 2, "required": False}, "[FOO]..."),320+ ],321+)322+def test_argument_metavar_marks_optional(runner, kwargs, expected):323+ """An argument is bracketed in the usage line only when it is optional."""324+325+ @click.command()326+ @click.argument("foo", **kwargs)327+ def cli(foo):328+ pass329+330+ result = runner.invoke(cli, ["--help"])331+ assert result.exit_code == 0332+ assert result.output.splitlines()[0] == f"Usage: cli [OPTIONS] {expected}"333+334+335 @pytest.mark.parametrize("deprecated", [True, "USE B INSTEAD"])336 def test_deprecated_warning(runner, deprecated):337 @click.command()338 @click.argument(317 unmodified linesmodified:tests/test_commands.py+43 added
297 unmodified lines298 assert not result.exception299 assert result.output == "no subcommand, use default\nin subcommand\n"300 301 302+@pytest.mark.parametrize(303+ ("chain", "invoke_without_command", "metavar"),304+ [305+ (False, False, "COMMAND [ARGS]..."),306+ (False, True, "[COMMAND] [ARGS]..."),307+ (True, False, "COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]..."),308+ (True, True, "[COMMAND1] [ARGS]... [COMMAND2 [ARGS]...]..."),309+ ],310+)311+def test_subcommand_metavar_marks_optional(312+ runner, chain, invoke_without_command, metavar313+):314+ """The leading subcommand token is bracketed only when it is optional."""315+316+ @click.group(chain=chain, invoke_without_command=invoke_without_command)317+ def cli():318+ pass319+320+ @cli.command()321+ def sub():322+ pass323+324+ result = runner.invoke(cli, ["--help"])325+ assert result.exit_code == 0326+ assert result.output.splitlines()[0] == f"Usage: cli [OPTIONS] {metavar}"327+328+329 def test_aliased_command_canonical_name(runner):330 class AliasedGroup(click.Group):331 def get_command(self, ctx, cmd_name):332 return push185 unmodified lines518 assert deprecated in result.output519 520 521 @pytest.mark.parametrize("deprecated", [True, "USE OTHER COMMAND INSTEAD"])522+@pytest.mark.parametrize("doc", ["", None])523+def test_deprecated_empty_help_no_leading_space(runner, doc, deprecated):524+ """A command with empty or missing help text must render the deprecation525+ label at the normal indentation, without a stray leading space.526+ """527+528+ @click.command(deprecated=deprecated, help=doc)529+ def cli():530+ pass531+532+ out = runner.invoke(cli, ["--help"]).output533+ assert "\n (DEPRECATED" in out534+ assert "\n (DEPRECATED" not in out535+536+537+@pytest.mark.parametrize("deprecated", [True, "USE OTHER COMMAND INSTEAD"])538 def test_deprecated_in_invocation(runner, deprecated):539 @click.command(deprecated=deprecated)540 def deprecated_cmd():541 pass109 unmodified linesmodified:tests/test_options.py+14 added
56 unmodified lines57 if isinstance(deprecated, str):58 assert deprecated in result.output59 60 61+@pytest.mark.parametrize(62+ ("deprecated", "expected"),63+ [(True, "(DEPRECATED)"), ("USE B INSTEAD", "(DEPRECATED: USE B INSTEAD)")],64+)65+@pytest.mark.parametrize("help_text", ["", None])66+def test_deprecated_empty_help_no_leading_space(help_text, deprecated, expected):67+ """An option with empty or missing help text must not gain a stray leading68+ space before the deprecation label.69+ """70+ opt = click.Option(["--foo"], help=help_text, deprecated=deprecated)71+ ctx = click.Context(click.Command("cli"))72+ assert opt.get_help_record(ctx)[1] == expected73+74+75 @pytest.mark.parametrize("deprecated", [True, "USE B INSTEAD"])76 def test_deprecated_warning(runner, deprecated):77 @click.command()78 @click.option(3439 unmodified linesmodified:CHANGES.rst+5 added
16 unmodified lines17 - Fix Fish shell completion broken in ``8.4.0`` by :pr:`3126`. Newlines and18 tabs in option help text are now escaped, keeping the original completion19 format while still supporting multi-line help. :issue:`3502`20 :issue:`3043` :pr:`3504` :pr:`3508`21+- Deprecated commands and options with empty or missing help text no longer22+ render a stray leading space before the ``(DEPRECATED)`` label. :pr:`3509`23+- A :class:`Group` with ``invoke_without_command=True`` marks its subcommand as24+ optional in the usage help, showing ``[COMMAND]`` instead of ``COMMAND``.25+ :issue:`3059` :pr:`3507`26 27 28 Version 8.4.129 -------------1475 unmodified lines