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
Provenance
- Commit
bfea3cd- Tree
9ccbd8e- Author
Rowlando13 <67291205+Rowlando13@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent 1
309ce91- Parent 2
868b611
18 files changed+768 added−355 removed
added:docs/api.md+353 added
1+# API2+3+```{currentmodule} click4+```5+6+This part of the documentation lists the full API reference of all public7+classes and functions.8+9+```{contents}10+:depth: 111+:local: true12+```13+14+## Decorators15+16+```{eval-rst}17+.. autofunction:: command18+```19+20+```{eval-rst}21+.. autofunction:: group22+```23+24+```{eval-rst}25+.. autofunction:: argument26+```27+28+```{eval-rst}29+.. autofunction:: option30+```31+32+```{eval-rst}33+.. autofunction:: password_option34+```35+36+```{eval-rst}37+.. autofunction:: confirmation_option38+```39+40+```{eval-rst}41+.. autofunction:: version_option42+```43+44+```{eval-rst}45+.. autofunction:: help_option46+```47+48+```{eval-rst}49+.. autofunction:: pass_context50+```51+52+```{eval-rst}53+.. autofunction:: pass_obj54+```55+56+```{eval-rst}57+.. autofunction:: make_pass_decorator58+```59+60+```{eval-rst}61+.. autofunction:: click.decorators.pass_meta_key62+63+```64+65+## Utilities66+67+```{eval-rst}68+.. autofunction:: echo69+```70+71+```{eval-rst}72+.. autofunction:: echo_via_pager73+```74+75+```{eval-rst}76+.. autofunction:: prompt77+```78+79+```{eval-rst}80+.. autofunction:: confirm81+```82+83+```{eval-rst}84+.. autofunction:: progressbar85+```86+87+```{eval-rst}88+.. autofunction:: clear89+```90+91+```{eval-rst}92+.. autofunction:: style93+```94+95+```{eval-rst}96+.. autofunction:: unstyle97+```98+99+```{eval-rst}100+.. autofunction:: secho101+```102+103+```{eval-rst}104+.. autofunction:: edit105+```106+107+```{eval-rst}108+.. autofunction:: launch109+```110+111+```{eval-rst}112+.. autofunction:: getchar113+```114+115+```{eval-rst}116+.. autofunction:: pause117+```118+119+```{eval-rst}120+.. autofunction:: get_binary_stream121+```122+123+```{eval-rst}124+.. autofunction:: get_text_stream125+```126+127+```{eval-rst}128+.. autofunction:: open_file129+```130+131+```{eval-rst}132+.. autofunction:: get_app_dir133+```134+135+```{eval-rst}136+.. autofunction:: format_filename137+```138+139+## Commands140+141+```{eval-rst}142+.. autoclass:: BaseCommand143+ :members:144+```145+146+```{eval-rst}147+.. autoclass:: Command148+ :members:149+```150+151+```{eval-rst}152+.. autoclass:: MultiCommand153+ :members:154+```155+156+```{eval-rst}157+.. autoclass:: Group158+ :members:159+```160+161+```{eval-rst}162+.. autoclass:: CommandCollection163+ :members:164+```165+166+## Parameters167+168+```{eval-rst}169+.. autoclass:: Parameter170+ :members:171+```172+173+```{eval-rst}174+.. autoclass:: Option175+```176+177+```{eval-rst}178+.. autoclass:: Argument179+```180+181+## Context182+183+```{eval-rst}184+.. autoclass:: Context185+ :members:186+```187+188+```{eval-rst}189+.. autofunction:: get_current_context190+```191+192+```{eval-rst}193+.. autoclass:: click.core.ParameterSource194+ :members:195+ :member-order: bysource196+```197+198+(click-api-types)=199+200+## Types201+202+```{eval-rst}203+.. autodata:: STRING204+```205+206+```{eval-rst}207+.. autodata:: INT208+```209+210+```{eval-rst}211+.. autodata:: FLOAT212+```213+214+```{eval-rst}215+.. autodata:: BOOL216+```217+218+```{eval-rst}219+.. autodata:: UUID220+```221+222+```{eval-rst}223+.. autodata:: UNPROCESSED224+```225+226+```{eval-rst}227+.. autoclass:: File228+```229+230+```{eval-rst}231+.. autoclass:: Path232+```233+234+```{eval-rst}235+.. autoclass:: Choice236+ :members:237+```238+239+```{eval-rst}240+.. autoclass:: IntRange241+```242+243+```{eval-rst}244+.. autoclass:: FloatRange245+```246+247+```{eval-rst}248+.. autoclass:: DateTime249+```250+251+```{eval-rst}252+.. autoclass:: Tuple253+```254+255+```{eval-rst}256+.. autoclass:: ParamType257+ :members:258+```259+260+## Exceptions261+262+```{eval-rst}263+.. autoexception:: ClickException264+```265+266+```{eval-rst}267+.. autoexception:: Abort268+```269+270+```{eval-rst}271+.. autoexception:: UsageError272+```273+274+```{eval-rst}275+.. autoexception:: BadParameter276+```277+278+```{eval-rst}279+.. autoexception:: FileError280+```281+282+```{eval-rst}283+.. autoexception:: NoSuchOption284+```285+286+```{eval-rst}287+.. autoexception:: BadOptionUsage288+```289+290+```{eval-rst}291+.. autoexception:: BadArgumentUsage292+```293+294+## Formatting295+296+```{eval-rst}297+.. autoclass:: HelpFormatter298+ :members:299+```300+301+```{eval-rst}302+.. autofunction:: wrap_text303+```304+305+## Parsing306+307+```{eval-rst}308+.. autoclass:: OptionParser309+ :members:310+311+```312+313+## Shell Completion314+315+See {doc}`/shell-completion` for information about enabling and316+customizing Click's shell completion system.317+318+```{eval-rst}319+.. currentmodule:: click.shell_completion320+```321+322+```{eval-rst}323+.. autoclass:: CompletionItem324+```325+326+```{eval-rst}327+.. autoclass:: ShellComplete328+ :members:329+ :member-order: bysource330+```331+332+```{eval-rst}333+.. autofunction:: add_completion_class334+335+```336+337+(testing)=338+339+## Testing340+341+```{eval-rst}342+.. currentmodule:: click.testing343+```344+345+```{eval-rst}346+.. autoclass:: CliRunner347+ :members:348+```349+350+```{eval-rst}351+.. autoclass:: Result352+ :members:353+```deleted:docs/api.rst-217 removed
1-API2-===3-4-.. module:: click5-6-This part of the documentation lists the full API reference of all public7-classes and functions.8-9-.. contents::10- :depth: 111- :local:12-13-Decorators14-----------15-16-.. autofunction:: command17-18-.. autofunction:: group19-20-.. autofunction:: argument21-22-.. autofunction:: option23-24-.. autofunction:: password_option25-26-.. autofunction:: confirmation_option27-28-.. autofunction:: version_option29-30-.. autofunction:: help_option31-32-.. autofunction:: pass_context33-34-.. autofunction:: pass_obj35-36-.. autofunction:: make_pass_decorator37-38-.. autofunction:: click.decorators.pass_meta_key39-40-41-Utilities42----------43-44-.. autofunction:: echo45-46-.. autofunction:: echo_via_pager47-48-.. autofunction:: prompt49-50-.. autofunction:: confirm51-52-.. autofunction:: progressbar53-54-.. autofunction:: clear55-56-.. autofunction:: style57-58-.. autofunction:: unstyle59-60-.. autofunction:: secho61-62-.. autofunction:: edit63-64-.. autofunction:: launch65-66-.. autofunction:: getchar67-68-.. autofunction:: pause69-70-.. autofunction:: get_binary_stream71-72-.. autofunction:: get_text_stream73-74-.. autofunction:: open_file75-76-.. autofunction:: get_app_dir77-78-.. autofunction:: format_filename79-80-Commands81---------82-83-.. autoclass:: BaseCommand84- :members:85-86-.. autoclass:: Command87- :members:88-89-.. autoclass:: MultiCommand90- :members:91-92-.. autoclass:: Group93- :members:94-95-.. autoclass:: CommandCollection96- :members:97-98-Parameters99-----------100-101-.. autoclass:: Parameter102- :members:103-104-.. autoclass:: Option105-106-.. autoclass:: Argument107-108-Context109--------110-111-.. autoclass:: Context112- :members:113-114-.. autofunction:: get_current_context115-116-.. autoclass:: click.core.ParameterSource117- :members:118- :member-order: bysource119-120-.. _click-api-types:121-122-Types123------124-125-.. autodata:: STRING126-127-.. autodata:: INT128-129-.. autodata:: FLOAT130-131-.. autodata:: BOOL132-133-.. autodata:: UUID134-135-.. autodata:: UNPROCESSED136-137-.. autoclass:: File138-139-.. autoclass:: Path140-141-.. autoclass:: Choice142- :members:143-144-.. autoclass:: IntRange145-146-.. autoclass:: FloatRange147-148-.. autoclass:: DateTime149-150-.. autoclass:: Tuple151-152-.. autoclass:: ParamType153- :members:154-155-Exceptions156-----------157-158-.. autoexception:: ClickException159-160-.. autoexception:: Abort161-162-.. autoexception:: UsageError163-164-.. autoexception:: BadParameter165-166-.. autoexception:: FileError167-168-.. autoexception:: NoSuchOption169-170-.. autoexception:: BadOptionUsage171-172-.. autoexception:: BadArgumentUsage173-174-Formatting175-----------176-177-.. autoclass:: HelpFormatter178- :members:179-180-.. autofunction:: wrap_text181-182-Parsing183--------184-185-.. autoclass:: OptionParser186- :members:187-188-189-Shell Completion190-----------------191-192-See :doc:`/shell-completion` for information about enabling and193-customizing Click's shell completion system.194-195-.. currentmodule:: click.shell_completion196-197-.. autoclass:: CompletionItem198-199-.. autoclass:: ShellComplete200- :members:201- :member-order: bysource202-203-.. autofunction:: add_completion_class204-205-206-.. _testing:207-208-Testing209--------210-211-.. currentmodule:: click.testing212-213-.. autoclass:: CliRunner214- :members:215-216-.. autoclass:: Result217- :members:added:docs/command-line-reference.md+48 added
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748# General Command Line Topics
```{currentmodule} click```
```{contents}---depth: 1local: true---```
## Exit Codes
When a command is executed from the command line, then an exit code is return. The exit code, also called exit status or exit status code, is a positive integer that tells you whether the command executed with or without errors.
| Exit Code | Meaning ||-----------|-------------------------------------------------|| 0 | Success — the command completed without errors. || > 0 | Executed with errors |
Exit codes greater than zero mean are specific to the Operating System, Shell, and/or command.
To access the exit code, execute the command, then do the following depending:
```{eval-rst}.. tabs::
.. group-tab:: Powershell
.. code-block:: powershell
> echo $LASTEXITCODE
.. group-tab:: Bash
.. code-block:: bash
$ echo $?
.. group-tab:: Command Prompt
.. code-block:: text
> echo %ERRORLEVEL%
```added:docs/handling-files.md+102 added
1+(handling-files)=2+3+# Handling Files4+5+```{currentmodule} click6+```7+8+Click has built in features to support file and file path handling. The examples use arguments but the same principle9+applies to options as well.10+11+(file-args)=12+13+## File Arguments14+15+Click supports working with files with the {class}`File` type. Some notable features are:16+17+- 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.20+21+Example:22+23+```{eval-rst}24+.. click:example::25+26+ @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)36+37+And from the command line:38+39+.. click:run::40+41+ with isolated_filesystem():42+ invoke(inout, args=['-', 'hello.txt'], input=['hello'],43+ terminate_input=True)44+ invoke(inout, args=['hello.txt', '-'])45+```46+47+## File Path Arguments48+49+For handling paths, the {class}`Path` type is better than a `str`. Some notable features are:50+51+- 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.55+56+See {class}`Path` for all features.57+58+Example:59+60+```{eval-rst}61+.. click:example::62+63+ @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))68+69+And from the command line:70+71+.. click:run::72+73+ 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+```80+81+## File Opening Behaviors82+83+The {class}`File` type attempts to be "intelligent" about when to open a file. Stdin/stdout and files opened for reading84+will be opened immediately. This will give the user direct feedback when a file cannot be opened. Files opened for85+writing will only be open on the first IO operation. This is done by automatically wrapping the file in a special86+wrapper.87+88+File open behavior can be controlled by the boolean kwarg `lazy`. If a file is opened lazily:89+90+- 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).96+97+Since files opened for writing will typically empty the file, the lazy mode should only be disabled if the developer is98+absolutely sure that this is intended behavior.99+100+It is also possible to open files in atomic mode by passing `atomic=True`. In atomic mode, all writes go into a separate101+file in the same folder, and upon completion, the file will be moved over to the original location. This is useful if a102+file regularly read by other users is modified.deleted:docs/handling-files.rst-90 removed
1-.. _handling-files:2-3-Handling Files4-================5-6-.. currentmodule:: click7-8-Click has built in features to support file and file path handling. The examples use arguments but the same principle applies to options as well.9-10-.. _file-args:11-12-File Arguments13------------------14-15-Click supports working with files with the :class:`File` type. Some notable features are:16-17-* 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.19-20-Example:21-22-.. click:example::23-24- @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)34-35-And from the command line:36-37-.. click:run::38-39- with isolated_filesystem():40- invoke(inout, args=['-', 'hello.txt'], input=['hello'],41- terminate_input=True)42- invoke(inout, args=['hello.txt', '-'])43-44-File Path Arguments45-----------------------46-47-For handling paths, the :class:`Path` type is better than a ``str``. Some notable features are:48-49-* 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.53-54-See :class:`Path` for all features.55-56-Example:57-58-.. click:example::59-60- @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))65-66-And from the command line:67-68-.. click:run::69-70- 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'])76-77-78-File Opening Behaviors79------------------------------80-81-The :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.82-83-File open behavior can be controlled by the boolean kwarg ``lazy``. If a file is opened lazily:84-85-* 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).87-88-Since 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.89-90-It 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 lines111 testing112 utils113 shell-completion114 exceptions115+ command-line-reference116 unicode-support117 wincmd118 119 API Reference24 unmodified linesadded:docs/license.md+7 added
1234567# BSD-3-Clause License
```{literalinclude} ../LICENSE.txt---language: text---```deleted:docs/license.rst-5 removed
1-BSD-3-Clause License2-====================3-4-.. literalinclude:: ../LICENSE.txt5- :language: textmodified:docs/options.md+12 added-5 removed
129 unmodified lines130 ```131 132 ## Multi Value Options133 134-To 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.134+To 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.135 136 ```{eval-rst}137 .. click:example::138 55 unmodified lines194 (multiple-options)=195 196 ## Multiple Options197 198-The 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.198+The 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.199 200 ```{eval-rst}201 .. click:example::202 203 @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)209 210 .. click:run::211 212 invoke(commit, args=['-m', 'foo', '-m', 'bar', '-m', 'here'])43 unmodified lines256 invoke(info, args=['--shout'])257 258 ```259 258-To implement this more explicitly, pass in on-option `/` off-option. Click will automatically set `is_flag=True`. Click always wants you to provide an enable259-and disable flag so that you can change the default later.260+To implement this more explicitly, pass in on-option `/` off-option. Click will automatically set `is_flag=True`.261 262 ```{eval-rst}263 .. click:example::264 13 unmodified lines278 invoke(info, args=['--shout'])279 invoke(info, args=['--no-shout'])280 ```281 282+Use cases for this more explicit pattern include:283+284+* 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 flag287+288 If 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.289 290 ```{eval-rst}291 .. click:example::213 unmodified linesmodified:src/click/_termui_impl.py+9 added-4 removed
427 unmodified lines428 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()432+433+ # 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.name438 439 import subprocess440 81 unmodified lines522 523 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()530 531 import subprocess532 import tempfile533 319 unmodified linesmodified:src/click/core.py+53 added-15 removed
797 unmodified lines798 ctx = self._make_sub_context(other_cmd)799 800 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 )815 816 # Track all kwargs as params, so that forward() will pass817 # them on in subsequent calls.407 unmodified lines1225 1226 for param in iter_params_for_processing(param_order, self.get_params(ctx)):1227 _, args = param.handle_parse_result(ctx, opts, args)1228 1229+ # 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] = None1241+1242 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 lines2337 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 value74 unmodified lines2420 the :attr:`UNSET` sentinel.2421 2422 :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)2434 2435 if self.required and self.value_is_missing(value):2436 raise MissingParameter(ctx=ctx, param=self)2437 121 unmodified lines2559 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] = value2571 2572 return value, args2573 2574 def get_help_record(self, ctx: Context) -> tuple[str, str] | None:689 unmodified lines3264 source = ParameterSource.PROMPT3265 3266 return value, source3267 3239- 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 = False3276 3277+ if self.callback is not None:3278+ value = self.callback(ctx, self, value)3279 3280+ return value3281+3282+ # in the normal case, rely on Parameter.process_value3283+ return super().process_value(ctx, value)3284+3285+3286 class 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 linesmodified:src/click/termui.py+12 added-6 removed
117 unmodified lines118 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): ".121 122+ .. versionchanged:: 8.3.1123+ A space is no longer appended to the prompt.124+125 .. versionadded:: 8.0126 ``confirmation_prompt`` can be a custom string.127 128 .. versionadded:: 7.011 unmodified lines140 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/issue2471164 unmodified lines216 :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.219 220+ .. versionchanged:: 8.3.1221+ A space is no longer appended to the prompt.222+223 .. versionchanged:: 8.0224 Repeat until input is given if ``default`` is ``None``.225 226 .. versionadded:: 4.09 unmodified lines236 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 = True636 unmodified linesmodified:tests/test_arguments.py+37 added
577 unmodified lines578 pass579 580 with pytest.warns(UserWarning):581 runner.invoke(cli, [])582+583+584+@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+)597+def 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 supported602+603+ In particular, the argument is never passed an UNSET sentinel value.604+ """605+606+ class CustomArgument(click.Argument):607+ def type_cast_value(self, ctx, value):608+ assert value is not UNSET609+ return value610+611+ @click.command()612+ @click.argument("myarg", **argument_kwargs, cls=CustomArgument)613+ def cmd(myarg):614+ click.echo("ok")615+616+ result = runner.invoke(cmd, pass_argv)617+ assert not result.exception618+ assert result.exit_code == 0modified:tests/test_commands.py+37 added-9 removed
226 unmodified lines227 assert result.exception is None228 assert result.output == "Debug is off\n"229 230 231+@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+)231-def test_other_command_invoke_with_defaults(runner):262+def 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)267 268 @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, a273 274 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, ())275 276+ assert result.return_value == ("other", expected)277 278+279 def test_invoked_subcommand(runner):280 @click.group(invoke_without_command=True)281 @click.pass_context282 def cli(ctx):293 unmodified linesmodified:tests/test_defaults.py+26 added
82 unmodified lines83 assert "True" in result.output84 85 result = runner.invoke(cli, ["foo", "--help"], default_map={"foo": {"name": True}})86 assert "default: name" in result.output87+88+89+def test_shared_param_prefers_first_default(runner):90+ """test that the first default is chosen when multiple flags share a param name"""91+92+ @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)97+98+ @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)103+104+ result = runner.invoke(prefers_green, [])105+ assert "green" in result.output106+ result = runner.invoke(prefers_green, ["--red"])107+ assert "red" in result.output108+109+ result = runner.invoke(prefers_red, [])110+ assert "red" in result.output111+ result = runner.invoke(prefers_red, ["--green"])112+ assert "green" in result.outputmodified:tests/test_options.py+36 added
1010 unmodified lines1011 assert "I am a help text" in result.output1012 assert "you wont see me" not in result.output1013 1014 1015+@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+)1027+def 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 supported1032+1033+ In particular, the option is never passed an UNSET sentinel value.1034+ """1035+1036+ class CustomOption(click.Option):1037+ def type_cast_value(self, ctx, value):1038+ assert value is not UNSET1039+ return value1040+1041+ @click.command()1042+ @click.option("myparam", param_decl, **option_kwargs, cls=CustomOption)1043+ def cmd(myparam):1044+ click.echo("ok")1045+1046+ result = runner.invoke(cmd, pass_argv)1047+ assert not result.exception1048+ assert result.exit_code == 01049+1050+1051 def test_option_custom_class_reusable(runner):1052 """Ensure we can reuse a custom class option. See Issue #926"""1053 1054 class CustomOption(click.Option):1223 unmodified linesmodified:tests/test_utils.py+24 added
480 unmodified lines481 assert out == "Prompt to stdin: "482 assert err == ""483 484 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 == ""489+490+ 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:"495 496+ 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"501+502 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 == ""507 508 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 == ""513+514+ 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]:"519 520+ 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"525+526 monkeypatch.setattr(click.termui, "isatty", lambda x: True)527 monkeypatch.setattr(click.termui, "getchar", lambda: " ")528 529 click.pause("Pause to stdout")217 unmodified linesmodified:CHANGES.rst+11 added-4 removed
3 unmodified lines4 --------------5 6 Unreleased7 8-- 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`18 10-11-19 Version 8.3.020 --------------21 22 Released 2025-09-1715 unmodified lines38 - 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`43 44 Version 8.2.245 -------------46 1262 unmodified lines