Skip to content
Myr

Merge stable into main (#3037)

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

authored by Rowlando13 · committed by GitHub · parents 6965a6a, 5b0b7b4 · Browse files · 9 files+189 added−172 removed
This commit

State

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

Diff stats

9 files+189 added−172 removed

  • tests:+1 added−1 removed
  • other:+188 added−171 removed

9 files+189 added−172 removed

added:docs/prompts.md+168 added
1# User Input Prompts23```{currentmodule} click4```56Click supports prompts in two different places. The first is automated prompts when the parameter handling happens, and7the second is to ask for prompts at a later point independently.89This can be accomplished with the {func}`prompt` function, which asks for valid input according to a type, or the10{func}`confirm` function, which asks for confirmation (yes/no).1112```{contents}13---14depth: 215local: true16---17```1819(option-prompting)=2021## Option Prompts2223Option prompts are integrated into the option interface. Internally, it automatically calls either {func}`prompt` or24{func}`confirm` as necessary.2526In some cases, you want parameters that can be provided from the command line, but if not provided, ask for user input27instead. This can be implemented with Click by defining a prompt string.2829Example:3031```{eval-rst}32.. click:example::3334 @click.command()35 @click.option('--name', prompt=True)36 def hello(name):37 click.echo(f"Hello {name}!")3839And what it looks like:4041.. click:run::4243 invoke(hello, args=['--name=John'])44 invoke(hello, input=['John'])45```4647If you are not happy with the default prompt string, you can ask for48a different one:4950```{eval-rst}51.. click:example::5253 @click.command()54 @click.option('--name', prompt='Your name please')55 def hello(name):56 click.echo(f"Hello {name}!")5758What it looks like:5960.. click:run::6162 invoke(hello, input=['John'])63```6465It is advised that prompt not be used in conjunction with the multiple flag set to True. Instead, prompt in the function66interactively.6768By default, the user will be prompted for an input if one was not passed through the command line. To turn this behavior69off, see {ref}`optional-value`.7071## Input Prompts7273To manually ask for user input, you can use the {func}`prompt` function. By default, it accepts any Unicode string, but74you can ask for any other type. For instance, you can ask for a valid integer:7576```python77value = click.prompt('Please enter a valid integer', type=int)78```7980Additionally, the type will be determined automatically if a default value is provided. For instance, the following will81only accept floats:8283```python84value = click.prompt('Please enter a number', default=42.0)85```8687## Optional Prompts8889If the option has `prompt` enabled, then setting `prompt_required=False` tells Click to only show the prompt if the90option's flag is given, instead of if the option is not provided at all.9192```{eval-rst}93.. click:example::9495 @click.command()96 @click.option('--name', prompt=True, prompt_required=False, default="Default")97 def hello(name):98 click.echo(f"Hello {name}!")99100.. click:run::101102 invoke(hello)103 invoke(hello, args=["--name", "Value"])104 invoke(hello, args=["--name"], input="Prompt")105```106107If `required=True`, then the option will still prompt if it is not given, but it will also prompt if only the flag is108given.109110## Confirmation Prompts111112To ask if a user wants to continue with an action, the {func}`confirm` function comes in handy. By default, it returns113the result of the prompt as a boolean value:114115```python116if click.confirm('Do you want to continue?'):117 click.echo('Well done!')118```119120There is also the option to make the function automatically abort the execution of the program if it does not return121`True`:122123```python124click.confirm('Do you want to continue?', abort=True)125```126127## Dynamic Defaults for Prompts128129The `auto_envvar_prefix` and `default_map` options for the context allow the program to read option values from the130environment or a configuration file. However, this overrides the prompting mechanism, so that the user does not get the131option to change the value interactively.132133If you want to let the user configure the default value, but still be prompted if the option isn't specified on the134command line, you can do so by supplying a callable as the default value. For example, to get a default from the135environment:136137```python138import os139140@click.command()141@click.option(142 "--username", prompt=True,143 default=lambda: os.environ.get("USER", "")144)145def hello(username):146 click.echo(f"Hello, {username}!")147```148149To describe what the default value will be, set it in ``show_default``.150151```{eval-rst}152.. click:example::153154 import os155156 @click.command()157 @click.option(158 "--username", prompt=True,159 default=lambda: os.environ.get("USER", ""),160 show_default="current user"161 )162 def hello(username):163 click.echo(f"Hello, {username}!")164165.. click:run::166167 invoke(hello, args=["--help"])168```
deleted:docs/prompts.rst-162 removed
1User Input Prompts2==================34.. currentmodule:: click56Click supports prompts in two different places. The first is automated7prompts when the parameter handling happens, and the second is to ask for8prompts at a later point independently.910This can be accomplished with the :func:`prompt` function, which asks for11valid input according to a type, or the :func:`confirm` function, which asks12for confirmation (yes/no).1314.. contents::15 :depth: 216 :local:1718.. _option-prompting:1920Option Prompts21--------------2223Option prompts are integrated into the option interface. Internally, it24automatically calls either :func:`prompt` or :func:`confirm` as necessary.2526In some cases, you want parameters that can be provided from the command line,27but if not provided, ask for user input instead. This can be implemented with28Click by defining a prompt string.2930Example:3132.. click:example::3334 @click.command()35 @click.option('--name', prompt=True)36 def hello(name):37 click.echo(f"Hello {name}!")3839And what it looks like:4041.. click:run::4243 invoke(hello, args=['--name=John'])44 invoke(hello, input=['John'])4546If you are not happy with the default prompt string, you can ask for47a different one:4849.. click:example::5051 @click.command()52 @click.option('--name', prompt='Your name please')53 def hello(name):54 click.echo(f"Hello {name}!")5556What it looks like:5758.. click:run::5960 invoke(hello, input=['John'])6162It is advised that prompt not be used in conjunction with the multiple63flag set to True. Instead, prompt in the function interactively.6465By default, the user will be prompted for an input if one was not passed66through the command line. To turn this behavior off, see67:ref:`optional-value`.6869Input Prompts70-------------7172To manually ask for user input, you can use the :func:`prompt` function.73By default, it accepts any Unicode string, but you can ask for any other74type. For instance, you can ask for a valid integer::7576 value = click.prompt('Please enter a valid integer', type=int)7778Additionally, the type will be determined automatically if a default value is79provided. For instance, the following will only accept floats::8081 value = click.prompt('Please enter a number', default=42.0)8283Optional Prompts84------------------85If the option has ``prompt`` enabled, then setting86``prompt_required=False`` tells Click to only show the prompt if the87option's flag is given, instead of if the option is not provided at all.8889.. click:example::9091 @click.command()92 @click.option('--name', prompt=True, prompt_required=False, default="Default")93 def hello(name):94 click.echo(f"Hello {name}!")9596.. click:run::9798 invoke(hello)99 invoke(hello, args=["--name", "Value"])100 invoke(hello, args=["--name"], input="Prompt")101102If ``required=True``, then the option will still prompt if it is not103given, but it will also prompt if only the flag is given.104105Confirmation Prompts106--------------------107108To ask if a user wants to continue with an action, the :func:`confirm`109function comes in handy. By default, it returns the result of the prompt110as a boolean value::111112 if click.confirm('Do you want to continue?'):113 click.echo('Well done!')114115There is also the option to make the function automatically abort the116execution of the program if it does not return ``True``::117118 click.confirm('Do you want to continue?', abort=True)119120Dynamic Defaults for Prompts121----------------------------122123The ``auto_envvar_prefix`` and ``default_map`` options for the context124allow the program to read option values from the environment or a125configuration file. However, this overrides the prompting mechanism, so126that the user does not get the option to change the value interactively.127128If you want to let the user configure the default value, but still be129prompted if the option isn't specified on the command line, you can do so130by supplying a callable as the default value. For example, to get a default131from the environment:132133.. code-block:: python134135 import os136137 @click.command()138 @click.option(139 "--username", prompt=True,140 default=lambda: os.environ.get("USER", "")141 )142 def hello(username):143 click.echo(f"Hello, {username}!")144145To describe what the default value will be, set it in ``show_default``.146147.. click:example::148149 import os150151 @click.command()152 @click.option(153 "--username", prompt=True,154 default=lambda: os.environ.get("USER", ""),155 show_default="current user"156 )157 def hello(username):158 click.echo(f"Hello, {username}!")159160.. click:run::161162 invoke(hello, args=["--help"])
modified:docs/shell-completion.md+1 added-1 removed
136 unmodified lines
137138## Overriding Value Completion139140Value completions for a parameter can be customized without a custom type by providing a `shell_complete` function. The141function is used instead of any completion provided by the type. It is passed 3 keyword arguments:141function is used instead of any completion provided by the type. It is passed 3 positional arguments:142143- `ctx` - The current command context.144- `param` - The current parameter requesting completion.145- `incomplete` - The partial word that is being completed. May be an empty string if no characters have been entered
104 unmodified lines
modified:src/click/_termui_impl.py+13 added-5 removed
15 unmodified lines
16import typing as t17from gettext import gettext as _18from io import StringIO19from pathlib import Path20from shutil import which20from types import TracebackType2122from ._compat import _default_text_stdout23from ._compat import CYGWIN
209 unmodified lines
233 }234 ).rstrip()235236 def render_progress(self) -> None:238 import shutil239237 if self.hidden:238 return239240 if not self._is_atty:
5 unmodified lines
246247 buf = []248 # Update width in case the terminal has been resized249 if self.autowidth:250 import shutil251252 old_width = self.width253 self.width = 0254 clutter_length = term_len(self.format_progress_line())255 new_width = max(0, shutil.get_terminal_size().columns - clutter_length)
163 unmodified lines
419 """420 # Split the command into the invoked CLI and its parameters.421 if not cmd_parts:422 return False423424 import shutil425426 cmd = cmd_parts[0]427 cmd_params = cmd_parts[1:]428427 cmd_filepath = which(cmd)429 cmd_filepath = shutil.which(cmd)430 if not cmd_filepath:431 return False432 # Resolves symlinks and produces a normalized absolute path string.433 cmd_path = Path(cmd_filepath).resolve()
77 unmodified lines
511 """512 # Split the command into the invoked CLI and its parameters.513 if not cmd_parts:514 return False515516 import shutil517518 cmd = cmd_parts[0]519515 cmd_filepath = which(cmd)520 cmd_filepath = shutil.which(cmd)521 if not cmd_filepath:522 return False523 # Resolves symlinks and produces a normalized absolute path string.524 cmd_path = Path(cmd_filepath).resolve()
52 unmodified lines
577 if rv:578 return rv579 if WIN:580 return "notepad"581582 from shutil import which583584 for editor in "sensible-editor", "vim", "nano":585 if which(editor) is not None:586 return editor587 return "vi"
260 unmodified lines
modified:src/click/formatting.py+2 added-2 removed
117 unmodified lines
118 indent_increment: int = 2,119 width: int | None = None,120 max_width: int | None = None,121 ) -> None:122 import shutil123122 self.indent_increment = indent_increment123 if max_width is None:124 max_width = 80125 if width is None:126 import shutil127128 width = FORCED_WIDTH129 if width is None:130 width = max(min(shutil.get_terminal_size().columns, max_width) - 2, 50)131 self.width = width
170 unmodified lines
modified:src/click/shell_completion.py+2 added
403 unmodified lines
404405 def get_completion_args(self) -> tuple[list[str], str]:406 cwords = split_arg_string(os.environ["COMP_WORDS"])407 incomplete = os.environ["COMP_CWORD"]408 if incomplete:409 incomplete = split_arg_string(incomplete)[0]410 args = cwords[1:]411412 # Fish stores the partial word in both COMP_WORDS and413 # COMP_CWORD, remove it from complete args.
254 unmodified lines
modified:src/click/testing.py+2 added-1 removed
3 unmodified lines
4import contextlib5import io6import os7import shlex8import shutil8import sys9import tempfile10import typing as t11from types import TracebackType
557 unmodified lines
569 finally:570 os.chdir(cwd)571572 if temp_dir is None:573 import shutil574575 try:576 shutil.rmtree(dt)577 except OSError:578 pass
modified:tests/test_imports.py-1 removed
41 unmodified lines
42 "io",43 "itertools",44 "os",45 "re",46 "shutil",46 "stat",47 "struct",48 "sys",49 "threading",
21 unmodified lines
modified:tests/test_shell_completion.py+1 added
357 unmodified lines
358 ("zsh", {"COMP_WORDS": "", "COMP_CWORD": "0"}, "plain\na\n_\nplain\nb\nbee\n"),359 ("zsh", {"COMP_WORDS": "a b", "COMP_CWORD": "1"}, "plain\nb\nbee\n"),360 ("fish", {"COMP_WORDS": "", "COMP_CWORD": ""}, "plain,a\nplain,b\tbee\n"),361 ("fish", {"COMP_WORDS": "a b", "COMP_CWORD": "b"}, "plain,b\tbee\n"),362 ("fish", {"COMP_WORDS": 'a "b', "COMP_CWORD": '"b'}, "plain,b\tbee\n"),363 ],364)365@pytest.mark.usefixtures("_patch_for_completion")366def test_full_complete(runner, shell, env, expect):
195 unmodified lines