Skip to content
Myr

Merge branch 'stable' into fix-type-cast-sees-unset

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

authored by Kevin Deldycke · committed by GitHub · parents 18d2919, 06f52a4 · Browse files · 11 files+517 added−325 removed
This commit

State

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

Diff stats

11 files+517 added−325 removed

  • tests:+24 added−0 removed
  • other:+493 added−325 removed

11 files+517 added−325 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/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.
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+7 added-2 removed
255 unmodified lines
256 invoke(info, args=['--shout'])257258```259260To implement this more explicitly, pass in on-option `/` off-option. Click will automatically set `is_flag=True`. Click always wants you to provide an enable261and 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/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_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+3 added-1 removed
9 unmodified lines
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 to15 ``type_cast_value``. :issue:`3069`17 ``type_cast_value``. :issue:`3069` :pr:`3090`1819Version 8.3.020--------------21
1287 unmodified lines