Skip to content
Myr

Stable (#3851)

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

authored by Rowlando13 · committed by GitHub · parents 36baa15, 7944461 · Browse files · 30 files+1201 added−392 removed
This commit

State

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

Diff stats

30 files+1201 added−392 removed

  • tests:+826 added−339 removed
  • other:+375 added−53 removed

30 files+1201 added−392 removed

modified:docs/arguments.md+4 added-2 removed
modified:docs/complex.md+3 added-3 removed
348 unmodified lines
349 and then resolve `baz`. Each subcommand resolution step does a lazy load.3502. Helptext rendering. In order to get the short help description of subcommands,351 `cli --help` will load `foo` and `bar`. Note that it will still not load352 `baz`.3533. Shell completion. In order to get the subcommands of a lazy command, `cli <TAB>`354 will need to resolve the subcommands of `cli`. This process will trigger the lazy355 loads.3533. Shell completion. In order to get the subcommands of a lazy command, completing354 `cli` with {kbd}`Tab` will need to resolve the subcommands of `cli`. This process355 will trigger the lazy loads.356357### Further Deferring Imports358359It is possible to make the process even lazier, but it is generally more difficult the
27 unmodified lines
modified:docs/contrib.md+11 added-1 removed
25 unmodified lines
26| Project | Description | Popularity | Activity |27|---------------------------------------------------------|--------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------|28| [Typer](https://github.com/fastapi/typer) | Use Python type hints to create CLI apps. | ![GitHub stars](https://img.shields.io/github/stars/fastapi/typer?label=%20&style=flat-square) | ![Last commit](https://img.shields.io/github/last-commit/fastapi/typer?label=%20&style=flat-square) |29| [rich-click](https://github.com/ewels/rich-click) | Format help output with Rich. | ![GitHub stars](https://img.shields.io/github/stars/ewels/rich-click?label=%20&style=flat-square) | ![Last commit](https://img.shields.io/github/last-commit/ewels/rich-click?label=%20&style=flat-square) |30| [shtab](https://github.com/tqdm/shtab) | Speed up tab completion scripts and support more shells. | ![GitHub stars](https://img.shields.io/github/stars/tqdm/shtab?label=%20&style=flat-square) | ![Last commit](https://img.shields.io/github/last-commit/tqdm/shtab?label=%20&style=flat-square) |31| [click-app](https://github.com/simonw/click-app) | Cookiecutter template for creating new CLIs. | ![GitHub stars](https://img.shields.io/github/stars/simonw/click-app?label=%20&style=flat-square) | ![Last commit](https://img.shields.io/github/last-commit/simonw/click-app?label=%20&style=flat-square) |32| [Cloup](https://github.com/janluke/cloup) | Adds option groups, constraints, command aliases, help themes, suggestions and more. | ![GitHub stars](https://img.shields.io/github/stars/janluke/cloup?label=%20&style=flat-square) | ![Last commit](https://img.shields.io/github/last-commit/janluke/cloup?label=%20&style=flat-square) |33| [Click Extra](https://github.com/kdeldycke/click-extra) | Cloup + colorful `--help`, `--config`, `--show-params`, `--verbosity` options, etc. | ![GitHub stars](https://img.shields.io/github/stars/kdeldycke/click-extra?label=%20&style=flat-square) | ![Last commit](https://img.shields.io/github/last-commit/kdeldycke/click-extra?label=%20&style=flat-square) |3435## Interactive input libraries3637Click reads a prompt with the built-in {func}`input` and embeds no line editor of its own. If you need fancy features like completion of arbitrary values, selection menus or fuzzy search you need to replace {func}`click.prompt` with a third-party library. The projects below are popular and actively maintained:3839| Project | Description | Popularity | Activity |40|---------------------------------------------------------------------------|----------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------|41| [Textual](https://github.com/Textualize/textual) | Build terminal and web user interfaces with a Python API. | ![GitHub stars](https://img.shields.io/github/stars/Textualize/textual?label=%20&style=flat-square) | ![Last commit](https://img.shields.io/github/last-commit/Textualize/textual?label=%20&style=flat-square) |42| [prompt-toolkit](https://github.com/prompt-toolkit/python-prompt-toolkit) | Build interactive command lines with completion, history and key bindings. | ![GitHub stars](https://img.shields.io/github/stars/prompt-toolkit/python-prompt-toolkit?label=%20&style=flat-square) | ![Last commit](https://img.shields.io/github/last-commit/prompt-toolkit/python-prompt-toolkit?label=%20&style=flat-square) |4344```{note}35To make it into the list above, a project:45To make it into any of the lists above, a project:4647- must be actively maintained (at least one commit in the last year)48- must have a reasonable number of stars (at least 20)49
6 unmodified lines
modified:docs/exceptions.md+37 added-11 removed
17 unmodified lines
18## Where are Errors Handled?1920Click's main error handling is happening in {meth}`Command.main`. In21there it handles all subclasses of {exc}`ClickException` as well as the22standard {exc}`EOFError` and {exc}`KeyboardInterrupt` exceptions. The23latter are internally translated into an {exc}`Abort`.22standard {exc}`EOFError` and {exc}`KeyboardInterrupt` exceptions.2325The logic applied is the following:24The table below lists every way a command can end, and what Click does25for each. The middle column is the default. The last column applies when26{meth}`Command.main` runs with ``standalone_mode=False``, which the next27section describes.28271. If an {exc}`EOFError` or {exc}`KeyboardInterrupt` happens, reraise it28 as {exc}`Abort`.292. If a {exc}`ClickException` is raised, invoke the30 {meth}`ClickException.show` method on it to display it and then exit31 the program with {attr}`ClickException.exit_code`.323. If an {exc}`Abort` exception is raised print the string ``Aborted!``33 to standard error and exit the program with exit code ``1``.344. If it goes through well, exit the program with exit code ``0``.29| How the command ends | Standalone mode | ``standalone_mode=False`` |30| --- | --- | --- |31| It returns | Exit with code ``0`` | Return the value of {meth}`Command.invoke` |32| It called {meth}`Context.exit` | Exit with the given code | Return the given code |33| It raised a {exc}`ClickException` | Call {meth}`ClickException.show`, then exit with {attr}`ClickException.exit_code` | Propagate it |34| The user pressed {kbd}`Ctrl+C`, which raises a {exc}`KeyboardInterrupt` | Print a blank line, then ``Aborted!`` to standard error, and exit with code ``1`` | Print a blank line, then raise {exc}`Abort` with the original exception as its ``__cause__`` |35| The user pressed {kbd}`Ctrl+D`, or {kbd}`Ctrl+Z` on Windows, which raises an {exc}`EOFError` | The same as {kbd}`Ctrl+C` | The same as {kbd}`Ctrl+C` |36| It raised an {exc}`Abort` | Print ``Aborted!`` to standard error, and exit with code ``1`` | Propagate it |37| The output pipe closed early, which raises an {exc}`OSError` with ``EPIPE`` | Silence the flush errors, and exit with code ``1`` | The same |38| It raised any other exception | Propagate it | Propagate it |3940Click writes the message and exits once that handling is done. An41interrupt arriving during this last step cannot change the exit code the42table gave. It can only cost the message.4344## What if I Don't Want That?4546Generally you always have the option to invoke the {meth}`Command.invoke`47method yourself. For instance if you have a {class}`Command` you can
20 unmodified lines
68 standalone_mode=False,69)70```7172This is also how you replace the ``Aborted!`` message. Standalone mode73turns off every row of the table above, so catch the cases you want to74keep and write your own message for the rest:7576```python77try:78 command.main(79 ["command-name", "args", "go", "here"],80 standalone_mode=False,81 )82except click.Abort:83 click.echo("Bye!", err=True)84 raise SystemExit(1)85except click.ClickException as e:86 e.show()87 raise SystemExit(e.exit_code)88```8990## Which Exceptions Exist?9192Click has two exception bases: {exc}`ClickException` which is raised for93all exceptions that Click wants to signal to the user and {exc}`Abort`
69 unmodified lines
modified:docs/faqs.md+167 added
5 unmodified lines
6```78## General910### Calling a command as a regular function1112I decorated a function with `@click.command()` to make it a CLI. When I import that name and call it from Python, it does not run my function. It parses arguments, prints a usage error and exits the process:1314```pytb15>>> nasa_date_to_iso("2017-090")16Usage: cli [OPTIONS] DATESTR17Try 'cli --help' for help.1819Error: Got unexpected extra arguments (0 1 7 - 0 9 0)20SystemExit: 221```2223#### Answer2425This is not a bug in Click. The decorator replaced the function with a {class}`Command` object. Calling that object runs the Click pipeline, and its argument is the list of command line arguments to parse, not the function's parameters.2627The recommended pattern is to keep a plain function and wrap it with a thin command:2829```python30def nasa_date_to_iso(datestr): ...313233@click.command("nasa_date_to_iso")34@click.argument("datestr")35def nasa_date_to_iso_command(datestr):36 click.echo(nasa_date_to_iso(datestr))37```3839The function stays available as a Python API, and the command adds the CLI on top. Extracting behavior into a shared function used by several entry points is a common refactor.4041If you still want to run the command itself from Python, call it with a list of arguments and `standalone_mode=False` so it returns the result instead of exiting. This runs the Click pipeline, including parsing, validation and callbacks:4243```python44nasa_date_to_iso_command(["2017-090"], standalone_mode=False)45```4647An alternative form is:4849```python50nasa_date_to_iso_command.main(["2017-090"], standalone_mode=False)51```5253### Shell Variable Expansion On Windows5455I have a simple Click app :56
67 unmodified lines
124| `python -X utf8` | `1` | `utf-8` |125| `sys.stdout.reconfigure(encoding=…)` | `0` | `utf-8` |126127Do not rely on `sys.getfilesystemencoding()` on Windows either: [PEP 529](https://peps.python.org/pep-0529/) makes it `utf-8` regardless of the actual stream encoding.128129(edit-wait)=130### The `edit` utility fails to open Visual Studio Code131132Let's say our default editor is Visual Studio Code. A Click CLI calling `edit()` is supposed to open a new VSCode window on a temporary file then wait for us to edit that file before returning back the CLI execution.133134But VSCode (and some other editors) returns immediately: the file is deleted before you had a chance to edit it. With `require_save=True` (the default), the function also returns `None` instead of the edited content.135136This is not a bug in Click. In that particular case, the `code` command (VSCode's executable) is a launcher: it starts the real editor in the background, then exits. Click waits on that process and reads its exit as the end of the editing session. The same happens on any platform with any editor whose command returns before its window closes.137138#### Answer139140Setup your editor to make its launcher block until the window is closed, so Click keeps waiting on it.141142You can set the `EDITOR` in your environment with its appropriate flags:143144| Editor | Flags |145|---|---|146| Visual Studio Code | `EDITOR="code --wait"` |147| Sublime Text | `EDITOR="subl -w"` |148149For an editor with no such flag, a workaround is to point `EDITOR` at a small wrapper script that opens the editor and blocks until it exits.150151### Tab completion during interactive prompts152153A command asks for a file path while it runs:154155```python156import click157158159@click.command()160def convert():161 source = click.prompt("File to convert", type=click.Path(exists=True))162 click.echo(f"Converting {source}")163```164165Pressing {kbd}`Tab` while typing the answer inserts a tab character instead of completing the path:166167```console168$ convert169File to convert: Doc<TAB>170Error: Path 'Doc\t' does not exist.171```172173This is not a bug in Click. Tab completion of the command line belongs to the shell: the shell asks the program for candidates through Click's completion mode, before any command code runs. A prompt works the other way around. The program already runs and reads the line itself, so Click never sees the {kbd}`Tab` key.174175{func}`~click.prompt` reads that line with the built-in {func}`input`, and Click passes the whole prompt text to it as-is. This is where Python's {mod}`readline` module takes over, but nothing binds {kbd}`Tab` to completion by default.176177#### Answer178179Bind {kbd}`Tab` in `readline` and the prompt completes paths with no other change:180181```python182import readline183184if "libedit" in (readline.__doc__ or ""):185 readline.parse_and_bind("bind ^I rl_complete")186else:187 readline.parse_and_bind("tab: complete")188```189190See the {mod}`readline` documentation for the binding syntax, for the two libraries it can be built on, and for writing a completer of your own. The module is Unix-only, so the import fails on Windows.191192Readline completes file names. It knows nothing about the parameter, so it cannot complete other values, such as the choices of a {class}`~click.Choice` parameter. Click embeds no line editor of its own: for completion of such values at a prompt, use one of the [interactive input libraries](contrib.md#interactive-input-libraries).193194When the value does not have to be asked while the command runs, another option is to take it out of the prompt and put it on the command line, as an argument or an option:195196```python197@click.command()198@click.argument("source", type=click.Path(exists=True))199def convert(source):200 click.echo(f"Converting {source}")201```202203The shell completes paths there natively and Click's completion mode takes part in it (as described in [Shell Completion](shell-completion.md)).204205(custom-completions-show-the-full-value)=206### Custom completions show the full value207208`Path` and `File` parameters complete differently from a parameter with a custom completer. Take a command with one of each:209210```python211def complete_dirs(ctx, param, incomplete):212 return [213 CompletionItem(incomplete + name)214 for name in ("Documents", "Downloads", "Pictures")215 ]216217218@click.command()219@click.option("--src", type=click.Path())220@click.option("--dest", shell_complete=complete_dirs)221def copy(src, dest):222 click.echo(f"Copy from {src} to {dest}")223```224225Completing `--src` shows only the last component of each candidate, and omits the leading path:226227```console228$ copy --src /home/user/<TAB><TAB>229Documents Downloads Pictures230```231232Completing `--dest` shows each value in full, exactly as the completer returned it:233234```console235$ copy --dest /home/user/<TAB><TAB>236/home/user/Documents /home/user/Downloads /home/user/Pictures237```238239This is not a bug in Click. The two parameters are completed by different sides.240241`Path.shell_complete` and `File.shell_complete` never enumerate the directory: each returns a single item that is the incomplete value itself, tagged `file` (or `dir` for a `Path` restricted to directories). Then the shell takes over to propose completions, and each shell does so in its own way.242243A custom completer sends no such marker. Its `CompletionItem` carries the value, a `type` marker, and an optional `help` string. The value a completer returns is both what the shell displays and what it inserts into the command line.244245#### Answer246247To change how suggestions are displayed, work on the shell side:248249- Check whether your shell's completion system has an option that changes how candidates are displayed.250- Write a `ShellComplete` subclass and register it with `add_completion_class`, as described in [Adding Support for a Shell](shell-completion.md#adding-support-for-a-shell).251- Or return the shortened form directly from your completer, but make the parameter accept and interpret that shortened form into the full value.
modified:docs/parameter-types.md+52 added
151 unmodified lines
152* .. autoclass:: Path153 :noindex:154```155156(type-inference)=157158## How Click Infers a Type159160When `type` is not given, Click infers it from `default`. Only the defaults listed below161are recognized. Every other default gives {data}`STRING`.162163| `default` | Inferred type |164| ------------------------------------------------ | ----------------------------------------------- |165| not given, or `None` | {data}`STRING` |166| `"git"` | {data}`STRING` |167| `5` | {data}`INT` |168| `1.5` | {data}`FLOAT` |169| `True` | {data}`BOOL` |170| `[]` or `()` | {data}`STRING` |171| `[1, 2]` or `(1, 2)` | {data}`INT` |172| `[1.5, 2.5]` | {data}`FLOAT` |173| `[1, "git"]` | {data}`INT` |174| `[(1, "git")]` | {class}`Tuple` of ({data}`INT`, {data}`STRING`) |175| `{1, 2}` or `frozenset({1, 2})` | {data}`STRING` |176| `{"a": 1}` | {data}`STRING` |177| {class}`uuid.UUID` or {class}`datetime.datetime` | {data}`STRING` |178| `b"git"`, or any other object | {data}`STRING` |179180A `list` or `tuple` gives the type of its **first item only**, so `[1, "git"]` gives181{data}`INT` and the second item is converted with it. A first item that is itself a182`list` or `tuple` gives a {class}`Tuple`, which also sets `nargs`.183184A `set`, a `frozenset`, a `dict`, and a type Click ships but does not guess, such as185{class}`uuid.UUID`, all land in the last group. Their default is converted with186{data}`STRING`, so the command receives the `str()` form of the value.187188```{eval-rst}189.. click:example::190191 @click.command()192 @click.option('--count', default=5)193 @click.option('--tag', default={'git'})194 def show(count, tag):195 click.echo(f"count is {type(count).__name__}, tag is {type(tag).__name__}")196197.. click:run::198199 invoke(show, args=[])200```201202When `type` is given a callable Click does not recognize, that callable is called on the203string coming from the command line, and a `ValueError` it raises is reported as a bad204parameter. A container is rarely useful there, because calling it on a string splits the205string: `set` turns `"git"` into `{"g", "i", "t"}`. Pass a {class}`ParamType` instead,206as described in [](#how-to-implement-custom-types).207208## How to Implement Custom Types209210To implement a custom type, you need to subclass the {class}`ParamType` class. For simple cases, passing a Python211function that fails with a `ValueError` is also supported, though discouraged. Override the {meth}`~ParamType.convert`
46 unmodified lines
modified:docs/shell-completion.md+2 added
159 unmodified lines
160def cli(ev):161 click.echo(os.environ[ev])162```163164See {ref}`custom-completions-show-the-full-value` in the FAQ for why these values are displayed in full, while `Path` completions show only the last component of the path.165166## Overriding Value Completion167168Value completions for a parameter can be customized without a custom type by providing a `shell_complete` function. The169function is used instead of any completion provided by the type. It is passed 3 positional arguments:
108 unmodified lines
modified:docs/utils.md+3 added-3 removed
176 unmodified lines
177 click.echo('Invalid input :(')178```179180Note that this reads raw input, which means that things like arrow keys will show up in the platform's native escape181format. The only characters translated are `^C` and `^D` which are converted into keyboard interrupts and end of file182exceptions respectively. This is done because otherwise, it's too easy to forget about that and to create scripts that183cannot be properly exited.181format. The only characters translated are the ones produced by {kbd}`Ctrl+C` and {kbd}`Ctrl+D`, or {kbd}`Ctrl+Z` on182Windows, which are converted into keyboard interrupts and end of file exceptions respectively. This is done because183otherwise, it's too easy to forget about that and to create scripts that cannot be properly exited.184185## Waiting for Key Press186187```{versionadded} 2.0
202 unmodified lines
modified:src/click/_utils.py+9 added
16 unmodified lines
1718 def __repr__(self) -> str:19 return f"{self.__class__.__name__}.{self.name}"2021 def __copy__(self) -> Sentinel:22 return self2324 def __deepcopy__(self, memo: dict[int, t.Any]) -> Sentinel:25 return self2627 def __reduce_ex__(self, protocol: object) -> tuple[t.Any, ...]:28 return getattr, (self.__class__, self.name)293031UNSET: t.Literal[Sentinel.UNSET] = Sentinel.UNSET32"""Sentinel used to indicate that a value is not set."""3334FLAG_NEEDS_VALUE: t.Literal[Sentinel.FLAG_NEEDS_VALUE] = Sentinel.FLAG_NEEDS_VALUE
11 unmodified lines
modified:src/click/_winconsole.py-5 removed
43 unmodified lines
44ReadConsoleW = kernel32.ReadConsoleW45WriteConsoleW = kernel32.WriteConsoleW46GetConsoleMode = kernel32.GetConsoleMode47GetLastError = kernel32.GetLastError48GetCommandLineW = WINFUNCTYPE(LPWSTR)(("GetCommandLineW", windll.kernel32))48CommandLineToArgvW = WINFUNCTYPE(POINTER(LPWSTR), LPCWSTR, POINTER(c_int))(49 ("CommandLineToArgvW", windll.shell32)50)51LocalFree = WINFUNCTYPE(c_void_p, c_void_p)(("LocalFree", windll.kernel32))
8 unmodified lines
60ERROR_SUCCESS = 061ERROR_NOT_ENOUGH_MEMORY = 862ERROR_OPERATION_ABORTED = 9956365STDIN_FILENO = 066STDOUT_FILENO = 167STDERR_FILENO = 26864EOF = b"\x1a"65MAX_BYTES_WRITTEN = 327676667if t.TYPE_CHECKING:
225 unmodified lines
modified:src/click/core.py+67 added-28 removed
97 unmodified lines
9899 raise RuntimeError(message)100101102def _echo_aborted() -> None:103 """Write the final abort message to standard error."""104 echo(_("Aborted!"), file=sys.stderr)105106107def _format_deprecated_label(deprecated: bool | str) -> str:108 """Return the parenthesized deprecation label shown in help text."""109 label = _("deprecated").upper()110 if isinstance(deprecated, str):
1439 unmodified lines
15501551 # Process shell completion requests and exit early.1552 self._main_shell_completion(extra, prog_name, complete_var)15531554 # Every handler below takes the same two steps: propagate when1555 # standalone mode is disabled, otherwise collect the message and the1556 # exit code, and leave both to the teardown after the ``try``. The1557 # teardown writes the message and exits, and the outermost handler1558 # holds one policy for every interrupt arriving that late: the1559 # message may be lost, the intended exit code still wins.1560 report: cabc.Callable[[], None] | None = None1561 exit_code = 115621563 try:1564 try:1565 with self.make_context(prog_name, args, **extra) as ctx:1566 rv = self.invoke(ctx)
6 unmodified lines
1573 # chained commands which all returned `None` -- so it's not1574 # even always obvious that `rv` indicates success/failure1575 # by its truthiness/falsiness1576 ctx.exit()1577 except Exit as e:1578 if not standalone_mode:1579 # in non-standalone mode, return the exit code1580 # note that this is only reached if `self.invoke` above raises1581 # an Exit explicitly -- thus bypassing the check there which1582 # would return its result1583 # the results of non-standalone execution may therefore be1584 # somewhat ambiguous: if there are codepaths which lead to1585 # `ctx.exit(1)` and to `return 1`, the caller won't be able to1586 # tell the difference between the two1587 return e.exit_code15881589 exit_code = e.exit_code1590 except Abort:1591 if not standalone_mode:1592 raise15931594 report = _echo_aborted1595 except (EOFError, KeyboardInterrupt) as e:1596 # The blank line closes the terminal's ``^C`` echo.1597 echo(file=sys.stderr)15981599 if not standalone_mode:1565 raise Abort() from e1600 raise Abort() from e16011602 report = _echo_aborted1603 except ClickException as e:1604 if not standalone_mode:1605 raise1569 e.show()1570 sys.exit(e.exit_code)16061607 report, exit_code = e.show, e.exit_code1608 except OSError as e:1572 if e.errno == errno.EPIPE:1573 sys.stdout = t.cast(t.TextIO, _PacifyFlushWrapper(sys.stdout))1574 sys.stderr = t.cast(t.TextIO, _PacifyFlushWrapper(sys.stderr))1575 sys.exit(1)1576 else:1609 if e.errno != errno.EPIPE:1610 raise1578 except Exit as e:1579 if standalone_mode:1580 sys.exit(e.exit_code)1581 else:1582 # in non-standalone mode, return the exit code1583 # note that this is only reached if `self.invoke` above raises1584 # an Exit explicitly -- thus bypassing the check there which1585 # would return its result1586 # the results of non-standalone execution may therefore be1587 # somewhat ambiguous: if there are codepaths which lead to1588 # `ctx.exit(1)` and to `return 1`, the caller won't be able to1589 # tell the difference between the two1590 return e.exit_code1591 except Abort:16111612 sys.stdout = t.cast(t.TextIO, _PacifyFlushWrapper(sys.stdout))1613 sys.stderr = t.cast(t.TextIO, _PacifyFlushWrapper(sys.stderr))16141615 if report is not None:1616 report()16171618 sys.exit(exit_code)1619 except (EOFError, KeyboardInterrupt):1620 if not standalone_mode:1621 raise1594 echo(_("Aborted!"), file=sys.stderr)1595 sys.exit(1)16221623 sys.exit(exit_code)16241625 def _main_shell_completion(1626 self,1627 ctx_args: cabc.MutableMapping[str, t.Any],1628 prog_name: str,
1733 unmodified lines
3362 action=action,3363 nargs=self.nargs,3364 )33653338 def get_help_record(self, ctx: Context) -> tuple[str, str] | None:3339 if self.hidden:3340 return None3366 def get_help_spec(self, ctx: Context) -> str:3367 """Returns the left column of the option's help record: its spellings3368 and metavar, like ``-v, --verbose`` or ``-c, --config TEXT``.33693370 Unlike :meth:`get_help_record`, the spec is produced even when the3371 option is :attr:`hidden`.33723373 .. versionadded:: 8.5.13374 """3375 any_prefix_is_slash = False33763377 def _write_opts(opts: cabc.Sequence[str]) -> str:3378 nonlocal any_prefix_is_slash
12 unmodified lines
33913392 if self.secondary_opts:3393 rv.append(_write_opts(self.secondary_opts))33943395 return ("; " if any_prefix_is_slash else " / ").join(rv)33963397 def get_help_record(self, ctx: Context) -> tuple[str, str] | None:3398 if self.hidden:3399 return None34003401 help = self.help or ""34023403 extra = self.get_help_extra(ctx)3404 extra_items = []
11 unmodified lines
3416 if extra_items:3417 extra_str = "; ".join(extra_items)3418 help = f"{help} [{extra_str}]" if help else f"[{extra_str}]"34193381 return ("; " if any_prefix_is_slash else " / ").join(rv), help3420 return self.get_help_spec(ctx), help34213422 def get_help_extra(self, ctx: Context) -> types.OptionHelpExtra:3423 extra: types.OptionHelpExtra = {}3424
414 unmodified lines
modified:src/click/termui.py+10 added
868 unmodified lines
869 Note for Windows: to simplify cross-platform usage, the newlines are870 automatically converted from POSIX to Windows and vice versa. As such,871 the message here will have ``\n`` as newline markers.872873 .. warning::874875 The contract of this utility is that the editor command blocks until876 the editing session is over: Click waits for it to exit before877 reading the file back and cleaning it up. Editors whose command878 launches the real editor in the background and exits immediately879 break that contract. Click then returns before editing begins and880 removes the temporary file while the editor still has it open. See881 :ref:`edit-wait` to make such editors wait.882883 :param text: the text to edit.884 :param editor: optionally the editor to use. Defaults to automatic885 detection.886 :param env: environment variables to forward to the editor.
138 unmodified lines
added:tests/test_exceptions/__init__.py
added:tests/test_exceptions/test_FileError.py+6 added
1import click234def test_file_error_surrogates():5 message = click.FileError(filename="\udcff").format_message()6 assert message == "Could not open file '�': unknown error"
added:tests/test_types/__init__.py
added:tests/test_types/test_Choice.py+7 added
1import click234def test_choice_get_invalid_choice_message():5 choice = click.Choice(["a", "b", "c"])6 message = choice.get_invalid_choice_message("d", ctx=None)7 assert message == "'d' is not one of 'a', 'b', 'c'."
added:tests/test_types/test_convert_type.py+108 added
1import datetime2import uuid34import pytest56import click789@pytest.mark.parametrize(10 "default",11 [12 # Empty sequences fall back to STRING because ``_guess_type`` returns None.13 [],14 (),15 # Container types are guessed from the default but are not natively16 # supported, so they reach STRING through a different code path.17 set(),18 {1, 2},19 frozenset(),20 frozenset(["git"]),21 {},22 {"a": 1},23 ],24)25def test_convert_type_from_container_default(default):26 """Container defaults are not natively supported and fall back to STRING.2728 Refs: https://github.com/pallets/click/issues/303629 """30 assert click.types.convert_type(None, default) is click.STRING313233@pytest.mark.parametrize(34 ("container_type", "value", "expected"),35 [36 (set, "a,b,c", {"a", ",", "b", "c"}),37 (frozenset, "abc", frozenset({"a", "b", "c"})),38 ],39)40def test_explicit_container_type_splits_string(container_type, value, expected):41 """An explicit ``set`` or ``frozenset`` type wraps the builtin in a42 ``FuncParamType``, which splits CLI strings character-wise.4344 Refs: https://github.com/pallets/click/issues/303645 """46 param_type = click.types.convert_type(container_type)47 assert isinstance(param_type, click.types.FuncParamType)48 assert param_type.convert(value, None, None) == expected495051@pytest.mark.parametrize(52 ("default", "expected"),53 [54 # Recognized scalars.55 (None, click.STRING),56 ("git", click.STRING),57 (5, click.INT),58 (1.5, click.FLOAT),59 (True, click.BOOL),60 # An empty sequence gives no item to read.61 ([], click.STRING),62 ((), click.STRING),63 # A sequence gives the type of its first item only.64 ([1, 2], click.INT),65 ((1, 2), click.INT),66 ([1.5, 2.5], click.FLOAT),67 ([1, "git"], click.INT),68 # Everything else falls back to STRING, including types Click ships.69 ({1, 2}, click.STRING),70 (frozenset({1, 2}), click.STRING),71 ({"a": 1}, click.STRING),72 (uuid.UUID(int=0), click.STRING),73 (datetime.datetime(2026, 1, 1), click.STRING),74 (b"git", click.STRING),75 (object(), click.STRING),76 ],77)78def test_type_inferred_from_default(default, expected):79 """Every row of the type-inference table in ``docs/parameter-types.md``.8081 Keep the two in step: a change here is a change to documented behavior.8283 Refs: https://github.com/pallets/click/issues/303684 """85 assert click.types.convert_type(None, default) is expected868788def test_type_inferred_from_nested_sequence_default():89 """A sequence of sequences gives a composite ``Tuple`` of the inner types.9091 This is the one table row that is not a singleton ``ParamType``.9293 Refs: https://github.com/pallets/click/issues/303694 """95 param_type = click.types.convert_type(None, [(1, "git")])96 assert isinstance(param_type, click.Tuple)97 assert param_type.types == [click.INT, click.STRING]9899100def test_explicit_dict_type_rejects_string():101 """An explicit ``dict`` type cannot convert a plain CLI string at all.102103 Refs: https://github.com/pallets/click/issues/3036104 """105 param_type = click.types.convert_type(dict)106 assert isinstance(param_type, click.types.FuncParamType)107 with pytest.raises(click.BadParameter):108 param_type.convert("abc", None, None)
added:tests/test_types/test_File.py+31 added
1import pytest23import click456@pytest.mark.parametrize(7 "type",8 [9 click.File(mode="r"),10 click.File(mode="r", lazy=True),11 ],12)13def test_file_surrogates(type, tmp_path):14 """Ensures that the error handling in ``click.File`` is robust.1516 ``EILSEQ`` shows up with rootless Podman (FUSE-backed paths) and on filesystems17 that reject non-UTF-8 names, like ZFS with ``utf8only=on``.1819 See: https://github.com/pallets/click/issues/263420 """21 path = tmp_path / "\udcff"22 match = (23 # Common case: �': No such file or directory.24 r"(�': No such file or directory"25 # BSD/macOS libc special case (EILSEQ).26 r"|Illegal byte sequence"27 # glibc special case (EILSEQ).28 r"|Invalid or incomplete multibyte or wide character)"29 )30 with pytest.raises(click.BadParameter, match=match):31 type.convert(path, None, None)
added:tests/test_types/test_FloatRange.py+42 added
1import pytest23import click456@pytest.mark.parametrize(7 ("type", "value", "expect"),8 [9 (click.FloatRange(0.5, 1.5), "1.2", 1.2),10 (click.FloatRange(0.5, min_open=True), "0.51", 0.51),11 (click.FloatRange(max=1.5, max_open=True), "1.49", 1.49),12 (click.FloatRange(0.5, clamp=True), "-0.0", 0.5),13 (click.FloatRange(max=1.5, clamp=True), "inf", 1.5),14 ],15)16def test_range(type, value, expect):17 assert type.convert(value, None, None) == expect181920@pytest.mark.parametrize(21 ("type", "value", "expect"),22 [23 (click.FloatRange(0.5, min_open=True), 0.5, "x>0.5"),24 (click.FloatRange(max=1.5, max_open=True), 1.5, "x<1.5"),25 ],26)27def test_range_fail(type, value, expect):28 with pytest.raises(click.BadParameter) as exc_info:29 type.convert(value, None, None)3031 assert expect in exc_info.value.message323334def test_float_range_no_clamp_open():35 with pytest.raises(TypeError):36 click.FloatRange(0, 1, max_open=True, clamp=True)3738 sneaky = click.FloatRange(0, 1, max_open=True)39 sneaky.clamp = True4041 with pytest.raises(RuntimeError):42 sneaky.convert("1.5", None, None)
added:tests/test_types/test_FuncParamType.py+22 added
1import pytest23import click456@pytest.mark.parametrize(7 ("error_message", "expected"),8 [9 ("bad value: nope", "bad value: nope"),10 ("", "nope"),11 ],12)13def test_func_param_type_uses_value_error_message(error_message, expected):14 def parse(value):15 raise ValueError(error_message if error_message else "")1617 func_type = click.types.FuncParamType(parse)1819 with pytest.raises(click.BadParameter) as exc_info:20 func_type.convert("nope", None, None)2122 assert expected in exc_info.value.message
added:tests/test_types/test_IntRange.py+38 added
1import pytest23import click456@pytest.mark.parametrize(7 ("type", "value", "expect"),8 [9 (click.IntRange(0, 5), "3", 3),10 (click.IntRange(5), "5", 5),11 (click.IntRange(5), "100", 100),12 (click.IntRange(max=5), "5", 5),13 (click.IntRange(max=5), "-100", -100),14 (click.IntRange(0, clamp=True), "-1", 0),15 (click.IntRange(max=5, clamp=True), "6", 5),16 (click.IntRange(0, min_open=True, clamp=True), "0", 1),17 (click.IntRange(max=5, max_open=True, clamp=True), "5", 4),18 ],19)20def test_range(type, value, expect):21 assert type.convert(value, None, None) == expect222324@pytest.mark.parametrize(25 ("type", "value", "expect"),26 [27 (click.IntRange(0, 5), "6", "6 is not in the range 0<=x<=5."),28 (click.IntRange(5), "4", "4 is not in the range x>=5."),29 (click.IntRange(max=5), "6", "6 is not in the range x<=5."),30 (click.IntRange(0, 5, min_open=True), 0, "0<x<=5"),31 (click.IntRange(0, 5, max_open=True), 5, "0<=x<5"),32 ],33)34def test_range_fail(type, value, expect):35 with pytest.raises(click.BadParameter) as exc_info:36 type.convert(value, None, None)3738 assert expect in exc_info.value.message
added:tests/test_types/test_ParamType.py+24 added
1import typing as t23import click456def test_param_type_input_parameter_defaults_at_runtime():7 """Omitting the input type parameter works at runtime on every8 supported Python. The ``Any`` default is native (PEP 696) on Python9 3.13+, and backfilled by ``ParamType.__class_getitem__`` before10 that."""11 assert t.get_args(click.ParamType[int]) == (int, t.Any)12 assert t.get_args(click.ParamType[int, str]) == (int, str)131415def test_param_type_subclass_omitting_input_parameter():16 class DoublingType(click.ParamType[int]):17 name = "doubling"1819 def convert(self, value, param, ctx):20 return int(value) * 22122 doubling = DoublingType()23 assert doubling("21") == 4224 assert doubling(None) is None
added:tests/test_types/test_Path.py+185 added
1import os2import pathlib3import platform4import subprocess5import sys6import tempfile78import pytest910import click111213def test_path_dash_no_byteswarning():14 """Detecting the ``-`` dash sentinel must not compare ``bytes`` against15 ``str``, which raises a ``BytesWarning`` under ``python -bb``.1617 The warning is only emitted when the interpreter runs with ``-b``, so this18 has to be checked in a subprocess. ``-bb`` turns the warning into an error,19 so a clean exit means no mismatched comparison happened.20 """21 program = (22 "import click\n"23 "convert = click.Path(allow_dash=True).convert\n"24 "for value in ('-', '', b'-', b''):\n"25 " convert(value, None, None)\n"26 )27 result = subprocess.run(28 [sys.executable, "-bb", "-c", program],29 capture_output=True,30 text=True,31 )32 assert result.returncode == 0, result.stderr33 assert "BytesWarning" not in result.stderr343536def _symlinks_supported():37 with tempfile.TemporaryDirectory(prefix="click-pytest-") as tempdir:38 target = os.path.join(tempdir, "target")39 open(target, "w").close()40 link = os.path.join(tempdir, "link")4142 try:43 os.symlink(target, link)44 return True45 except OSError:46 return False474849@pytest.mark.skipif(50 not _symlinks_supported(), reason="The current OS or FS doesn't support symlinks."51)52def test_path_resolve_symlink(tmp_path, runner):53 test_file = tmp_path / "file"54 test_file_str = os.fspath(test_file)55 test_file.write_text("")5657 path_type = click.Path(resolve_path=True)58 param = click.Argument(["a"], type=path_type)59 ctx = click.Context(click.Command("cli", params=[param]))6061 test_dir = tmp_path / "dir"62 test_dir.mkdir()6364 abs_link = test_dir / "abs"65 abs_link.symlink_to(test_file)66 abs_rv = path_type.convert(os.fspath(abs_link), param, ctx)67 assert abs_rv == test_file_str6869 rel_link = test_dir / "rel"70 rel_link.symlink_to(pathlib.Path("..") / "file")71 rel_rv = path_type.convert(os.fspath(rel_link), param, ctx)72 assert rel_rv == test_file_str737475def _non_utf8_filenames_supported():76 with tempfile.TemporaryDirectory(prefix="click-pytest-") as tempdir:77 try:78 f = open(os.path.join(tempdir, "\udcff"), "w")79 except OSError:80 return False8182 f.close()83 return True848586@pytest.mark.skipif(87 not _non_utf8_filenames_supported(),88 reason="The current OS or FS doesn't support non-UTF-8 filenames.",89)90def test_path_surrogates(tmp_path, monkeypatch):91 monkeypatch.chdir(tmp_path)92 type = click.Path(exists=True)93 path = pathlib.Path("\udcff")9495 with pytest.raises(click.BadParameter, match="'�' does not exist"):96 type.convert(path, None, None)9798 type = click.Path(file_okay=False)99 path.touch()100101 with pytest.raises(click.BadParameter, match="'�' is a file"):102 type.convert(path, None, None)103104 path.unlink()105 type = click.Path(dir_okay=False)106 path.mkdir()107108 with pytest.raises(click.BadParameter, match="'�' is a directory"):109 type.convert(path, None, None)110111 path.rmdir()112113 def no_access(*args, **kwargs):114 """Test environments may be running as root, so we have to fake the result of115 the access tests that use os.access116 """117 p = args[0]118 assert p == path, f"unexpected os.access call on file not under test: {p!r}"119 return False120121 path.touch()122 type = click.Path(readable=True)123124 with pytest.raises(click.BadParameter, match="'�' is not readable"):125 with monkeypatch.context() as m:126 m.setattr(os, "access", no_access)127 type.convert(path, None, None)128129 type = click.Path(readable=False, writable=True)130131 with pytest.raises(click.BadParameter, match="'�' is not writable"):132 with monkeypatch.context() as m:133 m.setattr(os, "access", no_access)134 type.convert(path, None, None)135136 type = click.Path(readable=False, executable=True)137138 with pytest.raises(click.BadParameter, match="'�' is not executable"):139 with monkeypatch.context() as m:140 m.setattr(os, "access", no_access)141 type.convert(path, None, None)142143 path.unlink()144145146def _non_utf8_filenames_supported():147 with tempfile.TemporaryDirectory(prefix="click-pytest-") as tempdir:148 try:149 f = open(os.path.join(tempdir, "\udcff"), "w")150 except OSError:151 return False152153 f.close()154 return True155156157@pytest.mark.skipif(158 platform.system() == "Windows", reason="Filepath syntax differences."159)160def test_invalid_path_with_esc_sequence():161 with pytest.raises(click.BadParameter) as exc_info:162 with tempfile.TemporaryDirectory(prefix="my\ndir") as tempdir:163 click.Path(dir_okay=False).convert(tempdir, None, None)164165 assert "my\\ndir" in exc_info.value.message166167168@pytest.mark.parametrize(169 ("cls", "expect"),170 [171 (None, "a/b/c.txt"),172 (str, "a/b/c.txt"),173 (bytes, b"a/b/c.txt"),174 (pathlib.Path, pathlib.Path("a", "b", "c.txt")),175 ],176)177def test_path_type(runner, cls, expect):178 cli = click.Command(179 "cli",180 params=[click.Argument(["p"], type=click.Path(path_type=cls))],181 callback=lambda p: p,182 )183 result = runner.invoke(cli, ["a/b/c.txt"], standalone_mode=False)184 assert result.exception is None185 assert result.return_value == expect
modified:tests/test_utils/test_sentinel.py+45 added
1import copy2import pickle3from decimal import Decimal4from fractions import Fraction56import pytest78import click9from click._utils import Sentinel10from click._utils import UNSET111213def test_unset_sentinel():
41 unmodified lines
55 assert value != real_value56 assert value is not real_value5758 assert value not in real_values596061@pytest.mark.parametrize("sentinel", tuple(Sentinel))62@pytest.mark.parametrize(63 "duplicate",64 (65 copy.copy,66 copy.deepcopy,67 lambda value: pickle.loads(pickle.dumps(value)),68 ),69 ids=("copy", "deepcopy", "pickle"),70)71def test_sentinel_duplication_preserves_identity(sentinel, duplicate):72 """Sentinels are singletons: copying or pickling one returns the member.7374 The default ``Enum`` reduction is ``(cls, (member.value,))``, which cannot75 round-trip a bare ``object()`` value: the copy or the unpickled value is a76 new object and ``Sentinel()`` rejects it.77 """78 assert duplicate(sentinel) is sentinel798081@pytest.mark.parametrize(82 "duplicate",83 (84 copy.copy,85 copy.deepcopy,86 lambda value: pickle.loads(pickle.dumps(value)),87 ),88 ids=("copy", "deepcopy", "pickle"),89)90def test_parameter_duplication(duplicate):91 """Every ``Parameter`` holds ``UNSET`` in ``default`` unless one is given."""92 option = click.Option(["--name"])93 assert option.default is UNSET9495 duplicated = duplicate(option)96 assert duplicated.default is UNSET97 assert duplicated.name == "name"
added:tests/test_abort_interrupt.py+179 added
1"""A second Ctrl-C while ``Command.main()`` reported an abort or an error used2to escape as an unhandled traceback: the message and the exit both ran in3``except`` clauses, outside every ``try`` that caught ``KeyboardInterrupt``.4https://github.com/pallets/click/issues/380256The fix holds one policy, the one the pager has followed since7https://github.com/pallets/click/pull/351: a late interrupt must not replace8the intended outcome. In standalone mode the collected exit code wins, for9aborts, errors and success alike, and the message is best effort. Without10standalone mode the interrupt propagates to the caller. Two settled contracts11stay in place: the first interrupt reaches a non-standalone caller as12``Abort`` (https://github.com/pallets/click/pull/2380), and the ``Aborted!``13message stays as it is (declined in14https://github.com/pallets/click/issues/1447 and15https://github.com/pallets/click/issues/2584).16"""1718import sys1920import pytest2122import click232425class RecordingStderr:26 """A stderr stand-in that records what is written to it.2728 With ``interrupt_at=N``, the ``N``-th ``isatty()`` call raises29 ``KeyboardInterrupt``. ``echo()`` calls ``isatty()`` before writing, which30 is where the traceback in issue #3802 ended.31 """3233 def __init__(self, interrupt_at=None):34 self.text = ""35 self.interrupt_at = interrupt_at36 self.isatty_calls = 03738 def isatty(self):39 self.isatty_calls += 14041 if self.isatty_calls == self.interrupt_at:42 raise KeyboardInterrupt4344 return False4546 def write(self, value):47 self.text += value48 return len(value)4950 def flush(self):51 pass525354def _interrupt_prompt(text):55 """Stand in for ``input()`` when the user presses Ctrl-C at a prompt."""56 raise KeyboardInterrupt575859def _prompting_command():60 @click.command()61 @click.option("--name", prompt="Name")62 def cli(name):63 click.echo(name)6465 return cli666768def _interrupting_command():69 @click.command()70 def cli():71 raise KeyboardInterrupt7273 return cli747576def _exit_code(cli, stderr, monkeypatch):77 """Run *cli* in standalone mode and return its exit code."""78 monkeypatch.setattr(sys, "stderr", stderr)7980 try:81 cli.main([], "cli")82 except SystemExit as e:83 return e.code84 except KeyboardInterrupt:85 pytest.fail("KeyboardInterrupt escaped Command.main()")8687 pytest.fail("Command.main() returned without exiting")888990@pytest.mark.parametrize(91 ("source", "interrupt_at"),92 [("prompt", None), ("prompt", 1), ("body", None), ("body", 1), ("body", 2)],93)94def test_interrupt_while_reporting_abort(monkeypatch, source, interrupt_at):95 """Exit code 1 survives a second Ctrl-C; the message may not.9697 The counted ``isatty`` picks the window. A prompt converts the interrupt98 to ``Abort`` itself, so the only window left in ``Command.main()`` is the99 ``Aborted!`` message (``1``). An interrupt from the command body goes100 through the conversion in ``Command.main()``, which writes a blank line101 first (``1``), before the message (``2``).102 """103 if source == "prompt":104 monkeypatch.setattr("click.termui.visible_prompt_func", _interrupt_prompt)105 cli = _prompting_command()106 else:107 cli = _interrupting_command()108109 stderr = RecordingStderr(interrupt_at=interrupt_at)110111 assert _exit_code(cli, stderr, monkeypatch) == 1112113 if interrupt_at is None:114 assert "Aborted!" in stderr.text115116117def test_interrupt_while_reporting_error(monkeypatch):118 """A Ctrl-C while Click writes an error keeps the error's exit code."""119120 class InterruptedReport(click.ClickException):121 exit_code = 3122123 def show(self, file=None):124 raise KeyboardInterrupt125126 @click.command()127 def cli():128 raise InterruptedReport("boom")129130 assert _exit_code(cli, RecordingStderr(), monkeypatch) == 3131132133def test_late_interrupt_with_disabled_standalone_mode(monkeypatch):134 """Without standalone mode, a late interrupt reaches the caller, not exit 1.135136 The patched ``Abort`` raises a second ``KeyboardInterrupt`` from its137 constructor: it lands on the ``raise Abort() from e`` statement that138 ``Command.main()`` only runs for non-standalone callers.139 """140141 class InterruptedAbort(click.Abort):142 def __init__(self):143 raise KeyboardInterrupt144145 monkeypatch.setattr(click.core, "Abort", InterruptedAbort)146 cli = _interrupting_command()147 monkeypatch.setattr(sys, "stderr", RecordingStderr())148149 with pytest.raises(KeyboardInterrupt):150 cli.main([], "cli", standalone_mode=False)151152153def test_interrupt_while_exiting_after_success(monkeypatch):154 """A Ctrl-C while a successful exit propagates keeps exit code 0.155156 The uniform policy: the run completed before the interrupt arrived, so the157 intended outcome wins for success exactly as it does for aborts and158 errors.159 """160161 @click.command()162 def cli():163 click.echo("done")164165 real_exit = sys.exit166 codes = []167168 def interrupted_exit(code=None):169 codes.append(code)170171 if len(codes) == 1:172 raise KeyboardInterrupt173174 real_exit(code)175176 monkeypatch.setattr(sys, "exit", interrupted_exit)177178 assert _exit_code(cli, RecordingStderr(), monkeypatch) == 0179 assert codes == [0, 0]
modified:tests/test_basic.py+24 added
958 unmodified lines
959960 result = runner.invoke(cli, ["--version"], prog_name="mytool")961 assert result.exit_code == 0962 assert result.output == "mytool 1.0\n"963964965@pytest.mark.parametrize(966 ("nargs", "multiple", "default", "expect"),967 [968 (2, False, None, None),969 (2, False, (None, None), (None, None)),970 (None, True, None, ()),971 (None, True, (None, None), (None, None)),972 (2, True, None, ()),973 (2, True, [(None, None)], ((None, None),)),974 (-1, None, None, ()),975 ],976)977def test_cast_multi_default(runner, nargs, multiple, default, expect):978 if nargs == -1:979 param = click.Argument(["a"], nargs=nargs, default=default)980 else:981 param = click.Option(["-a"], nargs=nargs, multiple=multiple, default=default)982983 cli = click.Command("cli", params=[param], callback=lambda a: a)984 result = runner.invoke(cli, standalone_mode=False)985 assert result.exception is None986 assert result.return_value == expect
modified:tests/test_defaults.py+4 added
180 unmodified lines
181 ({"key": None}, "key", None),182 ({"key": 0}, "key", 0),183 ({"key": ""}, "key", ""),184 ({"key": False}, "key", False),185 # Falsy containers are returned as-is too.186 ({"key": set()}, "key", set()),187 ({"key": frozenset()}, "key", frozenset()),188 ({"key": {}}, "key", {}),189 ],190)191def test_lookup_default_returns_hides_sentinel(default_map, key, expected):192 """``lookup_default()`` should return ``None`` for missing keys, not :attr:`UNSET`.
375 unmodified lines
modified:tests/test_options.py+111 added-7 removed
70 unmodified lines
71 ctx = click.Context(click.Command("cli"))72 assert opt.get_help_record(ctx)[1] == expected737475@pytest.mark.parametrize(76 ("param_decls", "kwargs", "expected"),77 [78 (["-v", "--verbose"], {"is_flag": True}, "-v, --verbose"),79 (["--config"], {}, "--config TEXT"),80 (["--color/--no-color"], {}, "--color / --no-color"),81 (["/debug;/no-debug"], {}, "/debug; /no-debug"),82 ],83)84@pytest.mark.parametrize("hidden", [False, True])85def test_help_spec(param_decls, kwargs, hidden, expected):86 """A hidden option still produces its spec via ``get_help_spec()``, unlike87 ``get_help_record()``.88 """89 opt = click.Option(param_decls, hidden=hidden, **kwargs)90 ctx = click.Context(click.Command("cli"))91 assert opt.get_help_spec(ctx) == expected9293 if hidden:94 assert opt.get_help_record(ctx) is None95 else:96 assert opt.get_help_record(ctx)[0] == expected979899@pytest.mark.parametrize("deprecated", [True, "USE B INSTEAD"])100def test_deprecated_warning(runner, deprecated):101 @click.command()102 @click.option(
350 unmodified lines
453 )454 assert not result.exception455 assert result.output == "foo|bar|baz\n"456457458def test_envvar_container_type(runner):459 """Env vars are plain strings, so a container type splits them character-wise.460461 Refs: https://github.com/pallets/click/issues/3036462 """463464 @click.command()465 @click.option("--x", envvar="X", type=frozenset)466 def cli(x):467 assert isinstance(x, frozenset)468 click.echo("".join(sorted(x)))469470 result = runner.invoke(cli, [], env={"X": "git"})471 assert not result.exception472 assert result.output == "git\n"473474 @click.command()475 @click.option("--arg", multiple=True, envvar="X")476 def cmd(arg):477 click.echo("|".join(arg))478
155 unmodified lines
634 assert not result.exception635 assert "[default: b]" in result.output636637638def test_show_default_container_defaults(runner):639 """Container defaults are rendered through ``str()`` in the help output.640641 Refs: https://github.com/pallets/click/issues/3036642 """643644 @click.command()645 @click.option("--a", default=frozenset(["git"]), type=frozenset, show_default=True)646 @click.option("--b", default={"a": 1}, type=dict, show_default=True)647 @click.option("--c", default={"git"}, type=set, show_default=True)648 def cli(a, b, c):649 pass650651 result = runner.invoke(cli, ["--help"])652 assert "[default: frozenset({'git'})]" in result.output653 assert "[default: {'a': 1}]" in result.output654 assert "[default: {'git'}]" in result.output655656657def test_multiple_default_type():658 opt = click.Option(["-a"], multiple=True, default=(1, 2))659 assert opt.nargs == 1660 assert opt.multiple
11 unmodified lines
672 ctx = click.Context(click.Command("test"))673 assert opt.type_cast_value(ctx, opt.get_default(ctx)) == ((1, "a"),)674675676@pytest.mark.parametrize(677 "default",678 [679 set(),680 {1, 2},681 frozenset(),682 frozenset(["git"]),683 {},684 {"a": 1},685 ],686)687def test_type_from_default_container(default):688 """Container defaults have no native Click type and fall back to STRING.689690 The documented "if no type is provided, the type of the default value is691 used" rule does not apply to ``set``, ``frozenset`` or ``dict`` defaults.692693 Refs: https://github.com/pallets/click/issues/3036694 """695 opt = click.Option(["-a"], default=default)696 assert opt.type is click.STRING697698699def test_parse_multiple_default_composite_type(runner):700 @click.command()701 @click.option("-a", multiple=True, default=("a", "b"))702 @click.option("-b", multiple=True, default=[(1, "a")])
804 unmodified lines
1507 param = click.Option(["-c", "x"], flag_value=EngineType.OSS)1508 assert param.type is click.UNPROCESSED1509 param = click.Option(["-d", "x"], flag_value=frozenset())1510 assert param.type is click.UNPROCESSED1511 param = click.Option(["-e", "x"], flag_value=set())1512 assert param.type is click.UNPROCESSED1513 param = click.Option(["-f", "x"], flag_value={})1514 assert param.type is click.UNPROCESSED151515161517@pytest.mark.parametrize(1518 ("opt_params", "args", "expected"),
1103 unmodified lines
2622 assert result.exit_code == 02623 assert result.output == repr(EngineType.PRO)262426252539def test_custom_type_frozenset_flag_value(runner):2540 """Check that frozenset is correctly handled as a type, a flag value and a default.2626@pytest.mark.parametrize(2627 ("container_type", "flag_value", "default", "default_output", "flag_output"),2628 [2629 (set, set(), {"git"}, "{'git'}", "set()"),2630 (2631 frozenset,2632 frozenset(),2633 frozenset(["git"]),2634 "frozenset({'git'})",2635 "frozenset()",2636 ),2637 (dict, dict(), {"git": True}, "{'git': True}", "{}"),2638 ],2639)2640def test_custom_type_container_flag_value(2641 runner, container_type, flag_value, default, default_output, flag_output2642):2643 """Check that container types are correctly handled as a type, a flag value2644 and a default.26452646 Reproduces https://github.com/pallets/click/issues/26102647 """2648
1 unmodified line
2650 @click.option(2651 "--without-scm-ignore-files",2652 "scm_ignore_files",2653 is_flag=True,2550 type=frozenset,2551 flag_value=frozenset(),2552 default=frozenset(["git"]),2654 type=container_type,2655 flag_value=flag_value,2656 default=default,2657 )2658 def rcli(scm_ignore_files):2659 click.echo(repr(scm_ignore_files), nl=False)26602661 result = runner.invoke(rcli)2558 assert result.stdout == "frozenset({'git'})"2662 assert result.stdout == default_output2663 assert result.exit_code == 026642665 result = runner.invoke(rcli, ["--without-scm-ignore-files"])2562 assert result.stdout == "frozenset()"2666 assert result.stdout == flag_output2667 assert result.exit_code == 0266826692670@pytest.mark.parametrize(
985 unmodified lines
deleted:tests/test_types.py-332 removed
1import os.path2import pathlib3import platform4import subprocess5import sys6import tempfile7import typing as t89import pytest1011import click12from click import FileError131415@pytest.mark.parametrize(16 ("type", "value", "expect"),17 [18 (click.IntRange(0, 5), "3", 3),19 (click.IntRange(5), "5", 5),20 (click.IntRange(5), "100", 100),21 (click.IntRange(max=5), "5", 5),22 (click.IntRange(max=5), "-100", -100),23 (click.IntRange(0, clamp=True), "-1", 0),24 (click.IntRange(max=5, clamp=True), "6", 5),25 (click.IntRange(0, min_open=True, clamp=True), "0", 1),26 (click.IntRange(max=5, max_open=True, clamp=True), "5", 4),27 (click.FloatRange(0.5, 1.5), "1.2", 1.2),28 (click.FloatRange(0.5, min_open=True), "0.51", 0.51),29 (click.FloatRange(max=1.5, max_open=True), "1.49", 1.49),30 (click.FloatRange(0.5, clamp=True), "-0.0", 0.5),31 (click.FloatRange(max=1.5, clamp=True), "inf", 1.5),32 ],33)34def test_range(type, value, expect):35 assert type.convert(value, None, None) == expect363738@pytest.mark.parametrize(39 ("type", "value", "expect"),40 [41 (click.IntRange(0, 5), "6", "6 is not in the range 0<=x<=5."),42 (click.IntRange(5), "4", "4 is not in the range x>=5."),43 (click.IntRange(max=5), "6", "6 is not in the range x<=5."),44 (click.IntRange(0, 5, min_open=True), 0, "0<x<=5"),45 (click.IntRange(0, 5, max_open=True), 5, "0<=x<5"),46 (click.FloatRange(0.5, min_open=True), 0.5, "x>0.5"),47 (click.FloatRange(max=1.5, max_open=True), 1.5, "x<1.5"),48 ],49)50def test_range_fail(type, value, expect):51 with pytest.raises(click.BadParameter) as exc_info:52 type.convert(value, None, None)5354 assert expect in exc_info.value.message555657@pytest.mark.parametrize(58 ("error_message", "expected"),59 [60 ("bad value: nope", "bad value: nope"),61 ("", "nope"),62 ],63)64def test_func_param_type_uses_value_error_message(error_message, expected):65 def parse(value):66 raise ValueError(error_message if error_message else "")6768 func_type = click.types.FuncParamType(parse)6970 with pytest.raises(click.BadParameter) as exc_info:71 func_type.convert("nope", None, None)7273 assert expected in exc_info.value.message747576def test_float_range_no_clamp_open():77 with pytest.raises(TypeError):78 click.FloatRange(0, 1, max_open=True, clamp=True)7980 sneaky = click.FloatRange(0, 1, max_open=True)81 sneaky.clamp = True8283 with pytest.raises(RuntimeError):84 sneaky.convert("1.5", None, None)858687@pytest.mark.parametrize(88 ("nargs", "multiple", "default", "expect"),89 [90 (2, False, None, None),91 (2, False, (None, None), (None, None)),92 (None, True, None, ()),93 (None, True, (None, None), (None, None)),94 (2, True, None, ()),95 (2, True, [(None, None)], ((None, None),)),96 (-1, None, None, ()),97 ],98)99def test_cast_multi_default(runner, nargs, multiple, default, expect):100 if nargs == -1:101 param = click.Argument(["a"], nargs=nargs, default=default)102 else:103 param = click.Option(["-a"], nargs=nargs, multiple=multiple, default=default)104105 cli = click.Command("cli", params=[param], callback=lambda a: a)106 result = runner.invoke(cli, standalone_mode=False)107 assert result.exception is None108 assert result.return_value == expect109110111@pytest.mark.parametrize(112 ("cls", "expect"),113 [114 (None, "a/b/c.txt"),115 (str, "a/b/c.txt"),116 (bytes, b"a/b/c.txt"),117 (pathlib.Path, pathlib.Path("a", "b", "c.txt")),118 ],119)120def test_path_type(runner, cls, expect):121 cli = click.Command(122 "cli",123 params=[click.Argument(["p"], type=click.Path(path_type=cls))],124 callback=lambda p: p,125 )126 result = runner.invoke(cli, ["a/b/c.txt"], standalone_mode=False)127 assert result.exception is None128 assert result.return_value == expect129130131def test_path_dash_no_byteswarning():132 """Detecting the ``-`` dash sentinel must not compare ``bytes`` against133 ``str``, which raises a ``BytesWarning`` under ``python -bb``.134135 The warning is only emitted when the interpreter runs with ``-b``, so this136 has to be checked in a subprocess. ``-bb`` turns the warning into an error,137 so a clean exit means no mismatched comparison happened.138 """139 program = (140 "import click\n"141 "convert = click.Path(allow_dash=True).convert\n"142 "for value in ('-', '', b'-', b''):\n"143 " convert(value, None, None)\n"144 )145 result = subprocess.run(146 [sys.executable, "-bb", "-c", program],147 capture_output=True,148 text=True,149 )150 assert result.returncode == 0, result.stderr151 assert "BytesWarning" not in result.stderr152153154def _symlinks_supported():155 with tempfile.TemporaryDirectory(prefix="click-pytest-") as tempdir:156 target = os.path.join(tempdir, "target")157 open(target, "w").close()158 link = os.path.join(tempdir, "link")159160 try:161 os.symlink(target, link)162 return True163 except OSError:164 return False165166167@pytest.mark.skipif(168 not _symlinks_supported(), reason="The current OS or FS doesn't support symlinks."169)170def test_path_resolve_symlink(tmp_path, runner):171 test_file = tmp_path / "file"172 test_file_str = os.fspath(test_file)173 test_file.write_text("")174175 path_type = click.Path(resolve_path=True)176 param = click.Argument(["a"], type=path_type)177 ctx = click.Context(click.Command("cli", params=[param]))178179 test_dir = tmp_path / "dir"180 test_dir.mkdir()181182 abs_link = test_dir / "abs"183 abs_link.symlink_to(test_file)184 abs_rv = path_type.convert(os.fspath(abs_link), param, ctx)185 assert abs_rv == test_file_str186187 rel_link = test_dir / "rel"188 rel_link.symlink_to(pathlib.Path("..") / "file")189 rel_rv = path_type.convert(os.fspath(rel_link), param, ctx)190 assert rel_rv == test_file_str191192193def _non_utf8_filenames_supported():194 with tempfile.TemporaryDirectory(prefix="click-pytest-") as tempdir:195 try:196 f = open(os.path.join(tempdir, "\udcff"), "w")197 except OSError:198 return False199200 f.close()201 return True202203204@pytest.mark.skipif(205 not _non_utf8_filenames_supported(),206 reason="The current OS or FS doesn't support non-UTF-8 filenames.",207)208def test_path_surrogates(tmp_path, monkeypatch):209 monkeypatch.chdir(tmp_path)210 type = click.Path(exists=True)211 path = pathlib.Path("\udcff")212213 with pytest.raises(click.BadParameter, match="'�' does not exist"):214 type.convert(path, None, None)215216 type = click.Path(file_okay=False)217 path.touch()218219 with pytest.raises(click.BadParameter, match="'�' is a file"):220 type.convert(path, None, None)221222 path.unlink()223 type = click.Path(dir_okay=False)224 path.mkdir()225226 with pytest.raises(click.BadParameter, match="'�' is a directory"):227 type.convert(path, None, None)228229 path.rmdir()230231 def no_access(*args, **kwargs):232 """Test environments may be running as root, so we have to fake the result of233 the access tests that use os.access234 """235 p = args[0]236 assert p == path, f"unexpected os.access call on file not under test: {p!r}"237 return False238239 path.touch()240 type = click.Path(readable=True)241242 with pytest.raises(click.BadParameter, match="'�' is not readable"):243 with monkeypatch.context() as m:244 m.setattr(os, "access", no_access)245 type.convert(path, None, None)246247 type = click.Path(readable=False, writable=True)248249 with pytest.raises(click.BadParameter, match="'�' is not writable"):250 with monkeypatch.context() as m:251 m.setattr(os, "access", no_access)252 type.convert(path, None, None)253254 type = click.Path(readable=False, executable=True)255256 with pytest.raises(click.BadParameter, match="'�' is not executable"):257 with monkeypatch.context() as m:258 m.setattr(os, "access", no_access)259 type.convert(path, None, None)260261 path.unlink()262263264@pytest.mark.parametrize(265 "type",266 [267 click.File(mode="r"),268 click.File(mode="r", lazy=True),269 ],270)271def test_file_surrogates(type, tmp_path):272 """Ensures that the error handling in ``click.File`` is robust.273274 ``EILSEQ`` shows up with rootless Podman (FUSE-backed paths) and on filesystems275 that reject non-UTF-8 names, like ZFS with ``utf8only=on``.276277 See: https://github.com/pallets/click/issues/2634278 """279 path = tmp_path / "\udcff"280 match = (281 # Common case: �': No such file or directory.282 r"(�': No such file or directory"283 # BSD/macOS libc special case (EILSEQ).284 r"|Illegal byte sequence"285 # glibc special case (EILSEQ).286 r"|Invalid or incomplete multibyte or wide character)"287 )288 with pytest.raises(click.BadParameter, match=match):289 type.convert(path, None, None)290291292def test_file_error_surrogates():293 message = FileError(filename="\udcff").format_message()294 assert message == "Could not open file '�': unknown error"295296297@pytest.mark.skipif(298 platform.system() == "Windows", reason="Filepath syntax differences."299)300def test_invalid_path_with_esc_sequence():301 with pytest.raises(click.BadParameter) as exc_info:302 with tempfile.TemporaryDirectory(prefix="my\ndir") as tempdir:303 click.Path(dir_okay=False).convert(tempdir, None, None)304305 assert "my\\ndir" in exc_info.value.message306307308def test_choice_get_invalid_choice_message():309 choice = click.Choice(["a", "b", "c"])310 message = choice.get_invalid_choice_message("d", ctx=None)311 assert message == "'d' is not one of 'a', 'b', 'c'."312313314def test_param_type_input_parameter_defaults_at_runtime():315 """Omitting the input type parameter works at runtime on every316 supported Python. The ``Any`` default is native (PEP 696) on Python317 3.13+, and backfilled by ``ParamType.__class_getitem__`` before318 that."""319 assert t.get_args(click.ParamType[int]) == (int, t.Any)320 assert t.get_args(click.ParamType[int, str]) == (int, str)321322323def test_param_type_subclass_omitting_input_parameter():324 class DoublingType(click.ParamType[int]):325 name = "doubling"326327 def convert(self, value, param, ctx):328 return int(value) * 2329330 doubling = DoublingType()331 assert doubling("21") == 42332 assert doubling(None) is None
modified:CHANGES.md+10 added
1## Version 8.5.123Unreleased45- Fix `copy.deepcopy()` and `pickle` on a `Parameter`, `Option` or `Command`. {pr}`3805`6- A `KeyboardInterrupt` arriving while `Command.main()` reports an abort or an error,7 or while it exits, no longer escapes as an unhandled traceback. The command still8 exits with the intended code; only the message may be lost. {issue}`3802`9- Add {meth}`Option.get_help_spec`, which returns the option's left help10 column even when the option is hidden. {meth}`Option.get_help_record` still11 returns `None` for hidden options, so help screens are unchanged. {pr}`3821`12- Document which types are inferred from `default`, and what an unrecognized13 `type` callable does to a command-line value. {issue}`3036` {pr}`3808`1415## Version 8.5.01617Released 2026-08-2418
1654 unmodified lines