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
Provenance
- Commit
6aabf09- Tree
014c6c6- Author
Rowlando13 <67291205+Rowlando13@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent 1
36baa15- Parent 2
7944461
30 files changed+1201 added−392 removed
modified:docs/arguments.md+4 added-2 removed
43 unmodified lines4445464748494849505152535455136 unmodified linesExpand all43 unmodified lines invoke(touch, args=['foo.txt'])```
An argument may be assigned a {ref}`parameter type <parameter-types>`.If no type is provided, the type of the default value is used. If nodefault value is provided, the type is assumed to be {data}`STRING`.If no type is provided, the type of the default value is used if it isrecognized, otherwise {data}`STRING` is used. If no default value isprovided, the type is assumed to be {data}`STRING`. See{ref}`type-inference` for the types that are recognized.
```{admonition} Note on Required Arguments:class: note
136 unmodified linesExpand allmodified:docs/complex.md+3 added-3 removed
348 unmodified lines349 and then resolve `baz`. Each subcommand resolution step does a lazy load.350 2. 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`.353-3. 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.353+3. 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.356 357 ### Further Deferring Imports358 359 It is possible to make the process even lazier, but it is generally more difficult the27 unmodified linesmodified:docs/contrib.md+11 added-1 removed
25 unmodified lines26 | Project | Description | Popularity | Activity |27 |---------------------------------------------------------|--------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------|28 | [Typer](https://github.com/fastapi/typer) | Use Python type hints to create CLI apps. |  |  |29 | [rich-click](https://github.com/ewels/rich-click) | Format help output with Rich. |  |  |30+| [shtab](https://github.com/tqdm/shtab) | Speed up tab completion scripts and support more shells. |  |  |31 | [click-app](https://github.com/simonw/click-app) | Cookiecutter template for creating new CLIs. |  |  |32 | [Cloup](https://github.com/janluke/cloup) | Adds option groups, constraints, command aliases, help themes, suggestions and more. |  |  |33 | [Click Extra](https://github.com/kdeldycke/click-extra) | Cloup + colorful `--help`, `--config`, `--show-params`, `--verbosity` options, etc. |  |  |34 35+## Interactive input libraries36+37+Click 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:38+39+| Project | Description | Popularity | Activity |40+|---------------------------------------------------------------------------|----------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------|41+| [Textual](https://github.com/Textualize/textual) | Build terminal and web user interfaces with a Python API. |  |  |42+| [prompt-toolkit](https://github.com/prompt-toolkit/python-prompt-toolkit) | Build interactive command lines with completion, history and key bindings. |  |  |43+44 ```{note}35-To make it into the list above, a project:45+To make it into any of the lists above, a project:46 47 - 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 linesmodified:docs/exceptions.md+37 added-11 removed
17 unmodified lines18 ## Where are Errors Handled?19 20 Click's main error handling is happening in {meth}`Command.main`. In21 there it handles all subclasses of {exc}`ClickException` as well as the22-standard {exc}`EOFError` and {exc}`KeyboardInterrupt` exceptions. The23-latter are internally translated into an {exc}`Abort`.22+standard {exc}`EOFError` and {exc}`KeyboardInterrupt` exceptions.23 25-The logic applied is the following:24+The table below lists every way a command can end, and what Click does25+for each. The middle column is the default. The last column applies when26+{meth}`Command.main` runs with ``standalone_mode=False``, which the next27+section describes.28 27-1. If an {exc}`EOFError` or {exc}`KeyboardInterrupt` happens, reraise it28- as {exc}`Abort`.29-2. 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`.32-3. If an {exc}`Abort` exception is raised print the string ``Aborted!``33- to standard error and exit the program with exit code ``1``.34-4. 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 |39 40+Click writes the message and exits once that handling is done. An41+interrupt arriving during this last step cannot change the exit code the42+table gave. It can only cost the message.43+44 ## What if I Don't Want That?45 46 Generally you always have the option to invoke the {meth}`Command.invoke`47 method yourself. For instance if you have a {class}`Command` you can20 unmodified lines68 standalone_mode=False,69 )70 ```71 72+This is also how you replace the ``Aborted!`` message. Standalone mode73+turns off every row of the table above, so catch the cases you want to74+keep and write your own message for the rest:75+76+```python77+try:78+ command.main(79+ ["command-name", "args", "go", "here"],80+ standalone_mode=False,81+ )82+except click.Abort:83+ click.echo("Bye!", err=True)84+ raise SystemExit(1)85+except click.ClickException as e:86+ e.show()87+ raise SystemExit(e.exit_code)88+```89+90 ## Which Exceptions Exist?91 92 Click has two exception bases: {exc}`ClickException` which is raised for93 all exceptions that Click wants to signal to the user and {exc}`Abort`69 unmodified linesmodified:docs/faqs.md+167 added
5 unmodified lines6 ```7 8 ## General9 10+### Calling a command as a regular function11+12+I 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:13+14+```pytb15+>>> nasa_date_to_iso("2017-090")16+Usage: cli [OPTIONS] DATESTR17+Try 'cli --help' for help.18+19+Error: Got unexpected extra arguments (0 1 7 - 0 9 0)20+SystemExit: 221+```22+23+#### Answer24+25+This 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.26+27+The recommended pattern is to keep a plain function and wrap it with a thin command:28+29+```python30+def nasa_date_to_iso(datestr): ...31+32+33+@click.command("nasa_date_to_iso")34+@click.argument("datestr")35+def nasa_date_to_iso_command(datestr):36+ click.echo(nasa_date_to_iso(datestr))37+```38+39+The 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.40+41+If 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:42+43+```python44+nasa_date_to_iso_command(["2017-090"], standalone_mode=False)45+```46+47+An alternative form is:48+49+```python50+nasa_date_to_iso_command.main(["2017-090"], standalone_mode=False)51+```52+53 ### Shell Variable Expansion On Windows54 55 I have a simple Click app :56 67 unmodified lines124 | `python -X utf8` | `1` | `utf-8` |125 | `sys.stdout.reconfigure(encoding=…)` | `0` | `utf-8` |126 127 Do 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.128+129+(edit-wait)=130+### The `edit` utility fails to open Visual Studio Code131+132+Let'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.133+134+But 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.135+136+This 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.137+138+#### Answer139+140+Setup your editor to make its launcher block until the window is closed, so Click keeps waiting on it.141+142+You can set the `EDITOR` in your environment with its appropriate flags:143+144+| Editor | Flags |145+|---|---|146+| Visual Studio Code | `EDITOR="code --wait"` |147+| Sublime Text | `EDITOR="subl -w"` |148+149+For 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.150+151+### Tab completion during interactive prompts152+153+A command asks for a file path while it runs:154+155+```python156+import click157+158+159+@click.command()160+def convert():161+ source = click.prompt("File to convert", type=click.Path(exists=True))162+ click.echo(f"Converting {source}")163+```164+165+Pressing {kbd}`Tab` while typing the answer inserts a tab character instead of completing the path:166+167+```console168+$ convert169+File to convert: Doc<TAB>170+Error: Path 'Doc\t' does not exist.171+```172+173+This 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.174+175+{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.176+177+#### Answer178+179+Bind {kbd}`Tab` in `readline` and the prompt completes paths with no other change:180+181+```python182+import readline183+184+if "libedit" in (readline.__doc__ or ""):185+ readline.parse_and_bind("bind ^I rl_complete")186+else:187+ readline.parse_and_bind("tab: complete")188+```189+190+See 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.191+192+Readline 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).193+194+When 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:195+196+```python197+@click.command()198+@click.argument("source", type=click.Path(exists=True))199+def convert(source):200+ click.echo(f"Converting {source}")201+```202+203+The shell completes paths there natively and Click's completion mode takes part in it (as described in [Shell Completion](shell-completion.md)).204+205+(custom-completions-show-the-full-value)=206+### Custom completions show the full value207+208+`Path` and `File` parameters complete differently from a parameter with a custom completer. Take a command with one of each:209+210+```python211+def complete_dirs(ctx, param, incomplete):212+ return [213+ CompletionItem(incomplete + name)214+ for name in ("Documents", "Downloads", "Pictures")215+ ]216+217+218+@click.command()219+@click.option("--src", type=click.Path())220+@click.option("--dest", shell_complete=complete_dirs)221+def copy(src, dest):222+ click.echo(f"Copy from {src} to {dest}")223+```224+225+Completing `--src` shows only the last component of each candidate, and omits the leading path:226+227+```console228+$ copy --src /home/user/<TAB><TAB>229+Documents Downloads Pictures230+```231+232+Completing `--dest` shows each value in full, exactly as the completer returned it:233+234+```console235+$ copy --dest /home/user/<TAB><TAB>236+/home/user/Documents /home/user/Downloads /home/user/Pictures237+```238+239+This is not a bug in Click. The two parameters are completed by different sides.240+241+`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.242+243+A 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.244+245+#### Answer246+247+To change how suggestions are displayed, work on the shell side:248+249+- 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 lines152 * .. autoclass:: Path153 :noindex:154 ```155 156+(type-inference)=157+158+## How Click Infers a Type159+160+When `type` is not given, Click infers it from `default`. Only the defaults listed below161+are recognized. Every other default gives {data}`STRING`.162+163+| `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` |179+180+A `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`.183+184+A `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.187+188+```{eval-rst}189+.. click:example::190+191+ @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__}")196+197+.. click:run::198+199+ invoke(show, args=[])200+```201+202+When `type` is given a callable Click does not recognize, that callable is called on the203+string coming from the command line, and a `ValueError` it raises is reported as a bad204+parameter. A container is rarely useful there, because calling it on a string splits the205+string: `set` turns `"git"` into `{"g", "i", "t"}`. Pass a {class}`ParamType` instead,206+as described in [](#how-to-implement-custom-types).207+208 ## How to Implement Custom Types209 210 To implement a custom type, you need to subclass the {class}`ParamType` class. For simple cases, passing a Python211 function that fails with a `ValueError` is also supported, though discouraged. Override the {meth}`~ParamType.convert`46 unmodified linesmodified:docs/shell-completion.md+2 added
159 unmodified lines160 def cli(ev):161 click.echo(os.environ[ev])162 ```163 164+See {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.165+166 ## Overriding Value Completion167 168 Value completions for a parameter can be customized without a custom type by providing a `shell_complete` function. The169 function is used instead of any completion provided by the type. It is passed 3 positional arguments:108 unmodified linesmodified:docs/utils.md+3 added-3 removed
176 unmodified lines177 click.echo('Invalid input :(')178 ```179 180 Note that this reads raw input, which means that things like arrow keys will show up in the platform's native escape181-format. The only characters translated are `^C` and `^D` which are converted into keyboard interrupts and end of file182-exceptions respectively. This is done because otherwise, it's too easy to forget about that and to create scripts that183-cannot be properly exited.181+format. The only characters translated are the ones produced by {kbd}`Ctrl+C` and {kbd}`Ctrl+D`, or {kbd}`Ctrl+Z` on182+Windows, which are converted into keyboard interrupts and end of file exceptions respectively. This is done because183+otherwise, it's too easy to forget about that and to create scripts that cannot be properly exited.184 185 ## Waiting for Key Press186 187 ```{versionadded} 2.0202 unmodified linesmodified:src/click/_utils.py+9 added
16 unmodified lines17 18 def __repr__(self) -> str:19 return f"{self.__class__.__name__}.{self.name}"20 21+ def __copy__(self) -> Sentinel:22+ return self23 24+ def __deepcopy__(self, memo: dict[int, t.Any]) -> Sentinel:25+ return self26+27+ def __reduce_ex__(self, protocol: object) -> tuple[t.Any, ...]:28+ return getattr, (self.__class__, self.name)29+30+31 UNSET: t.Literal[Sentinel.UNSET] = Sentinel.UNSET32 """Sentinel used to indicate that a value is not set."""33 34 FLAG_NEEDS_VALUE: t.Literal[Sentinel.FLAG_NEEDS_VALUE] = Sentinel.FLAG_NEEDS_VALUE11 unmodified linesmodified:src/click/_winconsole.py-5 removed
43 unmodified lines44 ReadConsoleW = kernel32.ReadConsoleW45 WriteConsoleW = kernel32.WriteConsoleW46 GetConsoleMode = kernel32.GetConsoleMode47 GetLastError = kernel32.GetLastError48-GetCommandLineW = WINFUNCTYPE(LPWSTR)(("GetCommandLineW", windll.kernel32))48 CommandLineToArgvW = WINFUNCTYPE(POINTER(LPWSTR), LPCWSTR, POINTER(c_int))(49 ("CommandLineToArgvW", windll.shell32)50 )51 LocalFree = WINFUNCTYPE(c_void_p, c_void_p)(("LocalFree", windll.kernel32))8 unmodified lines60 ERROR_SUCCESS = 061 ERROR_NOT_ENOUGH_MEMORY = 862 ERROR_OPERATION_ABORTED = 99563 65-STDIN_FILENO = 066-STDOUT_FILENO = 167-STDERR_FILENO = 268-64 EOF = b"\x1a"65 MAX_BYTES_WRITTEN = 3276766 67 if t.TYPE_CHECKING:225 unmodified linesmodified:src/click/core.py+67 added-28 removed
97 unmodified lines98 99 raise RuntimeError(message)100 101 102+def _echo_aborted() -> None:103+ """Write the final abort message to standard error."""104+ echo(_("Aborted!"), file=sys.stderr)105+106+107 def _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 lines1550 1551 # Process shell completion requests and exit early.1552 self._main_shell_completion(extra, prog_name, complete_var)1553 1554+ # 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 = 11562+1563 try:1564 try:1565 with self.make_context(prog_name, args, **extra) as ctx:1566 rv = self.invoke(ctx)6 unmodified lines1573 # 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_code1588+1589+ exit_code = e.exit_code1590+ except Abort:1591+ if not standalone_mode:1592+ raise1593+1594+ report = _echo_aborted1595 except (EOFError, KeyboardInterrupt) as e:1596+ # The blank line closes the terminal's ``^C`` echo.1597 echo(file=sys.stderr)1598+1599+ if not standalone_mode:1565- raise Abort() from e1600+ raise Abort() from e1601+1602+ report = _echo_aborted1603 except ClickException as e:1604 if not standalone_mode:1605 raise1569- e.show()1570- sys.exit(e.exit_code)1606+1607+ 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:1611+1612+ sys.stdout = t.cast(t.TextIO, _PacifyFlushWrapper(sys.stdout))1613+ sys.stderr = t.cast(t.TextIO, _PacifyFlushWrapper(sys.stderr))1614+1615+ if report is not None:1616+ report()1617+1618+ sys.exit(exit_code)1619+ except (EOFError, KeyboardInterrupt):1620 if not standalone_mode:1621 raise1594- echo(_("Aborted!"), file=sys.stderr)1595- sys.exit(1)1622 1623+ sys.exit(exit_code)1624+1625 def _main_shell_completion(1626 self,1627 ctx_args: cabc.MutableMapping[str, t.Any],1628 prog_name: str,1733 unmodified lines3362 action=action,3363 nargs=self.nargs,3364 )3365 3338- 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``.3369 3370+ Unlike :meth:`get_help_record`, the spec is produced even when the3371+ option is :attr:`hidden`.3372+3373+ .. versionadded:: 8.5.13374+ """3375 any_prefix_is_slash = False3376 3377 def _write_opts(opts: cabc.Sequence[str]) -> str:3378 nonlocal any_prefix_is_slash12 unmodified lines3391 3392 if self.secondary_opts:3393 rv.append(_write_opts(self.secondary_opts))3394 3395+ return ("; " if any_prefix_is_slash else " / ").join(rv)3396+3397+ def get_help_record(self, ctx: Context) -> tuple[str, str] | None:3398+ if self.hidden:3399+ return None3400+3401 help = self.help or ""3402 3403 extra = self.get_help_extra(ctx)3404 extra_items = []11 unmodified lines3416 if extra_items:3417 extra_str = "; ".join(extra_items)3418 help = f"{help} [{extra_str}]" if help else f"[{extra_str}]"3419 3381- return ("; " if any_prefix_is_slash else " / ").join(rv), help3420+ return self.get_help_spec(ctx), help3421 3422 def get_help_extra(self, ctx: Context) -> types.OptionHelpExtra:3423 extra: types.OptionHelpExtra = {}3424 414 unmodified linesmodified:src/click/termui.py+10 added
868 unmodified lines869 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.872 873+ .. warning::874+875+ 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.882+883 :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 linesadded:tests/test_exceptions/__init__.py
added:tests/test_exceptions/test_FileError.py+6 added
1+import click2+3+4+def 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
1+import click2+3+4+def 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
1+import datetime2+import uuid3+4+import pytest5+6+import click7+8+9+@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+)25+def test_convert_type_from_container_default(default):26+ """Container defaults are not natively supported and fall back to STRING.27+28+ Refs: https://github.com/pallets/click/issues/303629+ """30+ assert click.types.convert_type(None, default) is click.STRING31+32+33+@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+)40+def 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.43+44+ 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) == expected49+50+51+@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+)78+def test_type_inferred_from_default(default, expected):79+ """Every row of the type-inference table in ``docs/parameter-types.md``.80+81+ Keep the two in step: a change here is a change to documented behavior.82+83+ Refs: https://github.com/pallets/click/issues/303684+ """85+ assert click.types.convert_type(None, default) is expected86+87+88+def test_type_inferred_from_nested_sequence_default():89+ """A sequence of sequences gives a composite ``Tuple`` of the inner types.90+91+ This is the one table row that is not a singleton ``ParamType``.92+93+ 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]98+99+100+def test_explicit_dict_type_rejects_string():101+ """An explicit ``dict`` type cannot convert a plain CLI string at all.102+103+ 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
1+import pytest2+3+import click4+5+6+@pytest.mark.parametrize(7+ "type",8+ [9+ click.File(mode="r"),10+ click.File(mode="r", lazy=True),11+ ],12+)13+def test_file_surrogates(type, tmp_path):14+ """Ensures that the error handling in ``click.File`` is robust.15+16+ ``EILSEQ`` shows up with rootless Podman (FUSE-backed paths) and on filesystems17+ that reject non-UTF-8 names, like ZFS with ``utf8only=on``.18+19+ 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
1+import pytest2+3+import click4+5+6+@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+)16+def test_range(type, value, expect):17+ assert type.convert(value, None, None) == expect18+19+20+@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+)27+def test_range_fail(type, value, expect):28+ with pytest.raises(click.BadParameter) as exc_info:29+ type.convert(value, None, None)30+31+ assert expect in exc_info.value.message32+33+34+def test_float_range_no_clamp_open():35+ with pytest.raises(TypeError):36+ click.FloatRange(0, 1, max_open=True, clamp=True)37+38+ sneaky = click.FloatRange(0, 1, max_open=True)39+ sneaky.clamp = True40+41+ with pytest.raises(RuntimeError):42+ sneaky.convert("1.5", None, None)added:tests/test_types/test_FuncParamType.py+22 added
1+import pytest2+3+import click4+5+6+@pytest.mark.parametrize(7+ ("error_message", "expected"),8+ [9+ ("bad value: nope", "bad value: nope"),10+ ("", "nope"),11+ ],12+)13+def test_func_param_type_uses_value_error_message(error_message, expected):14+ def parse(value):15+ raise ValueError(error_message if error_message else "")16+17+ func_type = click.types.FuncParamType(parse)18+19+ with pytest.raises(click.BadParameter) as exc_info:20+ func_type.convert("nope", None, None)21+22+ assert expected in exc_info.value.messageadded:tests/test_types/test_IntRange.py+38 added
1+import pytest2+3+import click4+5+6+@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+)20+def test_range(type, value, expect):21+ assert type.convert(value, None, None) == expect22+23+24+@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+)34+def test_range_fail(type, value, expect):35+ with pytest.raises(click.BadParameter) as exc_info:36+ type.convert(value, None, None)37+38+ assert expect in exc_info.value.messageadded:tests/test_types/test_ParamType.py+24 added
1+import typing as t2+3+import click4+5+6+def 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)13+14+15+def test_param_type_subclass_omitting_input_parameter():16+ class DoublingType(click.ParamType[int]):17+ name = "doubling"18+19+ def convert(self, value, param, ctx):20+ return int(value) * 221+22+ doubling = DoublingType()23+ assert doubling("21") == 4224+ assert doubling(None) is Noneadded:tests/test_types/test_Path.py+185 added
1+import os2+import pathlib3+import platform4+import subprocess5+import sys6+import tempfile7+8+import pytest9+10+import click11+12+13+def test_path_dash_no_byteswarning():14+ """Detecting the ``-`` dash sentinel must not compare ``bytes`` against15+ ``str``, which raises a ``BytesWarning`` under ``python -bb``.16+17+ 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.stderr34+35+36+def _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")41+42+ try:43+ os.symlink(target, link)44+ return True45+ except OSError:46+ return False47+48+49+@pytest.mark.skipif(50+ not _symlinks_supported(), reason="The current OS or FS doesn't support symlinks."51+)52+def 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("")56+57+ path_type = click.Path(resolve_path=True)58+ param = click.Argument(["a"], type=path_type)59+ ctx = click.Context(click.Command("cli", params=[param]))60+61+ test_dir = tmp_path / "dir"62+ test_dir.mkdir()63+64+ 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_str68+69+ 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_str73+74+75+def _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 False81+82+ f.close()83+ return True84+85+86+@pytest.mark.skipif(87+ not _non_utf8_filenames_supported(),88+ reason="The current OS or FS doesn't support non-UTF-8 filenames.",89+)90+def test_path_surrogates(tmp_path, monkeypatch):91+ monkeypatch.chdir(tmp_path)92+ type = click.Path(exists=True)93+ path = pathlib.Path("\udcff")94+95+ with pytest.raises(click.BadParameter, match="'�' does not exist"):96+ type.convert(path, None, None)97+98+ type = click.Path(file_okay=False)99+ path.touch()100+101+ with pytest.raises(click.BadParameter, match="'�' is a file"):102+ type.convert(path, None, None)103+104+ path.unlink()105+ type = click.Path(dir_okay=False)106+ path.mkdir()107+108+ with pytest.raises(click.BadParameter, match="'�' is a directory"):109+ type.convert(path, None, None)110+111+ path.rmdir()112+113+ 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 False120+121+ path.touch()122+ type = click.Path(readable=True)123+124+ 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)128+129+ type = click.Path(readable=False, writable=True)130+131+ 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)135+136+ type = click.Path(readable=False, executable=True)137+138+ 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)142+143+ path.unlink()144+145+146+def _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 False152+153+ f.close()154+ return True155+156+157+@pytest.mark.skipif(158+ platform.system() == "Windows", reason="Filepath syntax differences."159+)160+def 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)164+165+ assert "my\\ndir" in exc_info.value.message166+167+168+@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+)177+def 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 == expectmodified:tests/test_utils/test_sentinel.py+45 added
1+import copy2+import pickle3 from decimal import Decimal4 from fractions import Fraction5 6+import pytest7+8+import click9+from click._utils import Sentinel10 from click._utils import UNSET11 12 13 def test_unset_sentinel():41 unmodified lines55 assert value != real_value56 assert value is not real_value57 58 assert value not in real_values59+60+61+@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+)71+def test_sentinel_duplication_preserves_identity(sentinel, duplicate):72+ """Sentinels are singletons: copying or pickling one returns the member.73+74+ 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 sentinel79+80+81+@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+)90+def 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 UNSET94+95+ 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 used2+to escape as an unhandled traceback: the message and the exit both ran in3+``except`` clauses, outside every ``try`` that caught ``KeyboardInterrupt``.4+https://github.com/pallets/click/issues/38025+6+The fix holds one policy, the one the pager has followed since7+https://github.com/pallets/click/pull/351: a late interrupt must not replace8+the intended outcome. In standalone mode the collected exit code wins, for9+aborts, errors and success alike, and the message is best effort. Without10+standalone mode the interrupt propagates to the caller. Two settled contracts11+stay in place: the first interrupt reaches a non-standalone caller as12+``Abort`` (https://github.com/pallets/click/pull/2380), and the ``Aborted!``13+message stays as it is (declined in14+https://github.com/pallets/click/issues/1447 and15+https://github.com/pallets/click/issues/2584).16+"""17+18+import sys19+20+import pytest21+22+import click23+24+25+class RecordingStderr:26+ """A stderr stand-in that records what is written to it.27+28+ 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+ """32+33+ def __init__(self, interrupt_at=None):34+ self.text = ""35+ self.interrupt_at = interrupt_at36+ self.isatty_calls = 037+38+ def isatty(self):39+ self.isatty_calls += 140+41+ if self.isatty_calls == self.interrupt_at:42+ raise KeyboardInterrupt43+44+ return False45+46+ def write(self, value):47+ self.text += value48+ return len(value)49+50+ def flush(self):51+ pass52+53+54+def _interrupt_prompt(text):55+ """Stand in for ``input()`` when the user presses Ctrl-C at a prompt."""56+ raise KeyboardInterrupt57+58+59+def _prompting_command():60+ @click.command()61+ @click.option("--name", prompt="Name")62+ def cli(name):63+ click.echo(name)64+65+ return cli66+67+68+def _interrupting_command():69+ @click.command()70+ def cli():71+ raise KeyboardInterrupt72+73+ return cli74+75+76+def _exit_code(cli, stderr, monkeypatch):77+ """Run *cli* in standalone mode and return its exit code."""78+ monkeypatch.setattr(sys, "stderr", stderr)79+80+ try:81+ cli.main([], "cli")82+ except SystemExit as e:83+ return e.code84+ except KeyboardInterrupt:85+ pytest.fail("KeyboardInterrupt escaped Command.main()")86+87+ pytest.fail("Command.main() returned without exiting")88+89+90+@pytest.mark.parametrize(91+ ("source", "interrupt_at"),92+ [("prompt", None), ("prompt", 1), ("body", None), ("body", 1), ("body", 2)],93+)94+def test_interrupt_while_reporting_abort(monkeypatch, source, interrupt_at):95+ """Exit code 1 survives a second Ctrl-C; the message may not.96+97+ 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()108+109+ stderr = RecordingStderr(interrupt_at=interrupt_at)110+111+ assert _exit_code(cli, stderr, monkeypatch) == 1112+113+ if interrupt_at is None:114+ assert "Aborted!" in stderr.text115+116+117+def test_interrupt_while_reporting_error(monkeypatch):118+ """A Ctrl-C while Click writes an error keeps the error's exit code."""119+120+ class InterruptedReport(click.ClickException):121+ exit_code = 3122+123+ def show(self, file=None):124+ raise KeyboardInterrupt125+126+ @click.command()127+ def cli():128+ raise InterruptedReport("boom")129+130+ assert _exit_code(cli, RecordingStderr(), monkeypatch) == 3131+132+133+def test_late_interrupt_with_disabled_standalone_mode(monkeypatch):134+ """Without standalone mode, a late interrupt reaches the caller, not exit 1.135+136+ 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+ """140+141+ class InterruptedAbort(click.Abort):142+ def __init__(self):143+ raise KeyboardInterrupt144+145+ monkeypatch.setattr(click.core, "Abort", InterruptedAbort)146+ cli = _interrupting_command()147+ monkeypatch.setattr(sys, "stderr", RecordingStderr())148+149+ with pytest.raises(KeyboardInterrupt):150+ cli.main([], "cli", standalone_mode=False)151+152+153+def test_interrupt_while_exiting_after_success(monkeypatch):154+ """A Ctrl-C while a successful exit propagates keeps exit code 0.155+156+ 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+ """160+161+ @click.command()162+ def cli():163+ click.echo("done")164+165+ real_exit = sys.exit166+ codes = []167+168+ def interrupted_exit(code=None):169+ codes.append(code)170+171+ if len(codes) == 1:172+ raise KeyboardInterrupt173+174+ real_exit(code)175+176+ monkeypatch.setattr(sys, "exit", interrupted_exit)177+178+ assert _exit_code(cli, RecordingStderr(), monkeypatch) == 0179+ assert codes == [0, 0]modified:tests/test_basic.py+24 added
958 unmodified lines959 960 result = runner.invoke(cli, ["--version"], prog_name="mytool")961 assert result.exit_code == 0962 assert result.output == "mytool 1.0\n"963+964+965+@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+)977+def 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)982+983+ 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 == expectmodified:tests/test_defaults.py+4 added
180 unmodified lines181 ({"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 )191 def test_lookup_default_returns_hides_sentinel(default_map, key, expected):192 """``lookup_default()`` should return ``None`` for missing keys, not :attr:`UNSET`.375 unmodified linesmodified:tests/test_options.py+111 added-7 removed
70 unmodified lines71 ctx = click.Context(click.Command("cli"))72 assert opt.get_help_record(ctx)[1] == expected73 74 75+@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])85+def 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) == expected92+93+ if hidden:94+ assert opt.get_help_record(ctx) is None95+ else:96+ assert opt.get_help_record(ctx)[0] == expected97+98+99 @pytest.mark.parametrize("deprecated", [True, "USE B INSTEAD"])100 def test_deprecated_warning(runner, deprecated):101 @click.command()102 @click.option(350 unmodified lines453 )454 assert not result.exception455 assert result.output == "foo|bar|baz\n"456 457+458+def test_envvar_container_type(runner):459+ """Env vars are plain strings, so a container type splits them character-wise.460+461+ Refs: https://github.com/pallets/click/issues/3036462+ """463+464 @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)))469+470+ result = runner.invoke(cli, [], env={"X": "git"})471+ assert not result.exception472+ assert result.output == "git\n"473+474+ @click.command()475 @click.option("--arg", multiple=True, envvar="X")476 def cmd(arg):477 click.echo("|".join(arg))478 155 unmodified lines634 assert not result.exception635 assert "[default: b]" in result.output636 637 638+def test_show_default_container_defaults(runner):639+ """Container defaults are rendered through ``str()`` in the help output.640+641+ Refs: https://github.com/pallets/click/issues/3036642+ """643+644+ @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+ pass650+651+ 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.output655+656+657 def test_multiple_default_type():658 opt = click.Option(["-a"], multiple=True, default=(1, 2))659 assert opt.nargs == 1660 assert opt.multiple11 unmodified lines672 ctx = click.Context(click.Command("test"))673 assert opt.type_cast_value(ctx, opt.get_default(ctx)) == ((1, "a"),)674 675 676+@pytest.mark.parametrize(677+ "default",678+ [679+ set(),680+ {1, 2},681+ frozenset(),682+ frozenset(["git"]),683+ {},684+ {"a": 1},685+ ],686+)687+def test_type_from_default_container(default):688+ """Container defaults have no native Click type and fall back to STRING.689+690+ 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.692+693+ Refs: https://github.com/pallets/click/issues/3036694+ """695+ opt = click.Option(["-a"], default=default)696+ assert opt.type is click.STRING697+698+699 def 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 lines1507 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.UNPROCESSED1515 1516 1517 @pytest.mark.parametrize(1518 ("opt_params", "args", "expected"),1103 unmodified lines2622 assert result.exit_code == 02623 assert result.output == repr(EngineType.PRO)2624 2625 2539-def 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+)2640+def 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.2645 2646 Reproduces https://github.com/pallets/click/issues/26102647 """2648 1 unmodified line2650 @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)2660 2661 result = runner.invoke(rcli)2558- assert result.stdout == "frozenset({'git'})"2662+ assert result.stdout == default_output2663 assert result.exit_code == 02664 2665 result = runner.invoke(rcli, ["--without-scm-ignore-files"])2562- assert result.stdout == "frozenset()"2666+ assert result.stdout == flag_output2667 assert result.exit_code == 02668 2669 2670 @pytest.mark.parametrize(985 unmodified linesdeleted:tests/test_types.py-332 removed
1-import os.path2-import pathlib3-import platform4-import subprocess5-import sys6-import tempfile7-import typing as t8-9-import pytest10-11-import click12-from click import FileError13-14-15-@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-)34-def test_range(type, value, expect):35- assert type.convert(value, None, None) == expect36-37-38-@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-)50-def test_range_fail(type, value, expect):51- with pytest.raises(click.BadParameter) as exc_info:52- type.convert(value, None, None)53-54- assert expect in exc_info.value.message55-56-57-@pytest.mark.parametrize(58- ("error_message", "expected"),59- [60- ("bad value: nope", "bad value: nope"),61- ("", "nope"),62- ],63-)64-def test_func_param_type_uses_value_error_message(error_message, expected):65- def parse(value):66- raise ValueError(error_message if error_message else "")67-68- func_type = click.types.FuncParamType(parse)69-70- with pytest.raises(click.BadParameter) as exc_info:71- func_type.convert("nope", None, None)72-73- assert expected in exc_info.value.message74-75-76-def test_float_range_no_clamp_open():77- with pytest.raises(TypeError):78- click.FloatRange(0, 1, max_open=True, clamp=True)79-80- sneaky = click.FloatRange(0, 1, max_open=True)81- sneaky.clamp = True82-83- with pytest.raises(RuntimeError):84- sneaky.convert("1.5", None, None)85-86-87-@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-)99-def 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)104-105- 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 == expect109-110-111-@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-)120-def 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 == expect129-130-131-def test_path_dash_no_byteswarning():132- """Detecting the ``-`` dash sentinel must not compare ``bytes`` against133- ``str``, which raises a ``BytesWarning`` under ``python -bb``.134-135- 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.stderr152-153-154-def _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")159-160- try:161- os.symlink(target, link)162- return True163- except OSError:164- return False165-166-167-@pytest.mark.skipif(168- not _symlinks_supported(), reason="The current OS or FS doesn't support symlinks."169-)170-def 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("")174-175- path_type = click.Path(resolve_path=True)176- param = click.Argument(["a"], type=path_type)177- ctx = click.Context(click.Command("cli", params=[param]))178-179- test_dir = tmp_path / "dir"180- test_dir.mkdir()181-182- 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_str186-187- 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_str191-192-193-def _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 False199-200- f.close()201- return True202-203-204-@pytest.mark.skipif(205- not _non_utf8_filenames_supported(),206- reason="The current OS or FS doesn't support non-UTF-8 filenames.",207-)208-def test_path_surrogates(tmp_path, monkeypatch):209- monkeypatch.chdir(tmp_path)210- type = click.Path(exists=True)211- path = pathlib.Path("\udcff")212-213- with pytest.raises(click.BadParameter, match="'�' does not exist"):214- type.convert(path, None, None)215-216- type = click.Path(file_okay=False)217- path.touch()218-219- with pytest.raises(click.BadParameter, match="'�' is a file"):220- type.convert(path, None, None)221-222- path.unlink()223- type = click.Path(dir_okay=False)224- path.mkdir()225-226- with pytest.raises(click.BadParameter, match="'�' is a directory"):227- type.convert(path, None, None)228-229- path.rmdir()230-231- 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 False238-239- path.touch()240- type = click.Path(readable=True)241-242- 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)246-247- type = click.Path(readable=False, writable=True)248-249- 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)253-254- type = click.Path(readable=False, executable=True)255-256- 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)260-261- path.unlink()262-263-264-@pytest.mark.parametrize(265- "type",266- [267- click.File(mode="r"),268- click.File(mode="r", lazy=True),269- ],270-)271-def test_file_surrogates(type, tmp_path):272- """Ensures that the error handling in ``click.File`` is robust.273-274- ``EILSEQ`` shows up with rootless Podman (FUSE-backed paths) and on filesystems275- that reject non-UTF-8 names, like ZFS with ``utf8only=on``.276-277- 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)290-291-292-def test_file_error_surrogates():293- message = FileError(filename="\udcff").format_message()294- assert message == "Could not open file '�': unknown error"295-296-297-@pytest.mark.skipif(298- platform.system() == "Windows", reason="Filepath syntax differences."299-)300-def 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)304-305- assert "my\\ndir" in exc_info.value.message306-307-308-def 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'."312-313-314-def 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)321-322-323-def test_param_type_subclass_omitting_input_parameter():324- class DoublingType(click.ParamType[int]):325- name = "doubling"326-327- def convert(self, value, param, ctx):328- return int(value) * 2329-330- doubling = DoublingType()331- assert doubling("21") == 42332- assert doubling(None) is Nonemodified:CHANGES.md+10 added
1 ## Version 8.5.12 3 Unreleased4 5+- 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`14+15 ## Version 8.5.016 17 Released 2026-08-2418 1654 unmodified lines