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
Provenance
- Commit
6b1278f- Tree
7863a78- Author
Kevin Deldycke <kdeldycke@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent 1
18d2919- Parent 2
06f52a4
11 files changed+517 added−325 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/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.added: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+7 added-2 removed
255 unmodified lines256 invoke(info, args=['--shout'])257 258 ```259 260-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 enable261-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/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_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+3 added-1 removed
9 unmodified lines10 - 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`18 19 Version 8.3.020 --------------21 1287 unmodified lines