Skip to content
Myr

Merge Stable into Main (#3114)

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

authored by Rowlando13 · committed by GitHub · parents 309ce91, 868b611 · Browse files · 18 files+768 added−355 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+768 added−355 removed

  • tests:+160 added−9 removed
  • other:+608 added−346 removed

18 files+768 added−355 removed

added:docs/api.md+353 added
1# API23```{currentmodule} click4```56This part of the documentation lists the full API reference of all public7classes and functions.89```{contents}10:depth: 111:local: true12```1314## Decorators1516```{eval-rst}17.. autofunction:: command18```1920```{eval-rst}21.. autofunction:: group22```2324```{eval-rst}25.. autofunction:: argument26```2728```{eval-rst}29.. autofunction:: option30```3132```{eval-rst}33.. autofunction:: password_option34```3536```{eval-rst}37.. autofunction:: confirmation_option38```3940```{eval-rst}41.. autofunction:: version_option42```4344```{eval-rst}45.. autofunction:: help_option46```4748```{eval-rst}49.. autofunction:: pass_context50```5152```{eval-rst}53.. autofunction:: pass_obj54```5556```{eval-rst}57.. autofunction:: make_pass_decorator58```5960```{eval-rst}61.. autofunction:: click.decorators.pass_meta_key6263```6465## Utilities6667```{eval-rst}68.. autofunction:: echo69```7071```{eval-rst}72.. autofunction:: echo_via_pager73```7475```{eval-rst}76.. autofunction:: prompt77```7879```{eval-rst}80.. autofunction:: confirm81```8283```{eval-rst}84.. autofunction:: progressbar85```8687```{eval-rst}88.. autofunction:: clear89```9091```{eval-rst}92.. autofunction:: style93```9495```{eval-rst}96.. autofunction:: unstyle97```9899```{eval-rst}100.. autofunction:: secho101```102103```{eval-rst}104.. autofunction:: edit105```106107```{eval-rst}108.. autofunction:: launch109```110111```{eval-rst}112.. autofunction:: getchar113```114115```{eval-rst}116.. autofunction:: pause117```118119```{eval-rst}120.. autofunction:: get_binary_stream121```122123```{eval-rst}124.. autofunction:: get_text_stream125```126127```{eval-rst}128.. autofunction:: open_file129```130131```{eval-rst}132.. autofunction:: get_app_dir133```134135```{eval-rst}136.. autofunction:: format_filename137```138139## Commands140141```{eval-rst}142.. autoclass:: BaseCommand143 :members:144```145146```{eval-rst}147.. autoclass:: Command148 :members:149```150151```{eval-rst}152.. autoclass:: MultiCommand153 :members:154```155156```{eval-rst}157.. autoclass:: Group158 :members:159```160161```{eval-rst}162.. autoclass:: CommandCollection163 :members:164```165166## Parameters167168```{eval-rst}169.. autoclass:: Parameter170 :members:171```172173```{eval-rst}174.. autoclass:: Option175```176177```{eval-rst}178.. autoclass:: Argument179```180181## Context182183```{eval-rst}184.. autoclass:: Context185 :members:186```187188```{eval-rst}189.. autofunction:: get_current_context190```191192```{eval-rst}193.. autoclass:: click.core.ParameterSource194 :members:195 :member-order: bysource196```197198(click-api-types)=199200## Types201202```{eval-rst}203.. autodata:: STRING204```205206```{eval-rst}207.. autodata:: INT208```209210```{eval-rst}211.. autodata:: FLOAT212```213214```{eval-rst}215.. autodata:: BOOL216```217218```{eval-rst}219.. autodata:: UUID220```221222```{eval-rst}223.. autodata:: UNPROCESSED224```225226```{eval-rst}227.. autoclass:: File228```229230```{eval-rst}231.. autoclass:: Path232```233234```{eval-rst}235.. autoclass:: Choice236 :members:237```238239```{eval-rst}240.. autoclass:: IntRange241```242243```{eval-rst}244.. autoclass:: FloatRange245```246247```{eval-rst}248.. autoclass:: DateTime249```250251```{eval-rst}252.. autoclass:: Tuple253```254255```{eval-rst}256.. autoclass:: ParamType257 :members:258```259260## Exceptions261262```{eval-rst}263.. autoexception:: ClickException264```265266```{eval-rst}267.. autoexception:: Abort268```269270```{eval-rst}271.. autoexception:: UsageError272```273274```{eval-rst}275.. autoexception:: BadParameter276```277278```{eval-rst}279.. autoexception:: FileError280```281282```{eval-rst}283.. autoexception:: NoSuchOption284```285286```{eval-rst}287.. autoexception:: BadOptionUsage288```289290```{eval-rst}291.. autoexception:: BadArgumentUsage292```293294## Formatting295296```{eval-rst}297.. autoclass:: HelpFormatter298 :members:299```300301```{eval-rst}302.. autofunction:: wrap_text303```304305## Parsing306307```{eval-rst}308.. autoclass:: OptionParser309 :members:310311```312313## Shell Completion314315See {doc}`/shell-completion` for information about enabling and316customizing Click's shell completion system.317318```{eval-rst}319.. currentmodule:: click.shell_completion320```321322```{eval-rst}323.. autoclass:: CompletionItem324```325326```{eval-rst}327.. autoclass:: ShellComplete328 :members:329 :member-order: bysource330```331332```{eval-rst}333.. autofunction:: add_completion_class334335```336337(testing)=338339## Testing340341```{eval-rst}342.. currentmodule:: click.testing343```344345```{eval-rst}346.. autoclass:: CliRunner347 :members:348```349350```{eval-rst}351.. autoclass:: Result352 :members:353```
deleted:docs/api.rst-217 removed
1API2===34.. module:: click56This part of the documentation lists the full API reference of all public7classes and functions.89.. contents::10 :depth: 111 :local:1213Decorators14----------1516.. autofunction:: command1718.. autofunction:: group1920.. autofunction:: argument2122.. autofunction:: option2324.. autofunction:: password_option2526.. autofunction:: confirmation_option2728.. autofunction:: version_option2930.. autofunction:: help_option3132.. autofunction:: pass_context3334.. autofunction:: pass_obj3536.. autofunction:: make_pass_decorator3738.. autofunction:: click.decorators.pass_meta_key394041Utilities42---------4344.. autofunction:: echo4546.. autofunction:: echo_via_pager4748.. autofunction:: prompt4950.. autofunction:: confirm5152.. autofunction:: progressbar5354.. autofunction:: clear5556.. autofunction:: style5758.. autofunction:: unstyle5960.. autofunction:: secho6162.. autofunction:: edit6364.. autofunction:: launch6566.. autofunction:: getchar6768.. autofunction:: pause6970.. autofunction:: get_binary_stream7172.. autofunction:: get_text_stream7374.. autofunction:: open_file7576.. autofunction:: get_app_dir7778.. autofunction:: format_filename7980Commands81--------8283.. autoclass:: BaseCommand84 :members:8586.. autoclass:: Command87 :members:8889.. autoclass:: MultiCommand90 :members:9192.. autoclass:: Group93 :members:9495.. autoclass:: CommandCollection96 :members:9798Parameters99----------100101.. autoclass:: Parameter102 :members:103104.. autoclass:: Option105106.. autoclass:: Argument107108Context109-------110111.. autoclass:: Context112 :members:113114.. autofunction:: get_current_context115116.. autoclass:: click.core.ParameterSource117 :members:118 :member-order: bysource119120.. _click-api-types:121122Types123-----124125.. autodata:: STRING126127.. autodata:: INT128129.. autodata:: FLOAT130131.. autodata:: BOOL132133.. autodata:: UUID134135.. autodata:: UNPROCESSED136137.. autoclass:: File138139.. autoclass:: Path140141.. autoclass:: Choice142 :members:143144.. autoclass:: IntRange145146.. autoclass:: FloatRange147148.. autoclass:: DateTime149150.. autoclass:: Tuple151152.. autoclass:: ParamType153 :members:154155Exceptions156----------157158.. autoexception:: ClickException159160.. autoexception:: Abort161162.. autoexception:: UsageError163164.. autoexception:: BadParameter165166.. autoexception:: FileError167168.. autoexception:: NoSuchOption169170.. autoexception:: BadOptionUsage171172.. autoexception:: BadArgumentUsage173174Formatting175----------176177.. autoclass:: HelpFormatter178 :members:179180.. autofunction:: wrap_text181182Parsing183-------184185.. autoclass:: OptionParser186 :members:187188189Shell Completion190----------------191192See :doc:`/shell-completion` for information about enabling and193customizing Click's shell completion system.194195.. currentmodule:: click.shell_completion196197.. autoclass:: CompletionItem198199.. autoclass:: ShellComplete200 :members:201 :member-order: bysource202203.. autofunction:: add_completion_class204205206.. _testing:207208Testing209-------210211.. currentmodule:: click.testing212213.. autoclass:: CliRunner214 :members:215216.. autoclass:: Result217 :members:
added:docs/command-line-reference.md+48 added
added:docs/handling-files.md+102 added
1(handling-files)=23# Handling Files45```{currentmodule} click6```78Click has built in features to support file and file path handling. The examples use arguments but the same principle9applies to options as well.1011(file-args)=1213## File Arguments1415Click supports working with files with the {class}`File` type. Some notable features are:1617- Support for `-` to mean a special file that refers to stdin when used for reading, and stdout when used for writing.18 This is a common pattern for POSIX command line utilities.19- Deals with `str` and `bytes` correctly for all versions of Python.2021Example:2223```{eval-rst}24.. click:example::2526 @click.command()27 @click.argument('input', type=click.File('rb'))28 @click.argument('output', type=click.File('wb'))29 def inout(input, output):30 """Copy contents of INPUT to OUTPUT."""31 while True:32 chunk = input.read(1024)33 if not chunk:34 break35 output.write(chunk)3637And from the command line:3839.. click:run::4041 with isolated_filesystem():42 invoke(inout, args=['-', 'hello.txt'], input=['hello'],43 terminate_input=True)44 invoke(inout, args=['hello.txt', '-'])45```4647## File Path Arguments4849For handling paths, the {class}`Path` type is better than a `str`. Some notable features are:5051- The `exists` argument will verify whether the path exists.52- `readable`, `writable`, and `executable` can perform permission checks.53- `file_okay` and `dir_okay` allow specifying whether files/directories are accepted.54- Error messages are nicely formatted using {func}`format_filename` so any undecodable bytes will be printed nicely.5556See {class}`Path` for all features.5758Example:5960```{eval-rst}61.. click:example::6263 @click.command()64 @click.argument('filename', type=click.Path(exists=True))65 def touch(filename):66 """Print FILENAME if the file exists."""67 click.echo(click.format_filename(filename))6869And from the command line:7071.. click:run::7273 with isolated_filesystem():74 with open('hello.txt', 'w') as f:75 f.write('Hello World!\n')76 invoke(touch, args=['hello.txt'])77 println()78 invoke(touch, args=['missing.txt'])79```8081## File Opening Behaviors8283The {class}`File` type attempts to be "intelligent" about when to open a file. Stdin/stdout and files opened for reading84will be opened immediately. This will give the user direct feedback when a file cannot be opened. Files opened for85writing will only be open on the first IO operation. This is done by automatically wrapping the file in a special86wrapper.8788File open behavior can be controlled by the boolean kwarg `lazy`. If a file is opened lazily:8990- A failure at first IO operation will happen by raising an {exc}`FileError`.91- It can help minimize resource handling confusion. If a file is opened in lazy mode, it will call92 {meth}`LazyFile.close_intelligently` to help figure out if the file needs closing or not. This is not needed for93 parameters, but is necessary for manually prompting. For manual prompts with the {func}`prompt` function you do not94 know if a stream like stdout was opened (which was already open before) or a real file was opened (that needs95 closing).9697Since files opened for writing will typically empty the file, the lazy mode should only be disabled if the developer is98absolutely sure that this is intended behavior.99100It is also possible to open files in atomic mode by passing `atomic=True`. In atomic mode, all writes go into a separate101file in the same folder, and upon completion, the file will be moved over to the original location. This is useful if a102file regularly read by other users is modified.
deleted:docs/handling-files.rst-90 removed
1.. _handling-files:23Handling Files4================56.. currentmodule:: click78Click has built in features to support file and file path handling. The examples use arguments but the same principle applies to options as well.910.. _file-args:1112File Arguments13-----------------1415Click supports working with files with the :class:`File` type. Some notable features are:1617* Support for ``-`` to mean a special file that refers to stdin when used for reading, and stdout when used for writing. This is a common pattern for POSIX command line utilities.18* Deals with ``str`` and ``bytes`` correctly for all versions of Python.1920Example:2122.. click:example::2324 @click.command()25 @click.argument('input', type=click.File('rb'))26 @click.argument('output', type=click.File('wb'))27 def inout(input, output):28 """Copy contents of INPUT to OUTPUT."""29 while True:30 chunk = input.read(1024)31 if not chunk:32 break33 output.write(chunk)3435And from the command line:3637.. click:run::3839 with isolated_filesystem():40 invoke(inout, args=['-', 'hello.txt'], input=['hello'],41 terminate_input=True)42 invoke(inout, args=['hello.txt', '-'])4344File Path Arguments45----------------------4647For handling paths, the :class:`Path` type is better than a ``str``. Some notable features are:4849* The ``exists`` argument will verify whether the path exists.50* ``readable``, ``writable``, and ``executable`` can perform permission checks.51* ``file_okay`` and ``dir_okay`` allow specifying whether files/directories are accepted.52* Error messages are nicely formatted using :func:`format_filename` so any undecodable bytes will be printed nicely.5354See :class:`Path` for all features.5556Example:5758.. click:example::5960 @click.command()61 @click.argument('filename', type=click.Path(exists=True))62 def touch(filename):63 """Print FILENAME if the file exists."""64 click.echo(click.format_filename(filename))6566And from the command line:6768.. click:run::6970 with isolated_filesystem():71 with open('hello.txt', 'w') as f:72 f.write('Hello World!\n')73 invoke(touch, args=['hello.txt'])74 println()75 invoke(touch, args=['missing.txt'])767778File Opening Behaviors79-----------------------------8081The :class:`File` type attempts to be "intelligent" about when to open a file. Stdin/stdout and files opened for reading will be opened immediately. This will give the user direct feedback when a file cannot be opened. Files opened for writing will only be open on the first IO operation. This is done by automatically wrapping the file in a special wrapper.8283File open behavior can be controlled by the boolean kwarg ``lazy``. If a file is opened lazily:8485* A failure at first IO operation will happen by raising an :exc:`FileError`.86* It can help minimize resource handling confusion. If a file is opened in lazy mode, it will call :meth:`LazyFile.close_intelligently` to help figure out if the file needs closing or not. This is not needed for parameters, but is necessary for manually prompting. For manual prompts with the :func:`prompt` function you do not know if a stream like stdout was opened (which was already open before) or a real file was opened (that needs closing).8788Since files opened for writing will typically empty the file, the lazy mode should only be disabled if the developer is absolutely sure that this is intended behavior.8990It is also possible to open files in atomic mode by passing ``atomic=True``. In atomic mode, all writes go into a separate file in the same folder, and upon completion, the file will be moved over to the original location. This is useful if a file regularly read by other users is modified.
modified:docs/index.rst+1 added
110 unmodified lines
111 testing112 utils113 shell-completion114 exceptions115 command-line-reference116 unicode-support117 wincmd118119API Reference
24 unmodified lines
added:docs/license.md+7 added
deleted:docs/license.rst-5 removed
1BSD-3-Clause License2====================34.. literalinclude:: ../LICENSE.txt5 :language: text
modified:docs/options.md+12 added-5 removed
129 unmodified lines
130```131132## Multi Value Options133134To make an option take multiple values, pass in `nargs`. Note only a fixed number of arguments is supported. The values are passed to the underlying function as a tuple.134To make an option take multiple values, pass in `nargs`. Note you may pass in any positive integer, but not -1. The values are passed to the underlying function as a tuple.135136```{eval-rst}137.. click:example::138
55 unmodified lines
194(multiple-options)=195196## Multiple Options197198The multiple options format allows you to call the underlying function multiple times with one command line entry. If set, the default must be a list or tuple. Setting a string as a default will be interpreted as list of characters.198The multiple options format allows options to take an arbitrary number of arguments (which is called variadic). The arguments are passed to the underlying function as a tuple. If set, the default must be a list or tuple. Setting a string as a default will be interpreted as list of characters.199200```{eval-rst}201.. click:example::202203 @click.command()204 @click.option('--message', '-m', multiple=True)205 def commit(message):206 click.echo('\n'.join(message))206 click.echo(message)207 for m in message:208 click.echo(m)209210.. click:run::211212 invoke(commit, args=['-m', 'foo', '-m', 'bar', '-m', 'here'])
43 unmodified lines
256 invoke(info, args=['--shout'])257258```259258To implement this more explicitly, pass in on-option `/` off-option. Click will automatically set `is_flag=True`. Click always wants you to provide an enable259and disable flag so that you can change the default later.260To implement this more explicitly, pass in on-option `/` off-option. Click will automatically set `is_flag=True`.261262```{eval-rst}263.. click:example::264
13 unmodified lines
278 invoke(info, args=['--shout'])279 invoke(info, args=['--no-shout'])280```281282Use cases for this more explicit pattern include:283284* The default can be dynamic so the user can explicitly specify the option with either on or off option, or pass in no option to use the dynamic default.285* Shell scripts sometimes want to be explicit even when it's the default286* Shell aliases can set a flag, then an invocation can add a negation of the flag287288If a forward slash(`/`) is contained in your option name already, you can split the parameters using `;`. In Windows `/` is commonly used as the prefix character.289290```{eval-rst}291.. click:example::
213 unmodified lines
modified:src/click/_termui_impl.py+9 added-4 removed
427 unmodified lines
428429 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()432433 # Produces a normalized absolute path string.434 # multi-call binaries such as busybox derive their identity from the symlink435 # less -> busybox. resolve() causes them to misbehave. (eg. less becomes busybox)436 cmd_path = Path(cmd_filepath).absolute()437 cmd_name = cmd_path.name438439 import subprocess440
81 unmodified lines
522523 cmd_filepath = shutil.which(cmd)524 if not cmd_filepath:525 return False523 # Resolves symlinks and produces a normalized absolute path string.524 cmd_path = Path(cmd_filepath).resolve()526 # Produces a normalized absolute path string.527 # multi-call binaries such as busybox derive their identity from the symlink528 # less -> busybox. resolve() causes them to misbehave. (eg. less becomes busybox)529 cmd_path = Path(cmd_filepath).absolute()530531 import subprocess532 import tempfile533
319 unmodified lines
modified:src/click/core.py+53 added-15 removed
797 unmodified lines
798 ctx = self._make_sub_context(other_cmd)799800 for param in other_cmd.params:801 if param.name not in kwargs and param.expose_value:802 default_value = param.get_default(ctx)803 # We explicitly hide the :attr:`UNSET` value to the user, as we804 # choose to make it an implementation detail. And because ``invoke``805 # has been designed as part of Click public API, we return ``None``806 # instead. Refs:807 # https://github.com/pallets/click/issues/3066808 # https://github.com/pallets/click/issues/3065809 # https://github.com/pallets/click/pull/3068810 if default_value is UNSET:811 default_value = None812 kwargs[param.name] = param.type_cast_value( # type: ignore803 ctx, param.get_default(ctx)813 ctx, default_value814 )815816 # Track all kwargs as params, so that forward() will pass817 # them on in subsequent calls.
407 unmodified lines
12251226 for param in iter_params_for_processing(param_order, self.get_params(ctx)):1227 _, args = param.handle_parse_result(ctx, opts, args)12281229 # We now have all parameters' values into `ctx.params`, but the data may contain1230 # the `UNSET` sentinel.1231 # Convert `UNSET` to `None` to ensure that the user doesn't see `UNSET`.1232 #1233 # Waiting until after the initial parse to convert allows us to treat `UNSET`1234 # more like a missing value when multiple params use the same name.1235 # Refs:1236 # https://github.com/pallets/click/issues/30711237 # https://github.com/pallets/click/pull/30791238 for name, value in ctx.params.items():1239 if value is UNSET:1240 ctx.params[name] = None12411242 if args and not ctx.allow_extra_args and not ctx.resilient_parsing:1243 ctx.fail(1244 ngettext(1245 "Got unexpected extra argument ({args})",
1091 unmodified lines
2337 def type_cast_value(self, ctx: Context, value: t.Any) -> t.Any:2338 """Convert and validate a value against the parameter's2339 :attr:`type`, :attr:`multiple`, and :attr:`nargs`.2340 """2318 if value in (None, UNSET):2341 if value is None:2342 if self.multiple or self.nargs == -1:2343 return ()2344 else:2345 return value
74 unmodified lines
2420 the :attr:`UNSET` sentinel.24212422 :meta private:2423 """2424 # shelter `type_cast_value` from ever seeing an `UNSET` value by handling the2425 # cases in which `UNSET` gets special treatment explicitly at this layer2426 #2427 # Refs:2428 # https://github.com/pallets/click/issues/30692429 if value is UNSET:2430 if self.multiple or self.nargs == -1:2431 value = ()2432 else:2401 value = self.type_cast_value(ctx, value)2433 value = self.type_cast_value(ctx, value)24342435 if self.required and self.value_is_missing(value):2436 raise MissingParameter(ctx=ctx, param=self)2437
121 unmodified lines
2559 self.expose_value2560 # We skip adding the value if it was previously set by another parameter2561 # targeting the same variable name. This prevents parameters competing for2562 # the same name to override each other.2531 and self.name not in ctx.params2563 and (self.name not in ctx.params or ctx.params[self.name] is UNSET)2564 ):2565 # Click is logically enforcing that the name is None if the parameter is2566 # not to be exposed. We still assert it here to please the type checker.2567 assert self.name is not None, (2568 f"{self!r} parameter's name should not be None when exposing value."2569 )2538 # Normalize UNSET values to None, as we're about to pass them to the2539 # command function and move them to the pure-Python realm of user-written2540 # code.2541 ctx.params[self.name] = value if value is not UNSET else None2570 ctx.params[self.name] = value25712572 return value, args25732574 def get_help_record(self, ctx: Context) -> tuple[str, str] | None:
689 unmodified lines
3264 source = ParameterSource.PROMPT32653266 return value, source32673239 def type_cast_value(self, ctx: Context, value: t.Any) -> t.Any:3240 if self.is_flag and not self.required:3241 if value is UNSET:3242 if self.is_bool_flag:3243 # If the flag is a boolean flag, we return False if it is not set.3244 value = False3245 return super().type_cast_value(ctx, value)3268 def process_value(self, ctx: Context, value: t.Any) -> t.Any:3269 # process_value has to be overridden on Options in order to capture3270 # `value == UNSET` cases before `type_cast_value()` gets called.3271 #3272 # Refs:3273 # https://github.com/pallets/click/issues/30693274 if self.is_flag and not self.required and self.is_bool_flag and value is UNSET:3275 value = False32763277 if self.callback is not None:3278 value = self.callback(ctx, self, value)32793280 return value32813282 # in the normal case, rely on Parameter.process_value3283 return super().process_value(ctx, value)328432853286class Argument(Parameter):3287 """Arguments are positional parameters to a command. They generally3288 provide fewer features than options but can have infinite ``nargs``3289 and are required by default.
96 unmodified lines
modified:src/click/termui.py+12 added-6 removed
117 unmodified lines
118 For example if type is a Choice of either day or week,119 show_choices is true and text is "Group by" then the120 prompt will be "Group by (day, week): ".121122 .. versionchanged:: 8.3.1123 A space is no longer appended to the prompt.124125 .. versionadded:: 8.0126 ``confirmation_prompt`` can be a custom string.127128 .. versionadded:: 7.0
11 unmodified lines
140 f = hidden_prompt_func if hide_input else visible_prompt_func141 try:142 # Write the prompt separately so that we get nice143 # coloring through colorama on Windows141 echo(text.rstrip(" "), nl=False, err=err)142 # Echo a space to stdout to work around an issue where144 echo(text[:-1], nl=False, err=err)145 # Echo the last character to stdout to work around an issue where146 # readline causes backspace to clear the whole line.144 return f(" ")147 return f(text[-1:])148 except (KeyboardInterrupt, EOFError):149 # getpass doesn't print a newline if the user aborts input with ^C.150 # Allegedly this behavior is inherited from getpass(3).151 # A doc bug has been filed at https://bugs.python.org/issue24711
64 unmodified lines
216 :param show_default: shows or hides the default value in the prompt.217 :param err: if set to true the file defaults to ``stderr`` instead of218 ``stdout``, the same as with echo.219220 .. versionchanged:: 8.3.1221 A space is no longer appended to the prompt.222223 .. versionchanged:: 8.0224 Repeat until input is given if ``default`` is ``None``.225226 .. versionadded:: 4.0
9 unmodified lines
236 while True:237 try:238 # Write the prompt separately so that we get nice239 # coloring through colorama on Windows234 echo(prompt.rstrip(" "), nl=False, err=err)235 # Echo a space to stdout to work around an issue where240 echo(prompt[:-1], nl=False, err=err)241 # Echo the last character to stdout to work around an issue where242 # readline causes backspace to clear the whole line.237 value = visible_prompt_func(" ").lower().strip()243 value = visible_prompt_func(prompt[-1:]).lower().strip()244 except (KeyboardInterrupt, EOFError):245 raise Abort() from None246 if value in ("y", "yes"):247 rv = True
636 unmodified lines
modified:tests/test_arguments.py+37 added
577 unmodified lines
578 pass579580 with pytest.warns(UserWarning):581 runner.invoke(cli, [])582583584@pytest.mark.parametrize(585 ("argument_kwargs", "pass_argv"),586 (587 # there is a large potential parameter space to explore here588 # this is just a very small sample of it589 ({}, ["myvalue"]),590 ({"nargs": -1}, []),591 ({"nargs": -1}, ["myvalue"]),592 ({"default": None}, ["myvalue"]),593 ({"required": False}, []),594 ({"required": False}, ["myvalue"]),595 ),596)597def test_argument_custom_class_can_override_type_cast_value_and_never_sees_unset(598 runner, argument_kwargs, pass_argv599):600 """601 Test that overriding type_cast_value is supported602603 In particular, the argument is never passed an UNSET sentinel value.604 """605606 class CustomArgument(click.Argument):607 def type_cast_value(self, ctx, value):608 assert value is not UNSET609 return value610611 @click.command()612 @click.argument("myarg", **argument_kwargs, cls=CustomArgument)613 def cmd(myarg):614 click.echo("ok")615616 result = runner.invoke(cmd, pass_argv)617 assert not result.exception618 assert result.exit_code == 0
modified:tests/test_commands.py+37 added-9 removed
226 unmodified lines
227 assert result.exception is None228 assert result.output == "Debug is off\n"229230231@pytest.mark.parametrize(232 ("opt_params", "expected"),233 (234 # Original tests.235 ({"type": click.INT, "default": 42}, 42),236 ({"type": click.INT, "default": "15"}, 15),237 ({"multiple": True}, ()),238 # SENTINEL value tests.239 ({"default": None}, None),240 ({"type": click.STRING}, None), # No default specified, should be None.241 ({"type": click.BOOL, "default": False}, False),242 ({"type": click.BOOL, "default": True}, True),243 ({"type": click.FLOAT, "default": 3.14}, 3.14),244 # Multiple with default.245 ({"multiple": True, "default": [1, 2, 3]}, (1, 2, 3)),246 ({"multiple": True, "default": ()}, ()),247 # Required option without value should use SENTINEL behavior.248 ({"required": False}, None),249 # Choice type with default.250 ({"type": click.Choice(["a", "b", "c"]), "default": "b"}, "b"),251 # Path type with default.252 ({"type": click.Path(), "default": "/tmp"}, "/tmp"),253 # Flag options.254 ({"is_flag": True, "default": False}, False),255 ({"is_flag": True, "default": True}, True),256 # Count option.257 ({"count": True}, 0),258 # Hidden option.259 ({"hidden": True, "default": "secret"}, "secret"),260 ),261)231def test_other_command_invoke_with_defaults(runner):262def test_other_command_invoke_with_defaults(runner, opt_params, expected):263 @click.command()264 @click.pass_context265 def cli(ctx):266 return ctx.invoke(other_cmd)267268 @click.command()238 @click.option("-a", type=click.INT, default=42)239 @click.option("-b", type=click.INT, default="15")240 @click.option("-c", multiple=True)269 @click.option("-a", **opt_params)270 @click.pass_context242 def other_cmd(ctx, a, b, c):243 return ctx.info_name, a, b, c271 def other_cmd(ctx, a):272 return ctx.info_name, a273274 result = runner.invoke(cli, standalone_mode=False)246 # invoke should type cast default values, str becomes int, empty247 # multiple should be empty tuple instead of None248 assert result.return_value == ("other", 42, 15, ())275276 assert result.return_value == ("other", expected)277278279def test_invoked_subcommand(runner):280 @click.group(invoke_without_command=True)281 @click.pass_context282 def cli(ctx):
293 unmodified lines
modified:tests/test_defaults.py+26 added
82 unmodified lines
83 assert "True" in result.output8485 result = runner.invoke(cli, ["foo", "--help"], default_map={"foo": {"name": True}})86 assert "default: name" in result.output878889def test_shared_param_prefers_first_default(runner):90 """test that the first default is chosen when multiple flags share a param name"""9192 @click.command93 @click.option("--red", "color", flag_value="red")94 @click.option("--green", "color", flag_value="green", default=True)95 def prefers_green(color):96 click.echo(color)9798 @click.command99 @click.option("--red", "color", flag_value="red", default=True)100 @click.option("--green", "color", flag_value="green")101 def prefers_red(color):102 click.echo(color)103104 result = runner.invoke(prefers_green, [])105 assert "green" in result.output106 result = runner.invoke(prefers_green, ["--red"])107 assert "red" in result.output108109 result = runner.invoke(prefers_red, [])110 assert "red" in result.output111 result = runner.invoke(prefers_red, ["--green"])112 assert "green" in result.output
modified:tests/test_options.py+36 added
1010 unmodified lines
1011 assert "I am a help text" in result.output1012 assert "you wont see me" not in result.output101310141015@pytest.mark.parametrize(1016 ("param_decl", "option_kwargs", "pass_argv"),1017 (1018 # there is a large potential parameter space to explore here1019 # this is just a very small sample of it1020 ("--opt", {}, []),1021 ("--opt", {"multiple": True}, []),1022 ("--opt", {"is_flag": True}, []),1023 ("--opt/--no-opt", {"is_flag": True, "default": None}, []),1024 ("--req", {"is_flag": True, "required": True}, ["--req"]),1025 ),1026)1027def test_option_custom_class_can_override_type_cast_value_and_never_sees_unset(1028 runner, param_decl, option_kwargs, pass_argv1029):1030 """1031 Test that overriding type_cast_value is supported10321033 In particular, the option is never passed an UNSET sentinel value.1034 """10351036 class CustomOption(click.Option):1037 def type_cast_value(self, ctx, value):1038 assert value is not UNSET1039 return value10401041 @click.command()1042 @click.option("myparam", param_decl, **option_kwargs, cls=CustomOption)1043 def cmd(myparam):1044 click.echo("ok")10451046 result = runner.invoke(cmd, pass_argv)1047 assert not result.exception1048 assert result.exit_code == 0104910501051def test_option_custom_class_reusable(runner):1052 """Ensure we can reuse a custom class option. See Issue #926"""10531054 class CustomOption(click.Option):
1223 unmodified lines
modified:tests/test_utils.py+24 added
480 unmodified lines
481 assert out == "Prompt to stdin: "482 assert err == ""483484 emulate_input("asdlkj\n")485 click.prompt("Prompt to stdin with no suffix", prompt_suffix="")486 out, err = capfd.readouterr()487 assert out == "Prompt to stdin with no suffix"488 assert err == ""489490 emulate_input("asdlkj\n")491 click.prompt("Prompt to stderr", err=True)492 out, err = capfd.readouterr()493 assert out == " "494 assert err == "Prompt to stderr:"495496 emulate_input("asdlkj\n")497 click.prompt("Prompt to stderr with no suffix", prompt_suffix="", err=True)498 out, err = capfd.readouterr()499 assert out == "x"500 assert err == "Prompt to stderr with no suffi"501502 emulate_input("y\n")503 click.confirm("Prompt to stdin")504 out, err = capfd.readouterr()505 assert out == "Prompt to stdin [y/N]: "506 assert err == ""507508 emulate_input("y\n")509 click.confirm("Prompt to stdin with no suffix", prompt_suffix="")510 out, err = capfd.readouterr()511 assert out == "Prompt to stdin with no suffix [y/N]"512 assert err == ""513514 emulate_input("y\n")515 click.confirm("Prompt to stderr", err=True)516 out, err = capfd.readouterr()517 assert out == " "518 assert err == "Prompt to stderr [y/N]:"519520 emulate_input("y\n")521 click.confirm("Prompt to stderr with no suffix", prompt_suffix="", err=True)522 out, err = capfd.readouterr()523 assert out == "]"524 assert err == "Prompt to stderr with no suffix [y/N"525526 monkeypatch.setattr(click.termui, "isatty", lambda x: True)527 monkeypatch.setattr(click.termui, "getchar", lambda: " ")528529 click.pause("Pause to stdout")
217 unmodified lines
modified:CHANGES.rst+11 added-4 removed
3 unmodified lines
4--------------56Unreleased78- Don't discard pager arguments by correctly using subprocess.Popen. :issue:`3039` :pr:`3055`8- Don't discard pager arguments by correctly using ``subprocess.Popen``. :issue:`3039`9 :pr:`3055`10- Replace ``Sentinel.UNSET`` default values by ``None`` as they're passed through11 the ``Context.invoke()`` method. :issue:`3066` :issue:`3065` :pr:`3068`12- Fix conversion of ``Sentinel.UNSET`` happening too early, which caused incorrect13 behavior for multiple parameters using the same name. :issue:`3071` :pr:`3079`14- Fix rendering when ``prompt`` and ``confirm`` parameter ``prompt_suffix`` is15 empty. :issue:`3019` :pr:`3021`16- When ``Sentinel.UNSET`` is found during parsing, it will skip calls to17 ``type_cast_value``. :issue:`3069` :pr:`3090`18101119Version 8.3.020--------------2122Released 2025-09-17
15 unmodified lines
38- Fix handling of quoted and escaped parameters in Fish autocompletion. :issue:`2995` :pr:`3013`39- Lazily import ``shutil``. :pr:`3023`40- Properly forward exception information to resources registered with41 ``click.core.Context.with_resource()``. :issue:`2447` :pr:`3058`35- Fix regression related to EOF handling in CliRunner. :issue:`2939` :pr:`2940`42- Fix regression related to EOF handling in ``CliRunner``. :issue:`2939` :pr:`2940`4344Version 8.2.245-------------46
1262 unmodified lines