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
Provenance
- Commit
2b01f81- Tree
f474861- Author
Rowlando13 <67291205+Rowlando13@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent 1
6965a6a- Parent 2
5b0b7b4
9 files changed+189 added−172 removed
added:docs/prompts.md+168 added
1+# User Input Prompts2+3+```{currentmodule} click4+```5+6+Click supports prompts in two different places. The first is automated prompts when the parameter handling happens, and7+the second is to ask for prompts at a later point independently.8+9+This 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).11+12+```{contents}13+---14+depth: 215+local: true16+---17+```18+19+(option-prompting)=20+21+## Option Prompts22+23+Option prompts are integrated into the option interface. Internally, it automatically calls either {func}`prompt` or24+{func}`confirm` as necessary.25+26+In some cases, you want parameters that can be provided from the command line, but if not provided, ask for user input27+instead. This can be implemented with Click by defining a prompt string.28+29+Example:30+31+```{eval-rst}32+.. click:example::33+34+ @click.command()35+ @click.option('--name', prompt=True)36+ def hello(name):37+ click.echo(f"Hello {name}!")38+39+And what it looks like:40+41+.. click:run::42+43+ invoke(hello, args=['--name=John'])44+ invoke(hello, input=['John'])45+```46+47+If you are not happy with the default prompt string, you can ask for48+a different one:49+50+```{eval-rst}51+.. click:example::52+53+ @click.command()54+ @click.option('--name', prompt='Your name please')55+ def hello(name):56+ click.echo(f"Hello {name}!")57+58+What it looks like:59+60+.. click:run::61+62+ invoke(hello, input=['John'])63+```64+65+It is advised that prompt not be used in conjunction with the multiple flag set to True. Instead, prompt in the function66+interactively.67+68+By default, the user will be prompted for an input if one was not passed through the command line. To turn this behavior69+off, see {ref}`optional-value`.70+71+## Input Prompts72+73+To manually ask for user input, you can use the {func}`prompt` function. By default, it accepts any Unicode string, but74+you can ask for any other type. For instance, you can ask for a valid integer:75+76+```python77+value = click.prompt('Please enter a valid integer', type=int)78+```79+80+Additionally, the type will be determined automatically if a default value is provided. For instance, the following will81+only accept floats:82+83+```python84+value = click.prompt('Please enter a number', default=42.0)85+```86+87+## Optional Prompts88+89+If the option has `prompt` enabled, then setting `prompt_required=False` tells Click to only show the prompt if the90+option's flag is given, instead of if the option is not provided at all.91+92+```{eval-rst}93+.. click:example::94+95+ @click.command()96+ @click.option('--name', prompt=True, prompt_required=False, default="Default")97+ def hello(name):98+ click.echo(f"Hello {name}!")99+100+.. click:run::101+102+ invoke(hello)103+ invoke(hello, args=["--name", "Value"])104+ invoke(hello, args=["--name"], input="Prompt")105+```106+107+If `required=True`, then the option will still prompt if it is not given, but it will also prompt if only the flag is108+given.109+110+## Confirmation Prompts111+112+To ask if a user wants to continue with an action, the {func}`confirm` function comes in handy. By default, it returns113+the result of the prompt as a boolean value:114+115+```python116+if click.confirm('Do you want to continue?'):117+ click.echo('Well done!')118+```119+120+There is also the option to make the function automatically abort the execution of the program if it does not return121+`True`:122+123+```python124+click.confirm('Do you want to continue?', abort=True)125+```126+127+## Dynamic Defaults for Prompts128+129+The `auto_envvar_prefix` and `default_map` options for the context allow the program to read option values from the130+environment or a configuration file. However, this overrides the prompting mechanism, so that the user does not get the131+option to change the value interactively.132+133+If you want to let the user configure the default value, but still be prompted if the option isn't specified on the134+command line, you can do so by supplying a callable as the default value. For example, to get a default from the135+environment:136+137+```python138+import os139+140+@click.command()141+@click.option(142+ "--username", prompt=True,143+ default=lambda: os.environ.get("USER", "")144+)145+def hello(username):146+ click.echo(f"Hello, {username}!")147+```148+149+To describe what the default value will be, set it in ``show_default``.150+151+```{eval-rst}152+.. click:example::153+154+ import os155+156+ @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}!")164+165+.. click:run::166+167+ invoke(hello, args=["--help"])168+```deleted:docs/prompts.rst-162 removed
1-User Input Prompts2-==================3-4-.. currentmodule:: click5-6-Click supports prompts in two different places. The first is automated7-prompts when the parameter handling happens, and the second is to ask for8-prompts at a later point independently.9-10-This can be accomplished with the :func:`prompt` function, which asks for11-valid input according to a type, or the :func:`confirm` function, which asks12-for confirmation (yes/no).13-14-.. contents::15- :depth: 216- :local:17-18-.. _option-prompting:19-20-Option Prompts21---------------22-23-Option prompts are integrated into the option interface. Internally, it24-automatically calls either :func:`prompt` or :func:`confirm` as necessary.25-26-In some cases, you want parameters that can be provided from the command line,27-but if not provided, ask for user input instead. This can be implemented with28-Click by defining a prompt string.29-30-Example:31-32-.. click:example::33-34- @click.command()35- @click.option('--name', prompt=True)36- def hello(name):37- click.echo(f"Hello {name}!")38-39-And what it looks like:40-41-.. click:run::42-43- invoke(hello, args=['--name=John'])44- invoke(hello, input=['John'])45-46-If you are not happy with the default prompt string, you can ask for47-a different one:48-49-.. click:example::50-51- @click.command()52- @click.option('--name', prompt='Your name please')53- def hello(name):54- click.echo(f"Hello {name}!")55-56-What it looks like:57-58-.. click:run::59-60- invoke(hello, input=['John'])61-62-It is advised that prompt not be used in conjunction with the multiple63-flag set to True. Instead, prompt in the function interactively.64-65-By default, the user will be prompted for an input if one was not passed66-through the command line. To turn this behavior off, see67-:ref:`optional-value`.68-69-Input Prompts70--------------71-72-To manually ask for user input, you can use the :func:`prompt` function.73-By default, it accepts any Unicode string, but you can ask for any other74-type. For instance, you can ask for a valid integer::75-76- value = click.prompt('Please enter a valid integer', type=int)77-78-Additionally, the type will be determined automatically if a default value is79-provided. For instance, the following will only accept floats::80-81- value = click.prompt('Please enter a number', default=42.0)82-83-Optional Prompts84-------------------85-If the option has ``prompt`` enabled, then setting86-``prompt_required=False`` tells Click to only show the prompt if the87-option's flag is given, instead of if the option is not provided at all.88-89-.. click:example::90-91- @click.command()92- @click.option('--name', prompt=True, prompt_required=False, default="Default")93- def hello(name):94- click.echo(f"Hello {name}!")95-96-.. click:run::97-98- invoke(hello)99- invoke(hello, args=["--name", "Value"])100- invoke(hello, args=["--name"], input="Prompt")101-102-If ``required=True``, then the option will still prompt if it is not103-given, but it will also prompt if only the flag is given.104-105-Confirmation Prompts106---------------------107-108-To ask if a user wants to continue with an action, the :func:`confirm`109-function comes in handy. By default, it returns the result of the prompt110-as a boolean value::111-112- if click.confirm('Do you want to continue?'):113- click.echo('Well done!')114-115-There is also the option to make the function automatically abort the116-execution of the program if it does not return ``True``::117-118- click.confirm('Do you want to continue?', abort=True)119-120-Dynamic Defaults for Prompts121-----------------------------122-123-The ``auto_envvar_prefix`` and ``default_map`` options for the context124-allow the program to read option values from the environment or a125-configuration file. However, this overrides the prompting mechanism, so126-that the user does not get the option to change the value interactively.127-128-If you want to let the user configure the default value, but still be129-prompted if the option isn't specified on the command line, you can do so130-by supplying a callable as the default value. For example, to get a default131-from the environment:132-133-.. code-block:: python134-135- import os136-137- @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}!")144-145-To describe what the default value will be, set it in ``show_default``.146-147-.. click:example::148-149- import os150-151- @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}!")159-160-.. click:run::161-162- invoke(hello, args=["--help"])modified:docs/shell-completion.md+1 added-1 removed
136 unmodified lines137 138 ## Overriding Value Completion139 140 Value completions for a parameter can be customized without a custom type by providing a `shell_complete` function. The141-function is used instead of any completion provided by the type. It is passed 3 keyword arguments:141+function is used instead of any completion provided by the type. It is passed 3 positional arguments:142 143 - `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 entered104 unmodified linesmodified:src/click/_termui_impl.py+13 added-5 removed
15 unmodified lines16 import typing as t17 from gettext import gettext as _18 from io import StringIO19 from pathlib import Path20-from shutil import which20 from types import TracebackType21 22 from ._compat import _default_text_stdout23 from ._compat import CYGWIN209 unmodified lines233 }234 ).rstrip()235 236 def render_progress(self) -> None:238- import shutil239-237 if self.hidden:238 return239 240 if not self._is_atty:5 unmodified lines246 247 buf = []248 # Update width in case the terminal has been resized249 if self.autowidth:250+ import shutil251+252 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 lines419 """420 # Split the command into the invoked CLI and its parameters.421 if not cmd_parts:422 return False423+424+ import shutil425+426 cmd = cmd_parts[0]427 cmd_params = cmd_parts[1:]428 427- 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 lines511 """512 # Split the command into the invoked CLI and its parameters.513 if not cmd_parts:514 return False515+516+ import shutil517+518 cmd = cmd_parts[0]519 515- 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 lines577 if rv:578 return rv579 if WIN:580 return "notepad"581+582+ from shutil import which583+584 for editor in "sensible-editor", "vim", "nano":585 if which(editor) is not None:586 return editor587 return "vi"260 unmodified linesmodified:src/click/formatting.py+2 added-2 removed
117 unmodified lines118 indent_increment: int = 2,119 width: int | None = None,120 max_width: int | None = None,121 ) -> None:122- import shutil123-122 self.indent_increment = indent_increment123 if max_width is None:124 max_width = 80125 if width is None:126+ import shutil127+128 width = FORCED_WIDTH129 if width is None:130 width = max(min(shutil.get_terminal_size().columns, max_width) - 2, 50)131 self.width = width170 unmodified linesmodified:src/click/shell_completion.py+2 added
403 unmodified lines404 405 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:]411 412 # Fish stores the partial word in both COMP_WORDS and413 # COMP_CWORD, remove it from complete args.254 unmodified linesmodified:src/click/testing.py+2 added-1 removed
3 unmodified lines4 import contextlib5 import io6 import os7 import shlex8-import shutil8 import sys9 import tempfile10 import typing as t11 from types import TracebackType557 unmodified lines569 finally:570 os.chdir(cwd)571 572 if temp_dir is None:573+ import shutil574+575 try:576 shutil.rmtree(dt)577 except OSError:578 passmodified:tests/test_imports.py-1 removed
41 unmodified lines42 "io",43 "itertools",44 "os",45 "re",46- "shutil",46 "stat",47 "struct",48 "sys",49 "threading",21 unmodified linesmodified:tests/test_shell_completion.py+1 added
357 unmodified lines358 ("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")366 def test_full_complete(runner, shell, env, expect):195 unmodified lines