Skip to content
Myr

Merge Main into Stable (#3442)

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

authored by Rowlando13 · committed by GitHub · parents d5fbd32, e3e69e3 · Browse files · 39 files+3408 added−531 removed
This commit

State

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

Diff stats

39 files+3408 added−531 removed

  • tests:+2070 added−51 removed
  • other:+1338 added−480 removed

39 files+3408 added−531 removed

modified:docs/api.md+4 added
71 unmodified lines
72.. autofunction:: echo_via_pager73```7475```{eval-rst}76.. autofunction:: get_pager_file77```7879```{eval-rst}80.. autofunction:: prompt81```8283```{eval-rst}
274 unmodified lines
modified:docs/commands.md+29 added
349 unmodified lines
350 }351 })352```353354### Multi-value parameters355356When a `default_map` value is a string for a parameter with `nargs > 1` or a357{class}`Tuple` type, the string is split automatically, the same way an358environment variable would be. By default, values are split on whitespace. See359[Multiple Options from Environment360Values](options.md#multiple-options-from-environment-values) for details on361splitting behavior.362363```python364default_map = {365 "draw": {366 "point": "3 4", # split into ("3", "4") for nargs=2367 "color": "red", # passed as-is for nargs=1368 }369}370```371372You can also pass an already-structured tuple or list, which will be used as-is373without splitting:374375```python376default_map = {377 "draw": {378 "point": (3, 4), # used directly379 }380}381```382383## Context Defaults384385```{versionadded} 2.0386```
81 unmodified lines
modified:docs/conf.py+1 added
29 unmodified lines
30}31intersphinx_mapping = {32 "python": ("https://docs.python.org/3/", None),33}34myst_heading_anchors = 33536# HTML -----------------------------------------------------------------3738html_theme = "click"
20 unmodified lines
modified:docs/options.md+162 added-4 removed
228 unmodified lines
229230 invoke(commit, args=['-m', 'foo', '-m', 'bar', '-m', 'here'])231```232233## Combining short options234235Short options made of a single character can be combined into one argument: `-abc` is equivalent to `-a -b -c`. This is the standard POSIX behavior for short option stacking, and it is the reason a repeated flag like `-vvv` works with the [Counting](#counting) feature.236237```{eval-rst}238.. click:example::239240 @click.command()241 @click.option('-a', is_flag=True)242 @click.option('-b', is_flag=True)243 @click.option('-c', is_flag=True)244 def cli(a, b, c):245 click.echo(f"a={a} b={b} c={c}")246247.. click:run::248249 invoke(cli, args=['-a', '-b', '-c'])250 invoke(cli, args=['-abc'])251```252253If the last option in the combination takes a value, the value can either follow as the next argument or be attached directly:254255```{eval-rst}256.. click:example::257258 @click.command()259 @click.option('-v', is_flag=True)260 @click.option('-n', type=int)261 def cli(v, n):262 click.echo(f"v={v} n={n}")263264.. click:run::265266 invoke(cli, args=['-v', '-n', '5'])267 invoke(cli, args=['-vn', '5'])268 invoke(cli, args=['-vn5'])269```270271```{note}272Multi-character short option names are not supported. An argument like `-dbg` is interpreted as the combination of `-d`, `-b`, and `-g`, so Click reports `No such option: -d` if `-d` is not declared. For longer option names, use a long option with the `--` prefix (like `--debug`).273```274275## Counting276277To count the occurrence of an option, set `count=True`. If the option is not278passed on the command line, then the count is 0. Counting is commonly used for
231 unmodified lines
510```511512#### Feature switch groups (multiple flags sharing one variable)513472When multiple `flag_value` options target the same parameter473name, `default=True` on one of them marks it as the default474choice.514Several `flag_value` options can target the same parameter name to form a515feature switch group. The user picks one flag on the command line, and the516function receives the corresponding `flag_value`. When the user picks none,517Click falls back to whichever option claims the slot under the arbitration518rules described below.519520##### Non-boolean groups521522For non-boolean `flag_value` (strings, enum members, classes, ...), place523`default=True` on the option that should win when no flag is passed. The524substitution rule above resolves it to that option's `flag_value`. Any other525explicit `default` is passed through literally.526527| Definition | Not passed | `--upper` | `--lower` |528|--------------------------------------------------------|------------|-----------|-----------|529| `--upper` with `flag_value='upper'`, `default=True` | `"upper"` | `"upper"` | `"lower"` |530| `--upper` with `flag_value='upper'`, `default='upper'` | `"upper"` | `"upper"` | `"lower"` |480| Both without `default` | `None` | `"upper"` | `"lower"` |531| `--upper` with `flag_value='upper'`, `default=None` | `None` | `"upper"` | `"lower"` |532| Neither option carries a `default` | `None` | `"upper"` | `"lower"` |533534The third row is the three-state pattern: the function receives `None` when no535flag is passed, distinguishable from either explicit choice.536537##### Boolean groups538539When `flag_value` is `True` or `False`, the substitution rule does not apply:540`default=True` is the literal Python `True`. To make one flag in an541enable/disable pair the default, set its `default=True` explicitly:542543```python544@click.option("--without-xyz", "enable_xyz", flag_value=False)545@click.option("--with-xyz", "enable_xyz", flag_value=True, default=True)546```547548| Definition | Not passed | `--with-xyz` | `--without-xyz` |549|---------------------------------------------------------|------------|--------------|-----------------|550| `--with-xyz` with `flag_value=True`, `default=True` | `True` | `True` | `False` |551| `--without-xyz` with `flag_value=False`, `default=False`| `False` | `True` | `False` |552| `--with-xyz` with `flag_value=True`, `default=None` | `None` | `True` | `False` |553| Neither option carries a `default` | `False` | `True` | `False` |554555```{tip}556For most enable/disable cases, the pair form `--with-xyz/--without-xyz` is557shorter and equivalent. The multi-flag group form is useful when the on and off558flags need distinct names without a shared stem, or when each flag needs its559own help text.560```561562##### Arbitration rules563564When several options in a group resolve their values simultaneously, only one565wins the parameter slot. The full arbitration policy (source precedence,566explicit-beats-auto tie-break, first-declared fallback) is enumerated under567[Option value resolution](#option-value-resolution).568569## Option value resolution570571This section enumerates the rules Click applies when computing the value572delivered to the decorated function for every option. Rules are listed in the573order they fire during the parsing pipeline.574575### Type inference576577Without an explicit `type=`, Click infers the parameter type at construction:5785791. If `flag_value` is `True` or `False`, the type is {class}`BoolParamType`.5802. If `flag_value` is an `int`, `float`, or `str`, the type is the matching581 basic type.5823. If `flag_value` is any other Python object (a class, an enum member, a583 `frozenset`, ...), the type is {data}`UNPROCESSED` so the value passes584 through unchanged.5854. Otherwise, the type is inferred from `default` if set, falling back to586 {class}`StringParamType` when neither hint is available.587588### `default` interpretation589590The literal value passed as `default=` is interpreted differently depending on591whether the option is a flag and what `flag_value` it carries:5925931. `default=UNSET` (the absence sentinel) is treated as if `default` was not594 passed at all. It does not count as "the user picked nothing", and it does595 not count as an explicit default for arbitration purposes.5962. For a bare boolean flag (no `flag_value`, or `flag_value` of `True` or597 `False`), an unset `default` auto-derives to `False`.5983. For a non-boolean flag with a `flag_value`, `default=True` is substituted599 with `flag_value`. This is the "activate this flag by default" shorthand.600 Any non-`True` `default` is passed through literally.6014. For a boolean flag with `flag_value` set, `default=True` is the literal602 Python `True`. The substitution from rule 3 does not apply.6035. `default=None` is always a real explicit value, distinct from `UNSET`604 absence.6056. Any other `default` is delivered to the function unchanged after conversion606 through the parameter's type.607608### Value sources609610Click resolves the value of every option from the following611sources, in order of decreasing precedence:6126131. **command line input** ({attr}`ParameterSource.COMMANDLINE`),6142. **environment variable** named in `envvar=` or derived from `auto_envvar_prefix`615 ({attr}`ParameterSource.ENVIRONMENT`),6163. **`default_map` entry** matching the parameter name on the active {class}`Context`617 ({attr}`ParameterSource.DEFAULT_MAP`),6184. **parameter default** ({attr}`ParameterSource.DEFAULT`).619620The first source that produces a value wins. Environment variables and621`default_map` entries set to `Sentinel.UNSET` are skipped, so they fall through622to the next source rather than supplying `UNSET` to the function.623624### Slot arbitration625626Several options can target the same `name` to form a feature switch group. When627they do, only one option's value reaches the function. Arbitration applies628these rules, in order:6296301. **By source.** Whichever option resolved its value from the most explicit631 source wins, regardless of decorator order. Any command-line input beats any632 default, an environment variable beats a `default_map` entry, and so on.6332. **Within the default tier, explicit beats auto-derived.** An option that634 received an explicit `default=` keyword wins over one whose default came635 from `default` interpretation.6363. **Otherwise, last declared wins.** When all options in the group resolved637 from the same source and tier (all auto-derived defaults, or all explicit638 defaults), the option declared last in the source code keeps the slot.639640## Values from Environment Variables641642To pass in a value from a specific environment variable use `envvar`.643
151 unmodified lines
modified:docs/parameter-types.md+21 added-2 removed
modified:docs/shell-completion.md+1 added-1 removed
118 unmodified lines
119120In this example, the type will suggest environment variables that start with the incomplete value.121122```python123class EnvVarType(ParamType):123class EnvVarType(ParamType[str]):124 name = "envvar"125126 def shell_complete(self, ctx, param, incomplete):127 return [
122 unmodified lines
modified:docs/support-multiple-versions.md+1 added-1 removed
53 unmodified lines
5455Here's an example ``ParamType`` subclass which uses this:5657```python58class CommaDelimitedString(click.ParamType):58class CommaDelimitedString(click.ParamType[str]):59 @add_ctx_arg60 def get_metavar(self, param: click.Parameter, ctx: click.Context | None) -> str:61 return "TEXT,TEXT,..."62```
modified:docs/testing.md+50 added-38 removed
202 unmodified lines
203Prompts will be emulated so they write the input data to204the output stream as well. If hidden input is expected then this205does not happen.206207## File Descriptors and Low-Level I/O207## Capture modes208209{class}`CliRunner` captures output by replacing210`sys.stdout` and `sys.stderr` with in-memory211{class}`~io.BytesIO`-backed wrappers. This is212Python-level redirection: calls to {func}`~click.echo`,213{func}`print`, or `sys.stdout.write()` are captured, but214the wrappers have no OS-level file descriptor.209{class}`CliRunner` captures output by replacing `sys.stdout` and `sys.stderr`210with in-memory wrappers. The `capture` parameter controls which strategy is211used.212216Code that calls `fileno()` on `sys.stdout` or217`sys.stderr`, like {mod}`faulthandler`,218{mod}`subprocess`, or C extensions, would normally crash219with {exc}`io.UnsupportedOperation` inside220{class}`CliRunner`.213### `capture="sys"` (default)214222To avoid this, {class}`CliRunner` preserves the original223stream's file descriptor and exposes it via `fileno()` on224the replacement wrapper.215Captures Python-level writes (`print()`, `click.echo()`, `sys.stdout.write()`).216It is fast and sufficient for most Click applications.217226This means:227- **Python-level writes** (`print()`, `click.echo()`,228 ...) are captured as usual.229- **fd-level writes** (C code writing directly to the230 file descriptor) go to the original terminal and are231 **not** captured.218Code that holds a reference to the original `sys.stdout` (like a library that219does `from sys import stdout` at import time) bypasses the capture and its220output is lost.221233This is the same trade-off that234[pytest](https://docs.pytest.org/en/stable/how-to/capture-stdout-stderr.html)235makes with its two capture modes:222In this mode `sys.stdout.fileno()` and `sys.stderr.fileno()` raise223{exc}`io.UnsupportedOperation`, matching the pre-`8.3.3` behavior. C-level224consumers ({mod}`faulthandler`, {mod}`subprocess`, C extensions) that expect a225real file descriptor must opt into the `capture="fd"` mode.226237- `capsys`, which captures Python-level output, where238 `fileno()` raises `UnsupportedOperation` and fd-level239 writes are not captured.240- `capfd`, which captures fd-level output via241 `os.dup2()`, where `fileno()` works and fd-level242 writes *are* captured.227### `capture="fd"`228244Rather than implementing a full `capfd`-style mechanism,245{class}`CliRunner` takes the simpler path: expose the246original `fd` so that standard library helpers keep247working, while accepting that their output is not248captured.229Redirects OS file descriptors `1` and `2` to a temporary file via230{func}`os.dup2`, inspired by [Pytest's231`capfd`](https://docs.pytest.org/en/stable/how-to/capture-stdout-stderr.html).232This catches output that bypasses `sys.stdout`, including:233250```{versionchanged} 8.3.3251`fileno()` on the redirected streams now returns the252original stream's file descriptor instead of raising.234- Stale references to the original `sys.stdout` and `sys.stderr`.235- Logging frameworks that cache the original stream (like `structlog` or the236 stdlib's `logging` module).237- C extensions and subprocesses that write directly to `fd 1` or `fd 2`.238239```python240from click.testing import CliRunner241from myapp import cli242243244def test_captures_everything():245 runner = CliRunner(capture="fd")246 result = runner.invoke(cli)247 # result.stdout contains both Python-level and fd-level output248 assert "expected output" in result.stdout249```250251In this mode `sys.stdout.fileno()` returns the saved (pre-redirection) `fd`, so252{mod}`faulthandler` and similar consumers keep working. Writes to `fd 1` and253`fd 2` land in the capture tmpfile, so `os.dup2()` calls inside the CLI no254longer leak into the host runner's stdout.255256```{note}257`capture="fd"` is not available on Windows.258```259260```{versionchanged} 8.4.0261Added the `capture` parameter. The default `sys` mode no longer exposes the262original `fd` through `fileno()`, reverting the change introduced in `8.3.3`263that broke Pytest's `fd`-level capture teardown. Use `capture="fd"` to restore264that behavior with proper isolation.265```
modified:docs/utils.md+13 added
108 unmodified lines
109 def less():110 click.echo_via_pager(_generate_output())111```112113For more complex programs, which can't easily use a simple generator, you114can get access to a writable file-like object for the pager, and write to115that instead:116117```{eval-rst}118.. click:example::119 @click.command()120 def less():121 with click.get_pager_file() as pager:122 for idx in range(50000):123 print(idx, file=pager)124```125126## Screen Clearing127128```{versionadded} 2.0129```
276 unmodified lines
modified:examples/validation/validation.py+2 added-2 removed
7 unmodified lines
8 raise click.BadParameter("Should be a positive, even integer.")9 return value101112class URL(click.ParamType):12class URL(click.ParamType[urlparse.ParseResult]):13 name = "url"1415 def convert(self, value, param, ctx):15 def convert(self, value, param, ctx) -> urlparse.ParseResult:16 if not isinstance(value, tuple):17 value = urlparse.urlparse(value)18 if value.scheme not in ("http", "https"):19 self.fail(
29 unmodified lines
modified:src/click/__init__.py+2 added
31 unmodified lines
32from .exceptions import BadParameter as BadParameter33from .exceptions import ClickException as ClickException34from .exceptions import FileError as FileError35from .exceptions import MissingParameter as MissingParameter36from .exceptions import NoSuchCommand as NoSuchCommand37from .exceptions import NoSuchOption as NoSuchOption38from .exceptions import UsageError as UsageError39from .formatting import HelpFormatter as HelpFormatter40from .formatting import wrap_text as wrap_text
1 unmodified line
42from .termui import clear as clear43from .termui import confirm as confirm44from .termui import echo_via_pager as echo_via_pager45from .termui import edit as edit46from .termui import get_pager_file as get_pager_file47from .termui import getchar as getchar48from .termui import launch as launch49from .termui import pause as pause50from .termui import progressbar as progressbar
76 unmodified lines
modified:src/click/_compat.py+4 added
500 unmodified lines
501) -> bool:502 if color is None:503 if stream is None:504 stream = sys.stdin505 elif hasattr(stream, "color"):506 # ._termui_impl.MaybeStripAnsi handles stripping ansi itself,507 # so we don't need to strip it here508 return False509 return not isatty(stream) and not _is_jupyter_kernel_output(stream)510 return not color511512
114 unmodified lines
modified:src/click/_termui_impl.py+118 added-79 removed
6 unmodified lines
7from __future__ import annotations89import collections.abc as cabc10import contextlib11import io12import math13import os14import shlex15import sys
7 unmodified lines
23from ._compat import _default_text_stdout24from ._compat import CYGWIN25from ._compat import get_best_encoding26from ._compat import isatty26from ._compat import open_stream27from ._compat import strip_ansi28from ._compat import term_len29from ._compat import WIN30from .exceptions import ClickException31from .utils import echo3233V = t.TypeVar("V")343536class _BufferedTextPagerStream(t.Protocol):37 buffer: t.BinaryIO383940def _has_binary_buffer(41 stream: t.BinaryIO | t.TextIO,42) -> t.TypeGuard[_BufferedTextPagerStream]:43 # TextIO is wider than TextIOWrapper; text-only streams such as StringIO44 # are valid TextIO values but do not expose a binary buffer to wrap.45 return getattr(stream, "buffer", None) is not None464748if os.name == "nt":49 BEFORE_BAR = "\r"50 AFTER_BAR = "\n"51else:
133 unmodified lines
185 t //= 60186 hours = t % 24187 t //= 24188 if t > 0:176 return f"{t}d {hours:02}:{minutes:02}:{seconds:02}"189 return "{d}{day_label} {h:02}:{m:02}:{s:02}".format(190 d=t,191 day_label=_("d"),192 h=hours,193 m=minutes,194 s=seconds,195 )196 else:197 return f"{hours:02}:{minutes:02}:{seconds:02}"198 return ""199
184 unmodified lines
384 self.finish()385 self.render_progress()386387369def pager(generator: cabc.Iterable[str], color: bool | None = None) -> None:388class MaybeStripAnsi(io.TextIOWrapper):389 def __init__(self, stream: t.IO[bytes], *, color: bool, **kwargs: t.Any):390 super().__init__(stream, **kwargs)391 self.color = color392393 def write(self, text: str) -> int:394 if not self.color:395 text = strip_ansi(text)396 return super().write(text)397398399def _pager_contextmanager(400 color: bool | None = None,401) -> t.ContextManager[tuple[t.BinaryIO | t.TextIO, str, bool]]:402 """Decide what method to use for paging through text."""403 stdout = _default_text_stdout()404405 # There are no standard streams attached to write to. For example,
1 unmodified line
407 if stdout is None:408 stdout = StringIO()409410 if not isatty(sys.stdin) or not isatty(stdout):379 return _nullpager(stdout, generator, color)411 return _nullpager(stdout, color)412413 # Split using POSIX mode (the default) so that quote characters are414 # stripped from tokens and quoted Windows paths are preserved.415 # Non-POSIX mode retains quotes in tokens, and wrapping tokens416 # with shlex.quote re-introduces quoting issues on Windows.417 pager_cmd_parts = shlex.split(os.environ.get("PAGER", ""))418 if pager_cmd_parts:419 if WIN:388 if _tempfilepager(generator, pager_cmd_parts, color):389 return390 elif _pipepager(generator, pager_cmd_parts, color):391 return420 return _tempfilepager(pager_cmd_parts, color)421 return _pipepager(pager_cmd_parts, color)422423 if os.environ.get("TERM") in ("dumb", "emacs"):394 return _nullpager(stdout, generator, color)395 if (WIN or sys.platform.startswith("os2")) and _tempfilepager(396 generator, ["more"], color397 ):398 return399 if _pipepager(generator, ["less"], color):400 return424 return _nullpager(stdout, color)425 if WIN or sys.platform.startswith("os2"):426 return _tempfilepager(["more"], color)427 return _pipepager(["less"], color)428402 import tempfile429404 fd, filename = tempfile.mkstemp()405 os.close(fd)406 try:407 if _pipepager(generator, ["more"], color):408 return409 return _nullpager(stdout, generator, color)410 finally:411 os.unlink(filename)430@contextlib.contextmanager431def get_pager_file(color: bool | None = None) -> t.Generator[t.TextIO, None, None]:432 """Context manager.433 Yields a writable file-like object which can be used as an output pager.434 .. versionadded:: 8.4435 :param color: controls if the pager supports ANSI colors or not. The436 default is autodetection.437 """438 with _pager_contextmanager(color=color) as (stream, encoding, color):439 # Split streams by capabilities rather than the abstract TextIO /440 # BinaryIO annotations: buffered text streams can be unwrapped to bytes,441 # while text-only streams are yielded as-is.442 if _has_binary_buffer(stream):443 # Text stream backed by a binary buffer.444 stream = MaybeStripAnsi(stream.buffer, color=color, encoding=encoding)445 elif isinstance(stream, t.BinaryIO):446 # Binary stream447 stream = MaybeStripAnsi(stream, color=color, encoding=encoding)448 try:449 yield stream450 finally:451 stream.flush()452453454@contextlib.contextmanager455def _pipepager(415 generator: cabc.Iterable[str], cmd_parts: list[str], color: bool | None416) -> bool:456 cmd_parts: list[str], color: bool | None = None457) -> t.Iterator[tuple[t.BinaryIO | t.TextIO, str, bool]]:458 """Page through text by feeding it to another program.459460 Invokes the pager via :class:`subprocess.Popen` with an ``argv`` list461 produced by :func:`shlex.split`. The command is resolved to an absolute
2 unmodified lines
464465 Invoking a pager through this might support colors: if piping to466 ``less`` and the user hasn't decided on colors, ``LESS=-R`` is set467 automatically.427428 Returns ``True`` if the command was found and executed, ``False``429 otherwise so another pager can be attempted.468 """469 # Split the command into the invoked CLI and its parameters.470 if not cmd_parts:471 stdout = _default_text_stdout() or StringIO()472 yield stdout, "utf-8", False433 return False473 return474475 import shutil476477 cmd = cmd_parts[0]478 cmd_params = cmd_parts[1:]479480 cmd_filepath = shutil.which(cmd)481 if not cmd_filepath:482 stdout = _default_text_stdout() or StringIO()483 yield stdout, "utf-8", False442 return False484 return485486 # Produces a normalized absolute path string.487 # multi-call binaries such as busybox derive their identity from the symlink488 # less -> busybox. resolve() causes them to misbehave. (eg. less becomes busybox)
14 unmodified lines
503 color = True504 elif "r" in less_flags or "R" in less_flags:505 color = True506507 if color is None:508 color = False509510 c = subprocess.Popen(511 [str(cmd_path)] + cmd_params,512 shell=False,513 stdin=subprocess.PIPE,514 env=env,515 errors="replace",516 text=True,517 )473 assert c.stdin is not None518 stdin = t.cast(t.BinaryIO, c.stdin)519 encoding = get_best_encoding(stdin)520 try:475 for text in generator:476 if not color:477 text = strip_ansi(text)478479 c.stdin.write(text)521 yield stdin, encoding, color522 except BrokenPipeError:523 # In case the pager exited unexpectedly, ignore the broken pipe error.524 pass525 except Exception as e:
5 unmodified lines
531 raise e532 finally:533 # We must close stdin and wait for the pager to exit before we continue534 try:493 c.stdin.close()535 stdin.close()536 # Close implies flush, so it might throw a BrokenPipeError if the pager537 # process exited already.538 except BrokenPipeError:539 pass
13 unmodified lines
553 pass554 else:555 break556515 return True557517558@contextlib.contextmanager559def _tempfilepager(519 generator: cabc.Iterable[str], cmd_parts: list[str], color: bool | None520) -> bool:560 cmd_parts: list[str], color: bool | None = None561) -> t.Iterator[tuple[t.BinaryIO | t.TextIO, str, bool]]:562 """Page through text by invoking a program on a temporary file.563564 Used as the primary pager strategy on Windows (where piping to565 ``more`` adds spurious ``\\r\\n``), and as a fallback on other566 platforms. The command is resolved to an absolute path with567 :func:`shutil.which`.527528 Returns ``True`` if the command was found and executed, ``False``529 otherwise so another pager can be attempted.568 """569 # Split the command into the invoked CLI and its parameters.570 if not cmd_parts:571 stdout = _default_text_stdout() or StringIO()572 yield stdout, "utf-8", False533 return False573 return574575 import shutil576 import subprocess577578 cmd = cmd_parts[0]579580 cmd_filepath = shutil.which(cmd)581 if not cmd_filepath:582 stdout = _default_text_stdout() or StringIO()583 yield stdout, "utf-8", False541 return False584 return585586 # Produces a normalized absolute path string.587 # multi-call binaries such as busybox derive their identity from the symlink588 # less -> busybox. resolve() causes them to misbehave. (eg. less becomes busybox)589 cmd_path = Path(cmd_filepath).absolute()590547 import subprocess591 import tempfile592550 fd, filename = tempfile.mkstemp()551 # TODO: This never terminates if the passed generator never terminates.552 text = "".join(generator)553 if not color:554 text = strip_ansi(text)593 encoding = get_best_encoding(sys.stdout)556 with open_stream(filename, "wb")[0] as f:557 f.write(text.encode(encoding))594 if color is None:595 color = False596 # On Windows, NamedTemporaryFile cannot be opened by another process597 # while Python still has it open, so we use delete=False and clean up manually598 # rather than using a contextmanager here.599 f = tempfile.NamedTemporaryFile(mode="wb", delete=False)600 try:559 subprocess.call([str(cmd_path), filename])560 except OSError:561 # Command not found562 pass601 yield t.cast(t.BinaryIO, f), encoding, color602 f.flush()603 f.close()604 subprocess.call([str(cmd_path), f.name])605 finally:564 os.close(fd)565 os.unlink(filename)606 os.unlink(f.name)607567 return True608569609@contextlib.contextmanager610def _nullpager(571 stream: t.TextIO, generator: cabc.Iterable[str], color: bool | None572) -> None:611 stream: t.TextIO, color: bool | None = None612) -> t.Iterator[tuple[t.TextIO, str, bool]]:613 """Simply print unformatted text. This is the ultimate fallback."""574 for text in generator:575 if not color:576 text = strip_ansi(text)577 stream.write(text)614 encoding = get_best_encoding(stream)615 if color is None:616 color = False617 yield stream, encoding, color618619620class Editor:621 def __init__(
137 unmodified lines
759 elif WIN:760 if locate:761 url = _unquote_file(url)762 args = ["explorer", f"/select,{url}"]763 try:764 return subprocess.call(args)765 except OSError:766 return 127767 else:724 args = ["start"]725 if wait:726 args.append("/WAIT")727 args.append("")728 args.append(url)729 try:730 return subprocess.call(args)731 except OSError:732 # Command not found733 return 127768 try:769 os.startfile(url) # type: ignore[attr-defined]770 except OSError:771 return 127772 return 0773 elif CYGWIN:774 if locate:775 url = _unquote_file(url)776 args = ["cygstart", os.path.dirname(url)]
133 unmodified lines
modified:src/click/_textwrap.py+139 added-2 removed
2 unmodified lines
3import collections.abc as cabc4import textwrap5from contextlib import contextmanager67from ._compat import _ansi_re8from ._compat import term_len91011def _truncate_visible(text: str, n: int) -> str:12 """Return the longest prefix of ``text`` containing at most ``n`` visible13 characters.1415 ANSI escape sequences inside the prefix are kept intact and do not count16 toward the visible width. A cut is never placed inside an escape sequence.17 """18 if n <= 0:19 return ""2021 visible = 022 i = 023 cut = 024 end = len(text)25 while i < end:26 m = _ansi_re.match(text, i)27 if m is not None:28 i = m.end()29 continue30 visible += 131 i += 132 cut = i33 if visible >= n:34 break35 return text[:cut]363738class TextWrapper(textwrap.TextWrapper):39 """``textwrap.TextWrapper`` variant that measures widths by visible40 character count.4142 ANSI escape sequences embedded in chunks, indents, or the placeholder are43 excluded from the width budget. Without this, styled help text (a styled44 ``Usage:`` prefix, a colorized option name, ...) would be wrapped earlier45 than its visible length warrants and tokens would split mid-word.46 """4748 def _handle_long_word(49 self,50 reversed_chunks: list[str],51 cur_line: list[str],
3 unmodified lines
55 space_left = max(width - cur_len, 1)5657 if self.break_long_words:58 last = reversed_chunks[-1]20 cut = last[:space_left]21 res = last[space_left:]59 cut = _truncate_visible(last, space_left)60 res = last[len(cut) :]61 cur_line.append(cut)62 reversed_chunks[-1] = res63 elif not cur_line:64 cur_line.append(reversed_chunks.pop())6566 def _wrap_chunks(self, chunks: list[str]) -> list[str]:67 """Wrap chunks counting widths in visible characters.6869 Mirrors the algorithm of :meth:`textwrap.TextWrapper._wrap_chunks`70 with every width measurement routed through71 :func:`click._compat.term_len` instead of :func:`len`, so ANSI escape72 bytes in chunks, indents, or the placeholder do not inflate the count.7374 .. seealso::75 :class:`textwrap.TextWrapper` in the Python standard library documentation:76 https://docs.python.org/3/library/textwrap.html#textwrap.TextWrapper7778 Reference implementation in CPython:79 https://github.com/python/cpython/blob/main/Lib/textwrap.py80 """81 lines: list[str] = []82 if self.width <= 0:83 raise ValueError(f"invalid width {self.width!r} (must be > 0)")84 if self.max_lines is not None:85 if self.max_lines > 1:86 indent = self.subsequent_indent87 else:88 indent = self.initial_indent89 if term_len(indent) + term_len(self.placeholder.lstrip()) > self.width:90 raise ValueError("placeholder too large for max width")9192 chunks.reverse()9394 while chunks:95 cur_line: list[str] = []96 cur_len = 09798 if lines:99 indent = self.subsequent_indent100 else:101 indent = self.initial_indent102103 width = self.width - term_len(indent)104105 if self.drop_whitespace and chunks[-1].strip() == "" and lines:106 del chunks[-1]107108 while chunks:109 n = term_len(chunks[-1])110111 if cur_len + n <= width:112 cur_line.append(chunks.pop())113 cur_len += n114115 else:116 break117118 if chunks and term_len(chunks[-1]) > width:119 self._handle_long_word(chunks, cur_line, cur_len, width)120 cur_len = sum(map(term_len, cur_line))121122 if self.drop_whitespace and cur_line and cur_line[-1].strip() == "":123 cur_len -= term_len(cur_line[-1])124 del cur_line[-1]125126 if cur_line:127 if (128 self.max_lines is None129 or len(lines) + 1 < self.max_lines130 or (131 not chunks132 or self.drop_whitespace133 and len(chunks) == 1134 and not chunks[0].strip()135 )136 and cur_len <= width137 ):138 lines.append(indent + "".join(cur_line))139 else:140 while cur_line:141 if (142 cur_line[-1].strip()143 and cur_len + term_len(self.placeholder) <= width144 ):145 cur_line.append(self.placeholder)146 lines.append(indent + "".join(cur_line))147 break148 cur_len -= term_len(cur_line[-1])149 del cur_line[-1]150 else:151 if lines:152 prev_line = lines[-1].rstrip()153 if (154 term_len(prev_line) + term_len(self.placeholder)155 <= self.width156 ):157 lines[-1] = prev_line + self.placeholder158 break159 lines.append(indent + self.placeholder.lstrip())160 break161162 return lines163164 @contextmanager165 def extra_indent(self, indent: str) -> cabc.Iterator[None]:166 old_initial_indent = self.initial_indent167 old_subsequent_indent = self.subsequent_indent
21 unmodified lines
modified:src/click/_utils.py+4 added-4 removed
17 unmodified lines
18 def __repr__(self) -> str:19 return f"{self.__class__.__name__}.{self.name}"202122UNSET = Sentinel.UNSET22UNSET: t.Literal[Sentinel.UNSET] = Sentinel.UNSET23"""Sentinel used to indicate that a value is not set."""2425FLAG_NEEDS_VALUE = Sentinel.FLAG_NEEDS_VALUE25FLAG_NEEDS_VALUE: t.Literal[Sentinel.FLAG_NEEDS_VALUE] = Sentinel.FLAG_NEEDS_VALUE26"""Sentinel used to indicate an option was passed as a flag without a27value but is not a flag option.2829``Option.consume_value`` uses this to prompt or use the ``flag_value``.30"""3132T_UNSET = t.Literal[UNSET] # type: ignore[valid-type]32T_UNSET: t.TypeAlias = t.Literal[Sentinel.UNSET]33"""Type hint for the :data:`UNSET` sentinel value."""3435T_FLAG_NEEDS_VALUE = t.Literal[FLAG_NEEDS_VALUE] # type: ignore[valid-type]35T_FLAG_NEEDS_VALUE: t.TypeAlias = t.Literal[Sentinel.FLAG_NEEDS_VALUE]36"""Type hint for the :data:`FLAG_NEEDS_VALUE` sentinel value."""
modified:src/click/_winconsole.py+3 added-2 removed
26 unmodified lines
27from ctypes.wintypes import DWORD28from ctypes.wintypes import HANDLE29from ctypes.wintypes import LPCWSTR30from ctypes.wintypes import LPWSTR31from gettext import gettext as _3233from ._compat import _NonClosingTextIOWrapper3435assert sys.platform == "win32"
116 unmodified lines
152 if GetLastError() == ERROR_OPERATION_ABORTED:153 # wait for KeyboardInterrupt154 time.sleep(0.1)155 if not rv:155 raise OSError(f"Windows error: {GetLastError()}")156 raise OSError(_("Windows error: {error}").format(error=GetLastError()))157158 if buffer[0] == EOF:159 return 0160 return 2 * code_units_read.value
8 unmodified lines
169 if errno == ERROR_SUCCESS:170 return "ERROR_SUCCESS"171 elif errno == ERROR_NOT_ENOUGH_MEMORY:172 return "ERROR_NOT_ENOUGH_MEMORY"172 return f"Windows error {errno}"173 return _("Windows error: {error}").format(error=errno)174175 def write(self, b: Buffer) -> int:176 bytes_to_be_written = len(b)177 buf = get_buffer(b)
120 unmodified lines
modified:src/click/core.py+157 added-98 removed
5 unmodified lines
6import inspect7import os8import sys9import typing as t10from abc import ABC11from abc import abstractmethod12from collections import abc13from collections import Counter14from contextlib import AbstractContextManager15from contextlib import contextmanager
12 unmodified lines
28from .exceptions import ClickException29from .exceptions import Exit30from .exceptions import MissingParameter31from .exceptions import NoArgsIsHelpError32from .exceptions import NoSuchCommand33from .exceptions import UsageError34from .formatting import HelpFormatter35from .formatting import join_options36from .globals import pop_context
55 unmodified lines
9293 raise RuntimeError(message)949596def _format_deprecated_label(deprecated: bool | str) -> str:97 """Return the parenthesized deprecation label shown in help text."""98 label = _("deprecated").upper()99 if isinstance(deprecated, str):100 return f"({label}: {deprecated})"101 return f"({label})"102103104def _format_deprecated_suffix(deprecated: bool | str) -> str:105 """Return the trailing reason for a ``DeprecationWarning`` message,106 prefixed with a space, or an empty string when no reason was given.107 """108 if isinstance(deprecated, str):109 return f" {deprecated}"110 return ""111112113def batch(iterable: cabc.Iterable[V], batch_size: int) -> list[tuple[V, ...]]:114 return list(zip(*repeat(iter(iterable), batch_size), strict=False))115116
353 unmodified lines
470471 self._close_callbacks: list[t.Callable[[], t.Any]] = []472 self._depth = 0473 self._parameter_source: dict[str, ParameterSource] = {}474 # Tracks whether the option that currently owns each parameter slot in475 # :attr:`params` had its ``default`` set explicitly by the user. Used476 # to tie-break feature-switch groups where multiple options share a477 # parameter name and both fall back to their default value.478 # Refs: https://github.com/pallets/click/issues/3403479 self._param_default_explicit: dict[str, bool] = {}480 self._exit_stack = ExitStack()481482 @property483 def protected_args(self) -> list[str]:
379 unmodified lines
863 # https://github.com/pallets/click/issues/3065864 # https://github.com/pallets/click/pull/3068865 if default_value is UNSET:866 default_value = None841 kwargs[param.name] = param.type_cast_value( # type: ignore842 ctx, default_value843 )867 kwargs[param.name] = param.type_cast_value(ctx, default_value)868869 # Track all kwargs as params, so that forward() will pass870 # them on in subsequent calls.871 ctx.params.update(kwargs)
286 unmodified lines
1158 else:1159 text = ""11601161 if self.deprecated:1138 deprecated_message = (1139 f"(DEPRECATED: {self.deprecated})"1140 if isinstance(self.deprecated, str)1141 else "(DEPRECATED)"1142 )1143 text = _("{text} {deprecated_message}").format(1144 text=text, deprecated_message=deprecated_message1145 )1162 text = f"{_(text)} {_format_deprecated_label(self.deprecated)}"11631164 return text.strip()11651166 def format_help(self, ctx: Context, formatter: HelpFormatter) -> None:
21 unmodified lines
1188 else:1189 text = ""11901191 if self.deprecated:1175 deprecated_message = (1176 f"(DEPRECATED: {self.deprecated})"1177 if isinstance(self.deprecated, str)1178 else "(DEPRECATED)"1179 )1180 text = _("{text} {deprecated_message}").format(1181 text=text, deprecated_message=deprecated_message1182 )1192 text = f"{_(text)} {_format_deprecated_label(self.deprecated)}"11931194 if text:1195 formatter.write_paragraph()1196
98 unmodified lines
1295 """Given a context, this invokes the attached callback (if it exists)1296 in the right way.1297 """1298 if self.deprecated:1289 extra_message = (1290 f" {self.deprecated}" if isinstance(self.deprecated, str) else ""1291 )1299 message = _(1300 "DeprecationWarning: The command {name!r} is deprecated.{extra_message}"1294 ).format(name=self.name, extra_message=extra_message)1301 ).format(1302 name=self.name,1303 extra_message=_format_deprecated_suffix(self.deprecated),1304 )1305 echo(style(message, fg="red"), err=True)13061307 if self.callback is not None:1308 return ctx.invoke(self.callback, **ctx.params)
20 unmodified lines
1329 not isinstance(param, Option)1330 or param.hidden1331 or (1332 not param.multiple1323 and ctx.get_parameter_source(param.name) # type: ignore1333 and ctx.get_parameter_source(param.name)1334 is ParameterSource.COMMANDLINE1335 )1336 ):1337 continue
608 unmodified lines
1946 def resolve_command(1947 self, ctx: Context, args: list[str]1948 ) -> tuple[str | None, Command | None, list[str]]:1949 cmd_name = make_str(args[0])1940 original_cmd_name = cmd_name19501951 # Get the command1952 cmd = self.get_command(ctx, cmd_name)1953
11 unmodified lines
1965 # place.1966 if cmd is None and not ctx.resilient_parsing:1967 if _split_opt(cmd_name)[0]:1968 self.parse_args(ctx, args)1960 ctx.fail(_("No such command {name!r}.").format(name=original_cmd_name))1969 raise NoSuchCommand(cmd_name, possibilities=self.commands, ctx=ctx)1970 return cmd_name if cmd else None, cmd, args[1:]19711972 def shell_complete(self, ctx: Context, incomplete: str) -> list[CompletionItem]:1973 """Return a list of completions for the incomplete value. Looks
87 unmodified lines
20612062 return iter(value)206320642056class Parameter:2065class Parameter(ABC):2066 r"""A parameter to a command comes in two versions: they are either2067 :class:`Option`\s or :class:`Argument`\s. Other subclasses are currently2068 not supported by design as some of the internals for parsing are2069 intentionally not finalized.
87 unmodified lines
21572158 def __init__(2159 self,2160 param_decls: cabc.Sequence[str] | None = None,2152 type: types.ParamType | t.Any | None = None,2161 type: types.ParamType[t.Any] | t.Any | None = None,2162 required: bool = False,2163 # XXX The default historically embed two concepts:2164 # - the declaration of a Parameter object carrying the default (handy to2165 # arbitrage the default value of coupled Parameters sharing the same
17 unmodified lines
2183 ]2184 | None = None,2185 deprecated: bool | str = False,2186 ) -> None:2178 self.name: str | None2187 self.name: str2188 self.opts: list[str]2189 self.secondary_opts: list[str]2190 self.name, self.opts, self.secondary_opts = self._parse_decls(2191 param_decls or (), expose_value2192 )2184 self.type: types.ParamType = types.convert_type(type, default)2193 self.type: types.ParamType[t.Any] = types.convert_type(type, default)21942195 # Default nargs to what the type tells us if we have that2196 # information available.2197 if nargs is None:
7 unmodified lines
2205 self.nargs = nargs2206 self.multiple = multiple2207 self.expose_value = expose_value2208 self.default: t.Any | t.Callable[[], t.Any] | None = default2209 # Whether the user passed ``default`` explicitly to the constructor.2210 # Captured before any auto-derived default (like ``False`` for boolean2211 # flags in :class:`Option`) replaces the :data:`UNSET` sentinel, so it2212 # remains ``False`` when the default was inferred rather than chosen.2213 # Refs: https://github.com/pallets/click/issues/34032214 self._default_explicit: bool = default is not UNSET2215 self.is_eager = is_eager2216 self.metavar = metavar2217 self.envvar = envvar2218 self._custom_shell_complete = shell_complete
43 unmodified lines
22622263 def __repr__(self) -> str:2264 return f"<{self.__class__.__name__} {self.name}>"22652266 @abstractmethod2267 def _parse_decls(2268 self, decls: cabc.Sequence[str], expose_value: bool2253 ) -> tuple[str | None, list[str], list[str]]:2254 raise NotImplementedError()2269 ) -> tuple[str, list[str], list[str]]: ...22702271 @property2272 def human_readable_name(self) -> str:2273 """Returns the human readable name of this parameter. This is the2274 same as the name for options, but the metavar for arguments.2275 """2261 return self.name # type: ignore2276 return self.name22772278 def make_metavar(self, ctx: Context) -> str:2279 if self.metavar is not None:2280 return self.metavar
40 unmodified lines
23212322 .. versionchanged:: 8.02323 Added the ``call`` parameter.2324 """2310 name = self.name2311 value = ctx.lookup_default(name, call=False) if name is not None else None2325 value = ctx.lookup_default(self.name, call=False)23262313 if value is None and not ctx._default_map_has(name):2327 if value is None and not ctx._default_map_has(self.name):2328 value = self.default23292330 if call and callable(value):2331 value = value()23322333 return value23342321 def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None:2322 raise NotImplementedError()2335 @abstractmethod2336 def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None: ...23372338 def consume_value(2339 self, ctx: Context, opts: cabc.Mapping[str, t.Any]2340 ) -> tuple[t.Any, ParameterSource]:
7 unmodified lines
23482349 :meta private:2350 """2351 # Collect from the parse the value passed by the user to the CLI.2338 value = opts.get(self.name, UNSET) # type: ignore2352 value = opts.get(self.name, UNSET)2353 # If the value is set, it means it was sourced from the command line by the2354 # parser, otherwise it left unset by default.2355 source = (2356 ParameterSource.COMMANDLINE
7 unmodified lines
2364 value = envvar_value2365 source = ParameterSource.ENVIRONMENT23662367 if value is UNSET:2354 default_map_value = ctx.lookup_default(self.name) # type: ignore[arg-type]2368 default_map_value = ctx.lookup_default(self.name)2369 if default_map_value is not None or ctx._default_map_has(self.name):2370 value = default_map_value2371 source = ParameterSource.DEFAULT_MAP23722373 # A string from default_map must be split for multi-value2374 # parameters, matching value_from_envvar behavior.2375 if isinstance(value, str) and self.nargs != 1:2376 value = self.type.split_envvar_value(value)23772378 if value is UNSET:2379 default_value = self.get_default(ctx)2380 if default_value is not UNSET:2381 value = default_value
215 unmodified lines
2597 a default).25982599 :meta private:2600 """2601 # Capture the slot's existing state before we mutate2602 # ``_parameter_source`` so the write decision below can compare our2603 # incoming source against the source of the option that already wrote2604 # the slot (if any).2605 existing_value = ctx.params.get(self.name, UNSET)2606 existing_source = ctx.get_parameter_source(self.name)2607 existing_default_explicit = ctx._param_default_explicit.get(self.name, False)26082609 with augment_usage_errors(ctx, param=self):2610 value, source = self.consume_value(ctx, opts)26112585 ctx.set_parameter_source(self.name, source) # type: ignore25862612 # Display a deprecation warning if necessary.2613 if (2614 self.deprecated2615 and value is not UNSET2616 and source < ParameterSource.DEFAULT_MAP2617 ):2593 extra_message = (2594 f" {self.deprecated}" if isinstance(self.deprecated, str) else ""2595 )2618 message = _(2619 "DeprecationWarning: The {param_type} {name!r} is deprecated."2620 "{extra_message}"2621 ).format(2622 param_type=self.param_type_name,2623 name=self.human_readable_name,2602 extra_message=extra_message,2624 extra_message=_format_deprecated_suffix(self.deprecated),2625 )2626 echo(style(message, fg="red"), err=True)26272628 # Process the value through the parameter's type.
6 unmodified lines
2635 # value is incompatible with the parameter type, so we reset the value2636 # to UNSET, which will be interpreted as a missing value.2637 value = UNSET26382617 # Add parameter's value to the context.2618 if (2619 self.expose_value2620 # We skip adding the value if it was previously set by another parameter2621 # targeting the same variable name. This prevents parameters competing for2622 # the same name to override each other.2623 and (self.name not in ctx.params or ctx.params[self.name] is UNSET)2624 ):2625 # Click is logically enforcing that the name is None if the parameter is2626 # not to be exposed. We still assert it here to please the type checker.2627 assert self.name is not None, (2628 f"{self!r} parameter's name should not be None when exposing value."2629 )2630 ctx.params[self.name] = value2639 # Arbitrate the slot when several parameters target the same variable2640 # name (feature-switch groups). See: https://github.com/pallets/click/issues/34032641 slot_empty = existing_value is UNSET2642 more_explicit = existing_source is not None and source < existing_source2643 same_source = existing_source is not None and source == existing_source2644 auto_would_downgrade_explicit = (2645 same_source2646 and source == ParameterSource.DEFAULT2647 and existing_default_explicit2648 and not self._default_explicit2649 )2650 is_winner = (2651 slot_empty2652 or more_explicit2653 or (same_source and not auto_would_downgrade_explicit)2654 )26552656 if is_winner:2657 ctx.set_parameter_source(self.name, source)2658 if self.expose_value:2659 ctx.params[self.name] = value2660 ctx._param_default_explicit[self.name] = self._default_explicit2661 elif existing_source is None:2662 # Nothing has claimed the slot yet. Record at least our source so downstream2663 # lookups don't return ``None``.2664 ctx.set_parameter_source(self.name, source)26652666 return value, args26672668 def get_help_record(self, ctx: Context) -> tuple[str, str] | None:2635 pass2669 return None26702671 def get_usage_pieces(self, ctx: Context) -> list[str]:2672 return []26732640 def get_error_hint(self, ctx: Context) -> str:2674 def get_error_hint(self, ctx: Context | None) -> str:2675 """Get a stringified version of the param for use in error messages to2676 indicate which param caused the error.26772678 .. versionchanged:: 8.4.02679 ``ctx`` can be ``None``.2680 """2681 hint_list = self.opts or [self.human_readable_name]2682 return " / ".join(f"'{x}'" for x in hint_list)26832684 def shell_complete(self, ctx: Context, incomplete: str) -> list[CompletionItem]:2685 """Return a list of completions for the incomplete value. If a2686 ``shell_complete`` function was given during init, it is used.2687 Otherwise, the :attr:`type`2651 :meth:`~click.types.ParamType.shell_complete` function is used.2688 :meth:`~click.types.ParamType[t.Any].shell_complete` function is used.26892690 :param ctx: Invocation context for this command.2691 :param incomplete: Value being completed. May be empty.2692
57 unmodified lines
2750 :param help: the help string.2751 :param hidden: hide this option from help outputs.2752 :param attrs: Other command arguments described in :class:`Parameter`.27532754 .. versionchanged:: 8.42755 Non-basic ``flag_value`` types (not ``str``, ``int``, ``float``, or2756 ``bool``) are passed through unchanged instead of being stringified.2757 Previously, ``type=click.UNPROCESSED`` was required to preserve them.27582759 .. versionchanged:: 8.22760 ``envvar`` used with ``flag_value`` will always use the ``flag_value``,2761 previously it would use the value of the environment variable.2762
9 unmodified lines
2772 The default of a single option boolean flag is not shown if the2773 default value is ``False``.27742775 .. versionchanged:: 8.0.12734 ``type`` is detected from ``flag_value`` if given.2776 ``type`` is detected from ``flag_value`` if given, for basic Python2777 types (``str``, ``int``, ``float``, ``bool``).2778 """27792780 param_type_name = "option"2781
9 unmodified lines
2791 flag_value: t.Any = UNSET,2792 multiple: bool = False,2793 count: bool = False,2794 allow_from_autoenv: bool = True,2752 type: types.ParamType | t.Any | None = None,2795 type: types.ParamType[t.Any] | t.Any | None = None,2796 help: str | None = None,2797 hidden: bool = False,2798 show_choices: bool = True,2799 show_envvar: bool = False,
7 unmodified lines
2807 param_decls, type=type, multiple=multiple, deprecated=deprecated, **attrs2808 )28092810 if prompt is True:2768 if self.name is None:2811 if not self.name:2812 raise TypeError("'name' is required with 'prompt=True'.")28132814 prompt_text: str | None = self.name.replace("_", " ").capitalize()2815 elif prompt is False:
1 unmodified line
2817 else:2818 prompt_text = prompt28192820 if deprecated:2778 deprecated_message = (2779 f"(DEPRECATED: {deprecated})"2780 if isinstance(deprecated, str)2781 else "(DEPRECATED)"2782 )2783 help = help + deprecated_message if help is not None else deprecated_message2821 label = _format_deprecated_label(deprecated)2822 help = f"{help} {label}" if help is not None else label28232824 self.prompt = prompt_text2825 self.confirmation_prompt = confirmation_prompt2826 self.prompt_required = prompt_required
36 unmodified lines
2863 # Auto-detect the type of the flag based on the flag_value.2864 if type is None:2865 # A flag without a flag_value is a boolean flag.2866 if flag_value is UNSET:2828 self.type: types.ParamType = types.BoolParamType()2867 self.type: types.ParamType[t.Any] = types.BoolParamType()2868 # If the flag value is a boolean, use BoolParamType.2869 elif isinstance(flag_value, bool):2870 self.type = types.BoolParamType()2871 # Otherwise, guess the type from the flag value.2872 else:2834 self.type = types.convert_type(None, flag_value)2873 guessed = types.convert_type(None, flag_value)2874 if (2875 isinstance(guessed, types.StringParamType)2876 and not isinstance(flag_value, str)2877 and flag_value is not None2878 ):2879 # The flag_value type couldn't be auto-detected2880 # (not str, int, float, or bool). Since flag_value2881 # is a programmer-provided Python object, not CLI2882 # input, pass it through unchanged instead of2883 # stringifying it.2884 self.type = types.UNPROCESSED2885 else:2886 self.type = guessed28872888 self.is_flag: bool = bool(is_flag)2889 self.is_bool_flag: bool = bool(2890 is_flag and isinstance(self.type, types.BoolParamType)
106 unmodified lines
2997 value = value()29982999 return value30002949 def get_error_hint(self, ctx: Context) -> str:3001 def get_error_hint(self, ctx: Context | None) -> str:3002 result = super().get_error_hint(ctx)3003 if self.show_envvar and self.envvar is not None:3004 result += f" (env var: '{self.envvar}')"3005 return result30063007 def _parse_decls(3008 self, decls: cabc.Sequence[str], expose_value: bool2957 ) -> tuple[str | None, list[str], list[str]]:3009 ) -> tuple[str, list[str], list[str]]:3010 opts = []3011 secondary_opts = []3012 name = None3013 possible_names = []30143015 for decl in decls:3016 if decl.isidentifier():3017 if name is not None:2966 raise TypeError(f"Name '{name}' defined twice")3018 raise TypeError(_("Name '{name}' defined twice").format(name=name))3019 name = decl3020 else:3021 split_char = ";" if decl[:1] == "/" else "/"3022 if split_char in decl:
6 unmodified lines
3029 if second:3030 secondary_opts.append(second.lstrip())3031 if first == second:3032 raise ValueError(3033 _(2981 f"Boolean option {decl!r} cannot use the"2982 " same flag for true/false."3034 "Boolean option {decl!r} cannot use the"3035 " same flag for true/false."3036 ).format(decl=decl)3037 )3038 else:3039 possible_names.append(_split_opt(decl))3040 opts.append(decl)
5 unmodified lines
3046 name = None30473048 if name is None:3049 if not expose_value:2996 return None, opts, secondary_opts3050 return "", opts, secondary_opts3051 raise TypeError(3052 _(2998 f"Could not determine name for option with declarations {decls!r}"3053 "Could not determine name for option with declarations {decls!r}"3054 ).format(decls=decls)3055 )30563057 if not opts and not secondary_opts:3058 raise TypeError(3059 _(3003 f"No options defined but a name was passed ({name})."3004 " Did you mean to declare an argument instead? Did"3005 f" you mean to pass '--{name}'?"3060 "No options defined but a name was passed ({name})."3061 " Did you mean to declare an argument instead? Did"3062 " you mean to pass '--{name}'?"3063 ).format(name=name)3064 )30653066 return name, opts, secondary_opts3067
90 unmodified lines
3158 if envvar is None:3159 if (3160 self.allow_from_autoenv3161 and ctx.auto_envvar_prefix is not None3104 and self.name is not None3162 and self.name3163 ):3164 envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}"31653166 if envvar is not None:
130 unmodified lines
32973298 if rv is not None:3299 return rv33003243 if (3244 self.allow_from_autoenv3245 and ctx.auto_envvar_prefix is not None3246 and self.name is not None3247 ):3301 if self.allow_from_autoenv and ctx.auto_envvar_prefix is not None and self.name:3302 envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}"3303 rv = os.environ.get(envvar)33043305 if rv:
84 unmodified lines
3390 # FLAG_NEEDS_VALUE sentinel) with the flag_value.3391 elif (3392 self.multiple3393 and value is not UNSET3394 and isinstance(value, cabc.Iterable)3395 and source < ParameterSource.DEFAULT_MAP3396 and any(v is FLAG_NEEDS_VALUE for v in value)3397 ):3398 value = [self.flag_value if v is FLAG_NEEDS_VALUE else v for v in value]
64 unmodified lines
3463 @property3464 def human_readable_name(self) -> str:3465 if self.metavar is not None:3466 return self.metavar3412 return self.name.upper() # type: ignore3467 return self.name.upper()34683469 def make_metavar(self, ctx: Context) -> str:3470 if self.metavar is not None:3471 return self.metavar3472 var = self.type.get_metavar(param=self, ctx=ctx)3473 if not var:3419 var = self.name.upper() # type: ignore3474 var = self.name.upper()3475 if self.deprecated:3476 var += "!"3477 if not self.required:3478 var = f"[{var}]"
2 unmodified lines
3481 return var34823483 def _parse_decls(3484 self, decls: cabc.Sequence[str], expose_value: bool3430 ) -> tuple[str | None, list[str], list[str]]:3485 ) -> tuple[str, list[str], list[str]]:3486 if not decls:3487 if not expose_value:3433 return None, [], []3488 return "", [], []3489 raise TypeError("Argument is marked as exposed, but does not have a name.")3490 if len(decls) == 1:3491 name = arg = decls[0]3492 name = name.replace("-", "_").lower()3493 else:3494 raise TypeError(3495 _(3440 "Arguments take exactly one parameter declaration, got"3441 f" {len(decls)}: {decls}."3496 "Arguments take exactly one parameter declaration, got"3497 " {length}: {decls}."3498 ).format(length=len(decls), decls=decls)3499 )3500 return name, [arg], []35013502 def get_usage_pieces(self, ctx: Context) -> list[str]:3503 return [self.make_metavar(ctx)]35043448 def get_error_hint(self, ctx: Context) -> str:3449 return f"'{self.make_metavar(ctx)}'"3505 def get_error_hint(self, ctx: Context | None) -> str:3506 if ctx is not None:3507 return f"'{self.make_metavar(ctx)}'"3508 return f"'{self.human_readable_name}'"35093510 def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None:3511 parser.add_argument(dest=self.name, nargs=self.nargs, obj=self)3512
23 unmodified lines
modified:src/click/decorators.py+2 added-2 removed
394 unmodified lines
395396 kwargs.setdefault("is_flag", True)397 kwargs.setdefault("callback", callback)398 kwargs.setdefault("expose_value", False)399 kwargs.setdefault("prompt", "Do you want to continue?")400 kwargs.setdefault("help", "Confirm the action without prompting.")399 kwargs.setdefault("prompt", _("Do you want to continue?"))400 kwargs.setdefault("help", _("Confirm the action without prompting."))401 return option(*param_decls, **kwargs)402403404def password_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]:
147 unmodified lines
modified:src/click/exceptions.py+51 added-15 removed
21 unmodified lines
2223 return param_hint242526def _format_possibilities(possibilities: list[str]) -> str:27 possibility_str = ", ".join(repr(p) for p in sorted(possibilities))28 return ngettext(29 "Did you mean {possibility}?",30 "(Did you mean one of: {possibilities}?)",31 len(possibilities),32 ).format(possibility=possibility_str, possibilities=possibility_str)333435class ClickException(Exception):36 """An exception that Click can handle and show to the user."""3738 #: The exit code for this exception.
47 unmodified lines
86 if (87 self.ctx is not None88 and self.ctx.command.get_help_option(self.ctx) is not None89 ):90 help_names = self.ctx.command.get_help_option_names(self.ctx)91 # Pick the longest name (like ``--help`` over ``-h``) for92 # readability in error messages.93 hint = _("Try '{command} {option}' for help.").format(82 command=self.ctx.command_path, option=self.ctx.help_option_names[0]94 command=self.ctx.command_path,95 option=max(help_names, key=len),96 )97 hint = f"{hint}\n"98 if self.ctx is not None:99 color = self.ctx.color
37 unmodified lines
137 def format_message(self) -> str:138 if self.param_hint is not None:139 param_hint = self.param_hint140 elif self.param is not None:128 param_hint = self.param.get_error_hint(self.ctx) # type: ignore141 param_hint = self.param.get_error_hint(self.ctx)142 else:143 return _("Invalid value: {message}").format(message=self.message)144145 return _("Invalid value for {param_hint}: {message}").format(
27 unmodified lines
173 def format_message(self) -> str:174 if self.param_hint is not None:175 param_hint: cabc.Sequence[str] | str | None = self.param_hint176 elif self.param is not None:164 param_hint = self.param.get_error_hint(self.ctx) # type: ignore177 param_hint = self.param.get_error_hint(self.ctx)178 else:179 param_hint = None180181 param_hint = _join_param_hints(param_hint)
36 unmodified lines
218 return self.message219220221class NoSuchOption(UsageError):209 """Raised if click attempted to handle an option that does not210 exist.222 """Raised if Click attempted to handle an option that does not exist.223224 .. versionadded:: 4.0225 """226227 def __init__(228 self,229 option_name: str,230 message: str | None = None,219 possibilities: cabc.Sequence[str] | None = None,231 possibilities: cabc.Iterable[str] | None = None,232 ctx: Context | None = None,233 ) -> None:234 if message is None:223 message = _("No such option: {name}").format(name=option_name)235 message = _("No such option {name!r}.").format(name=option_name)236237 super().__init__(message, ctx)238 self.option_name = option_name227 self.possibilities = possibilities239 self.possibilities: list[str] | None = None240 if possibilities:241 from difflib import get_close_matches242243 self.possibilities = get_close_matches(option_name, possibilities)244245 def format_message(self) -> str:246 if not self.possibilities:247 return self.message248 return f"{self.message} {_format_possibilities(self.possibilities)}"249233 possibility_str = ", ".join(sorted(self.possibilities))234 suggest = ngettext(235 "Did you mean {possibility}?",236 "(Possible options: {possibilities})",237 len(self.possibilities),238 ).format(possibility=possibility_str, possibilities=possibility_str)239 return f"{self.message} {suggest}"250251class NoSuchCommand(UsageError):252 """Raised if Click attempted to handle a command that does not exist."""253254 def __init__(255 self,256 command_name: str,257 message: str | None = None,258 possibilities: cabc.Iterable[str] | None = None,259 ctx: Context | None = None,260 ) -> None:261 if message is None:262 message = _("No such command {name!r}.").format(name=command_name)263264 super().__init__(message, ctx)265 self.command_name = command_name266 self.possibilities: list[str] | None = None267 if possibilities:268 from difflib import get_close_matches269270 self.possibilities = get_close_matches(command_name, possibilities)271272 def format_message(self) -> str:273 if not self.possibilities:274 return self.message275 return f"{self.message} {_format_possibilities(self.possibilities)}"276277278class BadOptionUsage(UsageError):279 """Raised if an option is generally supplied but the use of the option280 was incorrect. This is for instance raised if the number of arguments281 for an option is not correct.
63 unmodified lines
modified:src/click/formatting.py+15 added-1 removed
50 unmodified lines
51 :param subsequent_indent: the indent string that should be placed on52 each consecutive line.53 :param preserve_paragraphs: if this flag is set then the wrapping will54 intelligently handle paragraphs.5556 .. versionchanged:: 8.457 Width is measured in visible characters. ANSI escape sequences in58 ``text``, ``initial_indent``, or ``subsequent_indent`` no longer59 count toward the width budget, so styled input wraps based on what60 the user sees instead of raw byte length.61 """62 from ._textwrap import TextWrapper6364 text = text.expandtabs()
93 unmodified lines
158 :param prefix: The prefix for the first line. Defaults to159 ``"Usage: "``.160 """161 if prefix is None:156 prefix = f"{_('Usage:')} "162 prefix = "{usage} ".format(usage=_("Usage:"))163164 usage_prefix = f"{prefix:>{self.current_indent}}{prog} "165 text_width = self.width - self.current_indent166167 if not args:168 # Without args, the prefix's trailing space and the wrap_text169 # call that would normally place args on the line are both170 # unnecessary. Emit just the prefix line.171 self.write(usage_prefix.rstrip(" "))172 self.write("\n")173 return174175 if text_width >= (term_len(usage_prefix) + 20):176 # The arguments will fit to the right of the prefix.177 indent = " " * term_len(usage_prefix)178 self.write(
137 unmodified lines
modified:src/click/parser.py+18 added-17 removed
48 unmodified lines
495051def _unpack_args(52 args: cabc.Sequence[str], nargs_spec: cabc.Sequence[int]53) -> tuple[cabc.Sequence[str | cabc.Sequence[str | None] | None], list[str]]:53) -> tuple[cabc.Sequence[str | cabc.Sequence[str | T_UNSET] | T_UNSET], list[str]]:54 """Given an iterable of arguments and an iterable of nargs specifications,55 it returns a tuple with all the unpacked arguments at the first index56 and all remaining arguments as the second.57
6 unmodified lines
64 nargs_spec = deque(nargs_spec)65 rv: list[str | tuple[str | T_UNSET, ...] | T_UNSET] = []66 spos: int | None = None6768 def _fetch(c: deque[V]) -> V | T_UNSET:68 def _fetch(c: deque[str]) -> str | T_UNSET:69 try:70 if spos is None:71 return c.popleft()72 else:
1 unmodified line
74 except IndexError:75 return UNSET7677 while nargs_spec:78 nargs = _fetch(nargs_spec)78 if spos is None:79 nargs = nargs_spec.popleft()80 else:81 nargs = nargs_spec.pop()8280 if nargs is None:81 continue8283 if nargs == 1:84 rv.append(_fetch(args)) # type: ignore[arg-type]84 rv.append(_fetch(args))85 elif nargs > 1:86 x = [_fetch(args) for _ in range(nargs)]86 x: list[str | T_UNSET] = [_fetch(args) for _ in range(nargs)]8788 # If we're reversed, we're pulling in the arguments in reverse,89 # so we need to turn them around.90 if spos is not None:
49 unmodified lines
140141 for opt in opts:142 prefix, value = _split_opt(opt)143 if not prefix:144 raise ValueError(f"Invalid start character for option ({opt})")144 raise ValueError(145 _("Invalid start character for option ({option})").format(146 option=opt147 )148 )149 self.prefixes.add(prefix[0])150 if len(prefix) == 1 and len(value) == 1:151 self._short_opts.append(opt)152 else:
36 unmodified lines
189 self.obj = obj190191 def process(192 self,189 value: str | cabc.Sequence[str | None] | None | T_UNSET,193 value: str | cabc.Sequence[str | T_UNSET] | T_UNSET,194 state: _ParsingState,195 ) -> None:196 if self.nargs > 1:197 assert isinstance(value, cabc.Sequence)194 holes = sum(1 for x in value if x is UNSET)198 holes = sum(x is UNSET for x in value)199 if holes == len(value):200 value = UNSET201 elif holes != 0:202 raise BadArgumentUsage(
160 unmodified lines
363 def _match_long_opt(364 self, opt: str, explicit_value: str | None, state: _ParsingState365 ) -> None:366 if opt not in self._long_opt:363 from difflib import get_close_matches367 raise NoSuchOption(opt, possibilities=self._long_opt, ctx=self.ctx)368365 possibilities = get_close_matches(opt, self._long_opt)366 raise NoSuchOption(opt, possibilities=possibilities, ctx=self.ctx)367369 option = self._long_opt[opt]370 if option.takes_value:371 # At this point it's safe to modify rargs by injecting the372 # explicit value, because no exception is raised in this
55 unmodified lines
428 state.largs.append(f"{prefix}{''.join(unknown_options)}")429430 def _get_value_from_state(431 self, option_name: str, option: _Option, state: _ParsingState431 ) -> str | cabc.Sequence[str] | T_FLAG_NEEDS_VALUE:432 ) -> str | cabc.Sequence[str] | T_UNSET | T_FLAG_NEEDS_VALUE:433 nargs = option.nargs434434 value: str | cabc.Sequence[str] | T_FLAG_NEEDS_VALUE435 value: str | cabc.Sequence[str] | T_UNSET | T_FLAG_NEEDS_VALUE436437 if len(state.rargs) < nargs:438 if option.obj._flag_needs_value:439 # Option allows omitting the value.
94 unmodified lines
modified:src/click/shell_completion.py+20 added-8 removed
178 unmodified lines
179 set -l response (env %(complete_var)s=fish_complete COMP_WORDS=(commandline -cp) \180COMP_CWORD=(commandline -t) %(prog_name)s);181182 for completion in $response;183 set -l metadata (string split "," $completion);183 set -l metadata (string split \n $completion);184185 if test $metadata[1] = "dir";186 __fish_complete_directories $metadata[2];187 else if test $metadata[1] = "file";188 __fish_complete_path $metadata[2];189 else if test $metadata[1] = "plain";190 if test $metadata[3] != "_";191 echo $metadata[2]\t$metadata[3];192 else;190 echo $metadata[2];193 echo $metadata[2];194 end;195 end;196 end;197end;198
221 unmodified lines
420421 return args, incomplete422423 def format_completion(self, item: CompletionItem) -> str:420 if item.help:421 return f"{item.type},{item.value}\t{item.help}"424 """425 .. versionchanged:: 8.4426 Escape newlines in value and help to fix completion errors with427 multi-line help strings.428 """429 # The fish completion script splits each response line on literal430 # newlines, so any newline in the value or help would corrupt the431 # frame. Replace them with the two-character escape "\n" so the text432 # round-trips through fish without breaking the format. The "_"433 # sentinel for missing help mirrors :class:`ZshComplete`.434 help_ = item.help or "_"435 value = item.value.replace("\n", r"\n")436 help_escaped = help_.replace("\n", r"\n")437 return f"{item.type}\n{value}\n{help_escaped}"438423 return f"{item.type},{item.value}"439425440ShellCompleteType = t.TypeVar("ShellCompleteType", bound="type[ShellComplete]")441442443_available_shells: dict[str, type[ShellComplete]] = {
80 unmodified lines
524 """525 if not isinstance(param, Argument):526 return False527514 assert param.name is not None515 # Will be None if expose_value is False.528 value = ctx.params.get(param.name)529 return (530 param.nargs == -1531 or ctx.get_parameter_source(param.name) is not ParameterSource.COMMANDLINE
148 unmodified lines
modified:src/click/termui.py+74 added-24 removed
2 unmodified lines
3import collections.abc as cabc4import inspect5import io6import itertools7import re8import sys9import typing as t10from contextlib import AbstractContextManager11from contextlib import redirect_stdout12from gettext import gettext as _1314from ._compat import isatty15from ._compat import strip_ansi16from ._compat import WIN17from .exceptions import Abort18from .exceptions import UsageError19from .globals import resolve_color_default20from .types import Choice
32 unmodified lines
53}54_ansi_reset_all = "\033[0m"555657_HIDDEN_INPUT_MASK = "'***'"585960def _mask_hidden_input(message: str, value: str) -> str:61 """Replace occurrences of ``value`` in ``message`` with a fixed mask.6263 Both ``repr(value)`` (the form built-in :class:`ParamType` errors use64 via ``{value!r}``) and the raw value are masked. The raw-value pass65 uses word-boundary lookarounds so a substring like ``"1"`` does not66 match inside ``"10"``, and ``"ent"`` does not match inside67 ``"Authentication"``. The empty string is skipped to avoid matching68 at every boundary.69 """70 message = message.replace(repr(value), _HIDDEN_INPUT_MASK)71 if value:72 message = re.sub(73 rf"(?<!\w){re.escape(value)}(?!\w)", _HIDDEN_INPUT_MASK, message74 )75 return message767778def hidden_prompt_func(prompt: str) -> str:79 import getpass8081 return getpass.getpass(prompt)828384def _readline_prompt(func: t.Callable[[str], str], text: str, err: bool) -> str:85 """Call a prompt function, passing the full prompt on non-Windows so86 readline can handle line editing and cursor positioning correctly.8788 On Windows the prompt is written separately via :func:`echo` for89 colorama support, with only the last character passed to *func*.90 """91 if WIN:92 # Write the prompt separately so that we get nice coloring93 # through colorama on Windows.94 echo(text[:-1], nl=False, err=err)95 # Echo the last character to stdout to work around an issue96 # where readline causes backspace to clear the whole line.97 return func(text[-1:])98 if err:99 with redirect_stdout(sys.stderr):100 return func(text)101 return func(text)102103104def _build_prompt(105 text: str,106 suffix: str,107 show_default: bool | str = False,108 default: t.Any | None = None,109 show_choices: bool = True,66 type: ParamType | None = None,110 type: ParamType[t.Any] | None = None,111) -> str:112 prompt = text113 if type is not None and show_choices and isinstance(type, Choice):114 prompt += f" ({', '.join(map(str, type.choices))})"
15 unmodified lines
130 text: str,131 default: t.Any | None = None,132 hide_input: bool = False,133 confirmation_prompt: bool | str = False,90 type: ParamType | t.Any | None = None,134 type: ParamType[t.Any] | t.Any | None = None,135 value_proc: t.Callable[[str], t.Any] | None = None,136 prompt_suffix: str = ": ",137 show_default: bool | str = True,138 err: bool = False,
51 unmodified lines
190191 def prompt_func(text: str) -> str:192 f = hidden_prompt_func if hide_input else visible_prompt_func193 try:150 # Write the prompt separately so that we get nice151 # coloring through colorama on Windows152 echo(text[:-1], nl=False, err=err)153 # Echo the last character to stdout to work around an issue where154 # readline causes backspace to clear the whole line.155 return f(text[-1:])194 return _readline_prompt(f, text, err)195 except (KeyboardInterrupt, EOFError):196 # getpass doesn't print a newline if the user aborts input with ^C.197 # Allegedly this behavior is inherited from getpass(3).198 # A doc bug has been filed at https://bugs.python.org/issue24711
24 unmodified lines
223 break224 try:225 result = value_proc(value)226 except UsageError as e:188 if hide_input:189 echo(_("Error: The value you entered was invalid."), err=err)190 else:191 echo(_("Error: {e.message}").format(e=e), err=err)227 message = _mask_hidden_input(e.message, value) if hide_input else e.message228 echo(_("Error: {message}").format(message=message), err=err)229 continue230 if not confirmation_prompt:231 return result232 while True:
46 unmodified lines
279 )280281 while True:282 try:246 # Write the prompt separately so that we get nice247 # coloring through colorama on Windows248 echo(prompt[:-1], nl=False, err=err)249 # Echo the last character to stdout to work around an issue where250 # readline causes backspace to clear the whole line.251 value = visible_prompt_func(prompt[-1:]).lower().strip()283 value = _readline_prompt(visible_prompt_func, prompt, err).lower().strip()284 except (KeyboardInterrupt, EOFError):285 raise Abort() from None286 if value in ("y", "yes"):287 rv = True
9 unmodified lines
297 raise Abort()298 return rv299300301def get_pager_file(302 color: bool | None = None,303) -> t.ContextManager[t.TextIO]:304 """Context manager.305306 Yields a writable file-like object which can be used as an output pager.307308 .. versionadded:: 8.2309310 :param color: controls if the pager supports ANSI colors or not. The311 default is autodetection.312 """313 from ._termui_impl import get_pager_file314315 color = resolve_color_default(color)316317 return get_pager_file(color=color)318319320def echo_via_pager(321 text_or_generator: cabc.Iterable[str] | t.Callable[[], cabc.Iterable[str]] | str,322 color: bool | None = None,323) -> None:
7 unmodified lines
331 generator emitting the text to page.332 :param color: controls if the pager supports ANSI colors or not. The333 default is autodetection.334 """284 color = resolve_color_default(color)335336 if inspect.isgeneratorfunction(text_or_generator):337 i = t.cast("t.Callable[[], cabc.Iterable[str]]", text_or_generator)()338 elif isinstance(text_or_generator, str):
3 unmodified lines
342343 # convert every element of i to a text type if necessary344 text_generator = (el if isinstance(el, str) else str(el) for el in i)345296 from ._termui_impl import pager346 with get_pager_file(color=color) as pager:347 for text in itertools.chain(text_generator, "\n"):348 pager.write(text)349298 return pager(itertools.chain(text_generator, "\n"), color)350300351@t.overload352def progressbar(353 *,354 length: int,
316 unmodified lines
671 if fg:672 try:673 bits.append(f"\033[{_interpret_color(fg)}m")674 except KeyError:625 raise TypeError(f"Unknown color {fg!r}") from None675 raise TypeError(_("Unknown color {colour!r}").format(colour=fg)) from None676677 if bg:678 try:679 bits.append(f"\033[{_interpret_color(bg, 10)}m")680 except KeyError:631 raise TypeError(f"Unknown color {bg!r}") from None681 raise TypeError(_("Unknown color {colour!r}").format(colour=bg)) from None682683 if bold is not None:684 bits.append(f"\033[{1 if bold else 22}m")685 if dim is not None:
256 unmodified lines
modified:src/click/testing.py+103 added-36 removed
20 unmodified lines
21 from _typeshed import ReadableBuffer2223 from .core import Command2425CaptureMode = t.Literal["sys", "fd"]262728class EchoingStdin:29 def __init__(self, input: t.BinaryIO, output: t.BinaryIO) -> None:30 self._input = input31 self._output = output
36 unmodified lines
68 yield69 stream._paused = False707172class _FDCapture:73 """Redirect a file descriptor to a temporary file for capture.7475 Saves the current target of *targetfd* via :func:`os.dup`, then76 redirects it to a temporary file via :func:`os.dup2`. On77 :meth:`stop`, restores the original ``fd`` and returns the captured78 bytes. Inspired by Pytest's ``FDCapture``.7980 .. versionadded:: 8.4.081 """8283 def __init__(self, targetfd: int) -> None:84 self._targetfd = targetfd85 self.saved_fd: int = -186 self._tmpfile: t.BinaryIO | None = None8788 def start(self) -> None:89 self.saved_fd = os.dup(self._targetfd)90 self._tmpfile = tempfile.TemporaryFile(buffering=0)91 os.dup2(self._tmpfile.fileno(), self._targetfd)9293 def stop(self) -> bytes:94 assert self._tmpfile is not None, "_FDCapture.start() was not called"95 os.dup2(self.saved_fd, self._targetfd)96 os.close(self.saved_fd)97 self.saved_fd = -198 self._tmpfile.seek(0)99 data = self._tmpfile.read()100 self._tmpfile.close()101 self._tmpfile = None102 return data103104105class BytesIOCopy(io.BytesIO):106 """Patch ``io.BytesIO`` to let the written stream be copied to another.107108 .. versionadded:: 8.2
29 unmodified lines
138class _NamedTextIOWrapper(io.TextIOWrapper):139 """A :class:`~io.TextIOWrapper` with custom ``name`` and ``mode``140 that does not close its underlying buffer.141107 An optional ``original_fd`` preserves the file descriptor of the108 stream being replaced, so that C-level consumers that call109 :meth:`fileno` (``faulthandler``, ``subprocess``, ...) still work.110 Inspired by pytest's ``capsys``/``capfd`` split: see :doc:`/testing`111 for details.112113 .. versionchanged:: 8.3.3114 Added ``original_fd`` parameter and :meth:`fileno` override.142 When ``CliRunner`` runs in ``fd`` mode, ``_original_fd`` is patched to143 point at the saved (pre-redirection) ``fd``, so C-level consumers that call144 :meth:`fileno` (like ``faulthandler`` or ``subprocess``) keep working. In145 the default ``sys`` mode ``_original_fd`` stays at ``-1`` and146 :meth:`fileno` raises :exc:`io.UnsupportedOperation`, matching the147 pre-``8.3.3`` behavior.148 """149150 def __init__(151 self,152 buffer: t.BinaryIO,153 name: str,154 mode: str,122 *,123 original_fd: int = -1,155 **kwargs: t.Any,156 ) -> None:157 super().__init__(buffer, **kwargs)158 self._name = name159 self._mode = mode129 self._original_fd = original_fd160 self._original_fd: int = -1161162 def close(self) -> None:163 """The buffer this object contains belongs to some other object,164 so prevent the default ``__del__`` implementation from closing
2 unmodified lines
167 .. versionadded:: 8.3.2168 """169170 def fileno(self) -> int:140 """Return the file descriptor of the original stream, if one was141 provided at construction time.142143 This allows C-level consumers (``faulthandler``, ``subprocess``,144 signal handlers, ...) to obtain a valid fd without crashing, even145 though the Python-level writes are redirected to an in-memory146 buffer.147148 .. versionadded:: 8.3.3171 """Return the file descriptor of the saved original stream when172 ``CliRunner`` runs in ``fd`` mode. Otherwise delegate to173 :class:`~io.TextIOWrapper`, which raises174 :exc:`io.UnsupportedOperation` for a ``BytesIO``-backed buffer.175 """176 if self._original_fd >= 0:177 return self._original_fd178 return super().fileno()
118 unmodified lines
297 some circumstances. Note that regular prompts298 will automatically echo the input.299 :param catch_exceptions: Whether to catch any exceptions other than300 ``SystemExit`` when running :meth:`~CliRunner.invoke`.301 :param capture: Selects the output capture strategy. ``sys`` (default)302 captures Python-level writes only and leaves303 :meth:`sys.stdout.fileno` raising :exc:`io.UnsupportedOperation`, so304 user code that calls :func:`os.dup2` on ``sys.stdout.fileno()`` cannot305 clobber the host runner's stdout. ``fd`` redirects file descriptors306 ``1`` and ``2`` via :func:`os.dup2` to a temporary file, also catching307 output from stale stream references, C extensions, and subprocesses.308 ``fd`` is not supported on Windows.309310 .. versionchanged:: 8.4.0311 Added the ``capture`` parameter. The default ``sys`` mode no longer312 exposes the original fd through :meth:`fileno`, reverting the change313 introduced in ``8.3.3`` that broke Pytest's ``fd``-level capture314 teardown. Use ``capture="fd"`` to restore that behavior with proper315 isolation. :issue:`3384`316317 .. versionchanged:: 8.2318 Added the ``catch_exceptions`` parameter.319320 .. versionchanged:: 8.2
5 unmodified lines
326 charset: str = "utf-8",327 env: cabc.Mapping[str, str | None] | None = None,328 echo_stdin: bool = False,329 catch_exceptions: bool = True,330 capture: CaptureMode = "sys",331 ) -> None:332 if capture not in {"sys", "fd"}:333 raise ValueError(334 f"capture={capture!r} is not valid. Choose from 'sys' or 'fd'."335 )336 if capture == "fd" and sys.platform == "win32":337 raise ValueError(338 f"capture={capture!r} is not supported on Windows. Use 'sys'."339 )340 self.charset = charset341 self.env: cabc.Mapping[str, str | None] = env or {}342 self.echo_stdin = echo_stdin343 self.catch_exceptions = catch_exceptions344 self.capture: CaptureMode = capture345346 def get_default_prog_name(self, cli: Command) -> str:347 """Given a command object it will return the default program name348 for it. The default is the `name` attribute or ``"root"`` if not
56 unmodified lines
405 env = self.make_env(env)406407 stream_mixer = StreamMixer()408358 # Preserve the original file descriptors so that C-level359 # consumers (faulthandler, subprocess, etc.) can still obtain a360 # valid fd from the redirected streams. The original streams361 # may themselves lack a fileno() (e.g. when CliRunner is used362 # inside pytest's capsys), so we fall back to -1.363 def _safe_fileno(stream: t.IO[t.Any]) -> int:364 try:365 return stream.fileno()366 except (AttributeError, io.UnsupportedOperation):367 return -1368369 old_stdout_fd = _safe_fileno(old_stdout)370 old_stderr_fd = _safe_fileno(old_stderr)371409 if self.echo_stdin:410 bytes_input = echo_input = t.cast(411 t.BinaryIO, EchoingStdin(bytes_input, stream_mixer.stdout)412 )
11 unmodified lines
424 stream_mixer.stdout,425 encoding=self.charset,426 name="<stdout>",427 mode="w",391 original_fd=old_stdout_fd,428 )429430 sys.stderr = _NamedTextIOWrapper(431 stream_mixer.stderr,432 encoding=self.charset,433 name="<stderr>",434 mode="w",435 errors="backslashreplace",400 original_fd=old_stderr_fd,436 )437438 @_pause_echo(echo_input) # type: ignore439 def visible_input(prompt: str | None = None) -> str:
173 unmodified lines
613 exc_info = None614 if catch_exceptions is None:615 catch_exceptions = self.catch_exceptions616617 # Set up fd capture before isolation replaces sys.stdout and sys.stderr.618 cap_out: _FDCapture | None = None619 cap_err: _FDCapture | None = None620621 if self.capture == "fd":622 cap_out = _FDCapture(1)623 cap_err = _FDCapture(2)624 try:625 cap_out.start()626 cap_err.start()627 except OSError:628 cap_out = cap_err = None629630 with self.isolation(input=input, env=env, color=color) as outstreams:631 # Point the captured streams' fileno() at the saved (original)632 # fd so that C-level consumers like faulthandler keep working633 # while fd 1/2 are redirected to the capture tmpfile.634 if cap_out is not None and cap_err is not None:635 sys.stdout._original_fd = cap_out.saved_fd # type: ignore[union-attr]636 sys.stderr._original_fd = cap_err.saved_fd # type: ignore[union-attr]637638 return_value = None639 exception: BaseException | None = None640 exit_code = 0641
32 unmodified lines
674 exc_info = sys.exc_info()675 finally:676 sys.stdout.flush()677 sys.stderr.flush()678679 # Stop fd capture and merge the captured bytes into680 # the stdout/stderr BytesIO streams. BytesIOCopy mirrors681 # those writes into outstreams[2] automatically.682 if cap_out is not None and cap_err is not None:683 fd_out = cap_out.stop()684 fd_err = cap_err.stop()685 if fd_out:686 outstreams[0].write(fd_out)687 if fd_err:688 outstreams[1].write(fd_err)689690 stdout = outstreams[0].getvalue()691 stderr = outstreams[1].getvalue()692 output = outstreams[2].getvalue()693
43 unmodified lines
modified:src/click/types.py+227 added-137 removed
1from __future__ import annotations23import abc4import collections.abc as cabc5import enum6import os7import stat8import sys9import typing as t10import uuid11from datetime import datetime12from gettext import gettext as _13from gettext import ngettext14
13 unmodified lines
2829ParamTypeValue = t.TypeVar("ParamTypeValue")303130class ParamType:32class ParamTypeInfoDict(t.TypedDict):33 param_type: str34 name: str353637class ParamType(t.Generic[ParamTypeValue], abc.ABC):38 """Represents the type of a parameter. Validates and converts values39 from the command line or Python into the correct type.4041 To implement a custom type, subclass and implement at least the
23 unmodified lines
65 #: are split by ``os.path.pathsep`` by default (":" on Unix and ";" on66 #: Windows).67 envvar_list_splitter: t.ClassVar[str | None] = None6862 def to_info_dict(self) -> dict[str, t.Any]:69 def to_info_dict(self) -> ParamTypeInfoDict:70 """Gather information that could be useful for a tool generating71 user-facing documentation.7273 Use :meth:`click.Context.to_info_dict` to traverse the entire
17 unmodified lines
91 self,92 value: t.Any,93 param: Parameter | None = None,94 ctx: Context | None = None,88 ) -> t.Any:95 ) -> ParamTypeValue | None:96 if value is not None:97 return self.convert(value, param, ctx)98 return None99100 def get_metavar(self, param: Parameter, ctx: Context) -> str | None:101 """Returns the metavar default for this param if it provides one."""102
5 unmodified lines
108 """109110 def convert(111 self, value: t.Any, param: Parameter | None, ctx: Context | None104 ) -> t.Any:112 ) -> ParamTypeValue:113 """Convert the value to the correct type. This is not called if114 the value is ``None`` (the missing value).115116 This must accept string values from the command line, as well as
11 unmodified lines
128 its value. May be ``None``.129 :param ctx: The current context that arrived at this value. May130 be ``None``.131 """124 return value132 # The default returns the value as-is so subclasses that only customize133 # metadata are not forced to redeclare ``convert``.134 return t.cast("ParamTypeValue", value)135136 def split_envvar_value(self, rv: str) -> cabc.Sequence[str]:137 """Given a value from an environment variable this splits it up138 into small chunks depending on the defined envvar list splitter.
30 unmodified lines
169 """170 return []171172163class CompositeParamType(ParamType):173class CompositeParamType(ParamType[ParamTypeValue]):174 is_composite = True175176 @property167 def arity(self) -> int: # type: ignore168 raise NotImplementedError()177 @abc.abstractmethod178 def arity(self) -> int: ... # type: ignore[override]179180171class FuncParamType(ParamType):172 def __init__(self, func: t.Callable[[t.Any], t.Any]) -> None:181class FuncParamTypeInfoDict(ParamTypeInfoDict):182 func: t.Callable[[t.Any], t.Any]183184185class FuncParamType(ParamType[ParamTypeValue]):186 def __init__(self, func: t.Callable[[t.Any], ParamTypeValue]) -> None:187 self.name: str = func.__name__188 self.func = func189176 def to_info_dict(self) -> dict[str, t.Any]:177 info_dict = super().to_info_dict()178 info_dict["func"] = self.func179 return info_dict190 def to_info_dict(self) -> FuncParamTypeInfoDict:191 return {"func": self.func, **super().to_info_dict()}192193 def convert(194 self, value: t.Any, param: Parameter | None, ctx: Context | None183 ) -> t.Any:195 ) -> ParamTypeValue:196 try:197 return self.func(value)186 except ValueError:187 try:188 value = str(value)189 except UnicodeError:190 value = value.decode("utf-8", "replace")198 except ValueError as exc:199 message = str(exc)200192 self.fail(value, param, ctx)201 if not message:202 try:203 message = str(value)204 except UnicodeError:205 message = value.decode("utf-8", "replace")206207 self.fail(message, param, ctx)208209195class UnprocessedParamType(ParamType):210class UnprocessedParamType(ParamType[t.Any]):211 name = "text"212213 def convert(214 self, value: t.Any, param: Parameter | None, ctx: Context | None
3 unmodified lines
218 def __repr__(self) -> str:219 return "UNPROCESSED"220221207class StringParamType(ParamType):222class StringParamType(ParamType[str]):223 name = "text"224225 def convert(226 self, value: t.Any, param: Parameter | None, ctx: Context | None212 ) -> t.Any:227 ) -> str:228 if isinstance(value, bytes):229 enc = _get_argv_encoding()230 try:231 value = value.decode(enc)
5 unmodified lines
237 except UnicodeError:238 value = value.decode("utf-8", "replace")239 else:240 value = value.decode("utf-8", "replace")226 return value241 return value # type: ignore[no-any-return]242 return str(value)243244 def __repr__(self) -> str:245 return "STRING"246247233class Choice(ParamType, t.Generic[ParamTypeValue]):248class ChoiceInfoDict(ParamTypeInfoDict):249 choices: cabc.Sequence[t.Any]250 case_sensitive: bool251252253class Choice(ParamType[ParamTypeValue], t.Generic[ParamTypeValue]):254 """The choice type allows a value to be checked against a fixed set255 of supported values.256257 You may pass any iterable value which will be converted to a tuple
22 unmodified lines
280 ) -> None:281 self.choices: cabc.Sequence[ParamTypeValue] = tuple(choices)282 self.case_sensitive = case_sensitive283264 def to_info_dict(self) -> dict[str, t.Any]:265 info_dict = super().to_info_dict()266 info_dict["choices"] = self.choices267 info_dict["case_sensitive"] = self.case_sensitive268 return info_dict284 def to_info_dict(self) -> ChoiceInfoDict:285 return {286 "choices": self.choices,287 "case_sensitive": self.case_sensitive,288 **super().to_info_dict(),289 }290291 def _normalized_mapping(292 self, ctx: Context | None = None293 ) -> cabc.Mapping[ParamTypeValue, str]:
98 unmodified lines
392 len(self.choices),393 ).format(value=value, choice=choices_str, choices=choices_str)394395 def __repr__(self) -> str:375 return f"Choice({list(self.choices)})"396 return _("Choice({choices})").format(choices=list(self.choices))397398 def shell_complete(399 self, ctx: Context, param: Parameter, incomplete: str400 ) -> list[CompletionItem]:
17 unmodified lines
418419 return [CompletionItem(c) for c in matched]420421401class DateTime(ParamType):422class DateTimeInfoDict(ParamTypeInfoDict):423 formats: cabc.Sequence[str]424425426class DateTime(ParamType[datetime]):427 """The DateTime type converts date strings into `datetime` objects.428429 The format strings which are checked are configurable, but default to some430 common (non-timezone aware) ISO 8601 formats.
21 unmodified lines
452 "%Y-%m-%dT%H:%M:%S",453 "%Y-%m-%d %H:%M:%S",454 ]455431 def to_info_dict(self) -> dict[str, t.Any]:432 info_dict = super().to_info_dict()433 info_dict["formats"] = self.formats434 return info_dict456 def to_info_dict(self) -> DateTimeInfoDict:457 return {"formats": self.formats, **super().to_info_dict()}458459 def get_metavar(self, param: Parameter, ctx: Context) -> str | None:460 return f"[{'|'.join(self.formats)}]"461
4 unmodified lines
466 return None467468 def convert(469 self, value: t.Any, param: Parameter | None, ctx: Context | None447 ) -> t.Any:470 ) -> datetime:471 if isinstance(value, datetime):472 return value473474 for format in self.formats:
16 unmodified lines
491 def __repr__(self) -> str:492 return "DateTime"493494472class _NumberParamTypeBase(ParamType):473 _number_class: t.ClassVar[type[t.Any]]495class _NumberParamTypeBase(ParamType[ParamTypeValue]):496 _number_class: t.Callable[[t.Any], ParamTypeValue]497498 def convert(499 self, value: t.Any, param: Parameter | None, ctx: Context | None477 ) -> t.Any:500 ) -> ParamTypeValue:501 try:502 return self._number_class(value)503 except ValueError:504 self.fail(
4 unmodified lines
509 ctx,510 )511512513class NumberRangeInfoDict(ParamTypeInfoDict):514 min: float | None515 max: float | None516 min_open: bool517 max_open: bool518 clamp: bool519520490class _NumberRangeBase(_NumberParamTypeBase):521class _NumberRangeBase(_NumberParamTypeBase[ParamTypeValue]):522 def __init__(523 self,524 min: float | None = None,525 max: float | None = None,
6 unmodified lines
532 self.min_open = min_open533 self.max_open = max_open534 self.clamp = clamp535505 def to_info_dict(self) -> dict[str, t.Any]:506 info_dict = super().to_info_dict()507 info_dict.update(508 min=self.min,509 max=self.max,510 min_open=self.min_open,511 max_open=self.max_open,512 clamp=self.clamp,513 )514 return info_dict536 def to_info_dict(self) -> NumberRangeInfoDict:537 return {538 "min": self.min,539 "max": self.max,540 "min_open": self.min_open,541 "max_open": self.max_open,542 "clamp": self.clamp,543 **super().to_info_dict(),544 }545546 def convert(547 self, value: t.Any, param: Parameter | None, ctx: Context | None518 ) -> t.Any:548 ) -> ParamTypeValue:549 import operator550551 rv = super().convert(value, param, ctx)552 min = self.min553 max = self.max522 lt_min: bool = self.min is not None and (554 lt_min: bool = min is not None and (555 operator.le if self.min_open else operator.lt524 )(rv, self.min)525 gt_max: bool = self.max is not None and (556 )(rv, min) # type: ignore[arg-type]557 gt_max: bool = max is not None and (558 operator.ge if self.max_open else operator.gt527 )(rv, self.max)559 )(rv, max) # type: ignore[arg-type]560561 if self.clamp:530 if lt_min:531 return self._clamp(self.min, 1, self.min_open) # type: ignore562 if min is not None and lt_min:563 return self._clamp(min, 1, self.min_open) # type: ignore[arg-type]564533 if gt_max:534 return self._clamp(self.max, -1, self.max_open) # type: ignore565 if max is not None and gt_max:566 return self._clamp(max, -1, self.max_open) # type: ignore[arg-type]567568 if lt_min or gt_max:569 self.fail(570 _("{value} is not in the range {range}.").format(
4 unmodified lines
575 )576577 return rv578547 def _clamp(self, bound: float, dir: t.Literal[1, -1], open: bool) -> float:579 @abc.abstractmethod580 def _clamp(581 self, bound: ParamTypeValue, dir: t.Literal[1, -1], open: bool582 ) -> ParamTypeValue:583 """Find the valid value to clamp to bound in the given584 direction.585586 :param bound: The boundary value.587 :param dir: 1 or -1 indicating the direction to move.588 :param open: If true, the range does not include the bound.589 """555 raise NotImplementedError590 ...591592 def _describe_range(self) -> str:593 """Describe the range for use in help text."""594 if self.min is None:
12 unmodified lines
607 clamp = " clamped" if self.clamp else ""608 return f"<{type(self).__name__} {self._describe_range()}{clamp}>"609610576class IntParamType(_NumberParamTypeBase):611class IntParamType(_NumberParamTypeBase[int]):612 name = "integer"613 _number_class = int614615 def __repr__(self) -> str:616 return "INT"617618584class IntRange(_NumberRangeBase, IntParamType):619class IntRange(_NumberRangeBase[int], IntParamType):620 """Restrict an :data:`click.INT` value to a range of accepted621 values. See :ref:`ranges`.622623 If ``min`` or ``max`` are not passed, any value is accepted in that
8 unmodified lines
632 """633634 name = "integer range"635601 def _clamp( # type: ignore602 self, bound: int, dir: t.Literal[1, -1], open: bool603 ) -> int:636 def _clamp(self, bound: int, dir: t.Literal[1, -1], open: bool) -> int:637 if not open:638 return bound639640 return bound + dir641642610class FloatParamType(_NumberParamTypeBase):643class FloatParamType(_NumberParamTypeBase[float]):644 name = "float"645 _number_class = float646647 def __repr__(self) -> str:648 return "FLOAT"649650618class FloatRange(_NumberRangeBase, FloatParamType):651class FloatRange(_NumberRangeBase[float], FloatParamType):652 """Restrict a :data:`click.FLOAT` value to a range of accepted653 values. See :ref:`ranges`.654655 If ``min`` or ``max`` are not passed, any value is accepted in that
34 unmodified lines
690 # left up to the user to write a callback to do it if needed.691 raise RuntimeError("Clamping is not supported for open bounds.")692693661class BoolParamType(ParamType):694class BoolParamType(ParamType[bool]):695 name = "boolean"696697 bool_states: dict[str, bool] = {698 "1": True,
60 unmodified lines
759 def __repr__(self) -> str:760 return "BOOL"761762730class UUIDParameterType(ParamType):763class UUIDParameterType(ParamType[uuid.UUID]):764 name = "uuid"765766 def convert(767 self, value: t.Any, param: Parameter | None, ctx: Context | None735 ) -> t.Any:736 import uuid737768 ) -> uuid.UUID:769 if isinstance(value, uuid.UUID):770 return value771772 value = value.strip()
8 unmodified lines
781 def __repr__(self) -> str:782 return "UUID"783784754class File(ParamType):785class FileInfoDict(ParamTypeInfoDict):786 mode: str787 encoding: str | None788789790class File(ParamType[t.IO[t.Any]]):791 """Declares a parameter to be a file for reading or writing. The file792 is automatically closed once the context tears down (after the command793 finished working).794
38 unmodified lines
833 self.errors = errors834 self.lazy = lazy835 self.atomic = atomic836801 def to_info_dict(self) -> dict[str, t.Any]:802 info_dict = super().to_info_dict()803 info_dict.update(mode=self.mode, encoding=self.encoding)804 return info_dict837 def to_info_dict(self) -> FileInfoDict:838 return {839 "mode": self.mode,840 "encoding": self.encoding,841 **super().to_info_dict(),842 }843844 def resolve_lazy_flag(self, value: str | os.PathLike[str]) -> bool:845 if self.lazy is not None:846 return self.lazy
43 unmodified lines
890 ctx.call_on_close(safecall(f.flush))891892 return f893 except OSError as e:856 self.fail(f"'{format_filename(value)}': {e.strerror}", param, ctx)894 self.fail(895 f"'{format_filename(value)}': {e.strerror}",896 param,897 ctx,898 )899900 def shell_complete(901 self, ctx: Context, param: Parameter, incomplete: str902 ) -> list[CompletionItem]:
14 unmodified lines
917def _is_file_like(value: t.Any) -> te.TypeGuard[t.IO[t.Any]]:918 return hasattr(value, "read") or hasattr(value, "write")919920879class Path(ParamType):921class PathInfoDict(ParamTypeInfoDict):922 exists: bool923 file_okay: bool924 dir_okay: bool925 writable: bool926 readable: bool927 allow_dash: bool928929930class Path(ParamType[str | bytes | os.PathLike[str]]):931 """The ``Path`` type is similar to the :class:`File` type, but932 returns the filename instead of an open file. Various checks can be933 enabled to validate the type of file and permissions.934
55 unmodified lines
990 self.name = _("directory")991 else:992 self.name = _("path")993943 def to_info_dict(self) -> dict[str, t.Any]:944 info_dict = super().to_info_dict()945 info_dict.update(946 exists=self.exists,947 file_okay=self.file_okay,948 dir_okay=self.dir_okay,949 writable=self.writable,950 readable=self.readable,951 allow_dash=self.allow_dash,952 )953 return info_dict994 def to_info_dict(self) -> PathInfoDict:995 return {996 "exists": self.exists,997 "file_okay": self.file_okay,998 "dir_okay": self.dir_okay,999 "writable": self.writable,1000 "readable": self.readable,1001 "allow_dash": self.allow_dash,1002 **super().to_info_dict(),1003 }10041005 def coerce_path_result(1006 self, value: str | os.PathLike[str]1007 ) -> str | bytes | os.PathLike[str]:
98 unmodified lines
1106 type = "dir" if self.dir_okay and not self.file_okay else "file"1107 return [CompletionItem(incomplete, type=type)]110811091060class Tuple(CompositeParamType):1110class TupleInfoDict(ParamTypeInfoDict):1111 types: cabc.Sequence[ParamTypeInfoDict]111211131114class Tuple(CompositeParamType[tuple[t.Any, ...]]):1115 """The default behavior of Click is to apply a type on a value directly.1116 This works well in most cases, except for when `nargs` is set to a fixed1117 count and different types should be used for different items. In this1118 case the :class:`Tuple` type can be used. This type can only be used
5 unmodified lines
11241125 :param types: a list of types that should be used for the tuple items.1126 """11271074 def __init__(self, types: cabc.Sequence[type[t.Any] | ParamType]) -> None:1075 self.types: cabc.Sequence[ParamType] = [convert_type(ty) for ty in types]1128 def __init__(self, types: cabc.Sequence[type[t.Any] | ParamType[t.Any]]) -> None:1129 self.types: cabc.Sequence[ParamType[t.Any]] = [convert_type(ty) for ty in types]11301077 def to_info_dict(self) -> dict[str, t.Any]:1078 info_dict = super().to_info_dict()1079 info_dict["types"] = [t.to_info_dict() for t in self.types]1080 return info_dict1131 def to_info_dict(self) -> TupleInfoDict:1132 return {1133 "types": [ty.to_info_dict() for ty in self.types],1134 **super().to_info_dict(),1135 }11361137 @property1083 def name(self) -> str: # type: ignore1138 def name(self) -> str: # type: ignore[override]1139 return f"<{' '.join(ty.name for ty in self.types)}>"11401141 @property1087 def arity(self) -> int: # type: ignore1142 def arity(self) -> int: # type: ignore[override]1143 return len(self.types)11441145 def convert(1146 self, value: t.Any, param: Parameter | None, ctx: Context | None1092 ) -> t.Any:1147 ) -> tuple[t.Any, ...]:1148 len_type = len(self.types)1149 len_value = len(value)11501151 if len_value != len_type:
11 unmodified lines
1163 ty(x, param, ctx) for ty, x in zip(self.types, value, strict=False)1164 )116511661112def convert_type(ty: t.Any | None, default: t.Any | None = None) -> ParamType:1113 """Find the most appropriate :class:`ParamType` for the given Python1114 type. If the type isn't provided, it can be inferred from a default1115 value.1167def _guess_type(1168 ty: type[t.Any] | ParamType[t.Any] | None,1169 default: t.Any | None,1170) -> type[t.Any] | tuple[type[t.Any], ...] | ParamType[t.Any] | None:1171 """Infer a type from *ty* or *default*.11721173 Returns *ty* unchanged when it is not ``None``. Otherwise inspects1174 *default* to produce a ``type``, a ``tuple`` of types (for tuple1175 defaults), or ``None``.1176 """1117 guessed_type = False1177 if ty is not None:1178 return ty11791119 if ty is None and default is not None:1120 if isinstance(default, (tuple, list)):1121 # If the default is empty, ty will remain None and will1122 # return STRING.1123 if default:1124 item = default[0]1180 if default is None:1181 return None11821126 # A tuple of tuples needs to detect the inner types.1127 # Can't call convert recursively because that would1128 # incorrectly unwind the tuple to a single type.1129 if isinstance(item, (tuple, list)):1130 ty = tuple(map(type, item))1131 else:1132 ty = type(item)1133 else:1134 ty = type(default)1183 if not isinstance(default, (tuple, list)):1184 return type(default)11851136 guessed_type = True1186 # If the default is empty, return None so convert_type falls1187 # through to STRING.1188 if not default:1189 return None11901138 if isinstance(ty, tuple):1139 return Tuple(ty)1191 item = default[0]11921141 if isinstance(ty, ParamType):1142 return ty1193 # A sequence of iterables needs to detect the inner types.1194 # Can't call convert_type recursively because that would1195 # incorrectly unwind the tuple to a single type.1196 if isinstance(item, (tuple, list)):1197 return tuple(map(type, item))11981144 if ty is str or ty is None:1199 return type(item)120012011202@t.overload1203def convert_type(ty: None, default: None = None) -> StringParamType: ...120412051206@t.overload1207def convert_type(1208 ty: type[t.Any] | ParamType[t.Any], default: t.Any | None = None1209) -> ParamType[t.Any]: ...121012111212@t.overload1213def convert_type(1214 ty: t.Any | None, default: t.Any | None = None1215) -> ParamType[t.Any]: ...121612171218def convert_type(1219 ty: t.Any | None = None, default: t.Any | None = None1220) -> ParamType[t.Any]:1221 """Find the most appropriate :class:`ParamType` for the given Python1222 type. If the type isn't provided, it can be inferred from a default1223 value.1224 """1225 guessed = _guess_type(ty, default)1226 is_guessed = guessed is not ty12271228 if isinstance(guessed, tuple):1229 return Tuple(guessed)12301231 if isinstance(guessed, ParamType):1232 return guessed12331234 if guessed is str or guessed is None:1235 return STRING12361147 if ty is int:1237 if guessed is int:1238 return INT12391150 if ty is float:1240 if guessed is float:1241 return FLOAT12421153 if ty is bool:1243 if guessed is bool:1244 return BOOL12451156 if guessed_type:1246 if is_guessed:1247 return STRING12481249 if __debug__:1250 try:1161 if issubclass(ty, ParamType):1251 if issubclass(guessed, ParamType):1252 raise AssertionError(1163 f"Attempted to use an uninstantiated parameter type ({ty})."1253 f"Attempted to use an uninstantiated parameter type ({guessed})."1254 )1255 except TypeError:1166 # ty is an instance (correct), so issubclass fails.1256 # guessed is an instance (correct), so issubclass fails.1257 pass12581169 return FuncParamType(ty)1259 return FuncParamType(guessed)126012611262#: A dummy parameter type that just does nothing. From a user's1263#: perspective this appears to just be the same as `STRING` but
36 unmodified lines
modified:src/click/utils.py+18 added-7 removed
4 unmodified lines
5import re6import sys7import typing as t8from functools import update_wrapper9from gettext import gettext as _10from types import ModuleType11from types import TracebackType1213from ._compat import _default_text_stderr
102 unmodified lines
116 filename parameter does make sense. This is useful for safely opening117 files for writing.118 """119120 name: str121 mode: str122 encoding: str | None123 errors: str | None124 atomic: bool125 _f: t.IO[t.Any] | None126 should_close: bool127128 def __init__(129 self,130 filename: str | os.PathLike[str],131 mode: str = "r",132 encoding: str | None = None,133 errors: str | None = "strict",134 atomic: bool = False,126 ):127 self.name: str = os.fspath(filename)135 ) -> None:136 self.name = os.fspath(filename)137 self.mode = mode138 self.encoding = encoding139 self.errors = errors140 self.atomic = atomic132 self._f: t.IO[t.Any] | None133 self.should_close: bool141142 if self.name == "-":143 self._f, self.should_close = open_stream(filename, mode, encoding, errors)144 else:
59 unmodified lines
204 return iter(self._f) # type: ignore205206207class KeepOpenFile:208 _file: t.IO[t.Any]209210 def __init__(self, file: t.IO[t.Any]) -> None:202 self._file: t.IO[t.Any] = file211 self._file = file212213 def __getattr__(self, name: str) -> t.Any:214 return getattr(self._file, name)215
125 unmodified lines
341 ``'stdout'`` and ``'stderr'``342 """343 opener = binary_streams.get(name)344 if opener is None:336 raise TypeError(f"Unknown standard stream '{name}'")345 raise TypeError(_("Unknown standard stream '{name}'").format(name=name))346 return opener()347348349def get_text_stream(
12 unmodified lines
362 :param errors: overrides the default error mode.363 """364 opener = text_streams.get(name)365 if opener is None:357 raise TypeError(f"Unknown standard stream '{name}'")366 raise TypeError(_("Unknown standard stream '{name}'").format(name=name))367 return opener(encoding, errors)368369370def open_file(
144 unmodified lines
515 other cleanup code, and the case where the underlying file is not a broken516 pipe, all calls and attributes are proxied.517 """518519 wrapped: t.IO[t.Any]520521 def __init__(self, wrapped: t.IO[t.Any]) -> None:522 self.wrapped = wrapped523524 def flush(self) -> None:
117 unmodified lines
modified:tests/test_commands.py+32 added
571 unmodified lines
572 rv = runner.invoke(cli, standalone_mode=False)573 assert rv.exit_code == 1574 assert isinstance(rv.exception.__cause__, exc)575 assert rv.exception.__cause__.args == ("catch me!",)576577578def test_unknown_command(runner):579 result = runner.invoke(click.Group(), "unknown")580 assert result.exception581 assert "No such command 'unknown'." in result.output582583584@pytest.mark.parametrize(585 ("value", "expect"),586 [587 ("pause", "Did you mean 'push'?"),588 ("decline", "(Did you mean one of: 'declare', 'refine'?)"),589 ],590)591def test_suggest_possible_commands(runner, value, expect):592 cli = click.Group()593594 @cli.command()595 def push():596 pass597598 @cli.command()599 def declare():600 pass601602 @cli.command()603 def refine():604 pass605606 result = runner.invoke(cli, [value])607 assert expect in result.output
modified:tests/test_compat.py+47 added-2 removed
1from click._compat import should_strip_ansi1from __future__ import annotations23import sys45import pytest67import click8910def test_is_jupyter_kernel_output():11 class JupyterKernelFakeStream:12 pass1314 # implementation detail, aka cheapskate test15 JupyterKernelFakeStream.__module__ = "ipykernel.faked"10 assert not should_strip_ansi(stream=JupyterKernelFakeStream())16 assert click._compat._is_jupyter_kernel_output(stream=JupyterKernelFakeStream())171819@pytest.mark.parametrize(20 "stream",21 [None, sys.stdin, sys.stderr, sys.stdout],22)23@pytest.mark.parametrize(24 ("color", "expected_override"),25 [26 (True, False),27 (False, True),28 (None, None),29 ],30)31@pytest.mark.parametrize(32 ("isatty", "is_jupyter", "expected"),33 [34 (True, False, False),35 (False, True, False),36 (False, False, True),37 ],38)39def test_should_strip_ansi(40 monkeypatch,41 stream,42 color: bool | None,43 expected_override: bool | None,44 isatty: bool,45 is_jupyter: bool,46 expected: bool,47) -> None:48 monkeypatch.setattr(click._compat, "isatty", lambda x: isatty)49 monkeypatch.setattr(50 click._compat, "_is_jupyter_kernel_output", lambda x: is_jupyter51 )5253 if expected_override is not None:54 expected = expected_override55 assert click._compat.should_strip_ansi(stream=stream, color=color) == expected
modified:tests/test_defaults.py+37 added
355 unmodified lines
356 assert result.exit_code == 0357 assert result.output == repr(expected)358359360@pytest.mark.parametrize(361 ("default_map", "option_kwargs", "cli_args", "expected"),362 [363 # String is split for nargs=2 option.364 ({"point": "3 4"}, {"nargs": 2, "type": int}, [], (3, 4)),365 # String is split for explicit Tuple type.366 ({"point": "hello world"}, {"type": (str, str)}, [], ("hello", "world")),367 # Already-structured tuple passes through unchanged.368 ({"point": ("a", "b")}, {"nargs": 2}, [], ("a", "b")),369 # Already-structured list passes through unchanged.370 ({"point": [5, 6]}, {"nargs": 2, "type": int}, [], (5, 6)),371 # CLI args override default_map for nargs > 1.372 (373 {"point": "3 4"},374 {"nargs": 2, "type": int},375 ["--point", "10", "20"],376 (10, 20),377 ),378 ],379)380def test_default_map_nargs(runner, default_map, option_kwargs, cli_args, expected):381 """A string in ``default_map`` for an option with ``nargs > 1`` should be382 split the same way an environment variable string is split.383384 Regression test for https://github.com/pallets/click/issues/2745.385 """386387 @click.command()388 @click.option("--point", **option_kwargs)389 def cli(point):390 click.echo(repr(point))391392 result = runner.invoke(cli, cli_args, default_map=default_map)393 assert result.exit_code == 0394 assert result.output.strip() == repr(expected)395396397def test_unset_in_default_map(runner):398 """An ``UNSET`` value in ``default_map`` should be treated as if399 the key is absent, and so fallback to the parameter's own default.400
13 unmodified lines
modified:tests/test_formatting.py+248 added
1import pytest23import click4from click._compat import strip_ansi567def test_basic_functionality(runner):8 @click.command()
239 unmodified lines
248 "Error: Missing argument 'ARG'.",249 ]250251252@pytest.mark.parametrize(253 ("help_names", "extra_options", "expected_hint"),254 [255 # No shadowing, longest name is picked.256 (["-h", "--help"], [], "Try 'cli foo --help' for help."),257 # -h shadowed by a subcommand option, --help still available.258 (259 ["-h", "--help"],260 [click.option("--host", "-h")],261 "Try 'cli foo --help' for help.",262 ),263 # --help shadowed, -h still available.264 (265 ["-h", "--help"],266 [click.option("--help-file", "--help")],267 "Try 'cli foo -h' for help.",268 ),269 # Both names shadowed: no hint line at all.270 (271 ["-h", "--help"],272 [click.option("--host", "-h"), click.option("--help-file", "--help")],273 None,274 ),275 # Single custom help name, not shadowed.276 (["--man"], [], "Try 'cli foo --man' for help."),277 # Three help names, one shadowed, longest survivor picked.278 (279 ["-h", "--help", "--info"],280 [click.option("--info-file", "--info")],281 "Try 'cli foo --help' for help.",282 ),283 ],284)285def test_formatting_usage_error_help_hint(286 runner, help_names, extra_options, expected_hint287):288 """The error hint should only show non-shadowed help option names,289 picking the longest for readability.290291 https://github.com/pallets/click/issues/2790292 """293294 @click.group(context_settings={"help_option_names": help_names})295 def cli():296 pass297298 @cli.command()299 @click.argument("required_arg")300 def foo(required_arg, **kwargs):301 pass302303 for option in extra_options:304 option(foo)305306 result = runner.invoke(cli, ["foo"])307 assert result.exit_code == 2308 lines = result.output.splitlines()309 assert lines[0] == "Usage: cli foo [OPTIONS] REQUIRED_ARG"310 assert lines[-1] == "Error: Missing argument 'REQUIRED_ARG'."311 if expected_hint is not None:312 assert expected_hint in lines313 else:314 assert not any(line.startswith("Try ") for line in lines)315316317def test_formatting_custom_type_metavar(runner):318 class MyType(click.ParamType):319 def get_metavar(self, param: click.Parameter, ctx: click.Context):320 return "MY_TYPE"
112 unmodified lines
433 formatter.write_text(text)434 actual = formatter.getvalue()435 expected = " Lorem ipsum dolor sit amet,\n consectetur adipiscing elit\n"436 assert actual == expected437438439@pytest.mark.parametrize(440 ("body", "width", "initial_indent"),441 [442 # Styled ``initial_indent`` must be measured by visible width, so the443 # ``Usage:`` prefix shouldn't push ``[OPTIONS]`` to the second line.444 # Regression for the asymmetry between ``HelpFormatter.write_usage``445 # (which sized the prefix with ``term_len``) and ``wrap_text``446 # (which previously used raw ``len``).447 pytest.param(448 "[OPTIONS]",449 30,450 "\x1b[38;2;38;139;210m\x1b[1mUsage:\x1b[0m ",451 id="styled-initial-indent-does-not-break-body",452 ),453 # Styled chunks in the body itself wrap on visible width.454 pytest.param(455 "\x1b[31malpha\x1b[0m \x1b[31mbeta\x1b[0m"456 " \x1b[31mgamma\x1b[0m \x1b[31mdelta\x1b[0m",457 15,458 "",459 id="styled-body-wraps-on-visible-width",460 ),461 # ``_handle_long_word`` cuts a styled token between visible462 # characters; the ANSI escape sequence must not be split.463 pytest.param(464 "\x1b[31mabcdefghij\x1b[0m",465 5,466 "",467 id="styled-long-word-breaks-on-visible-width",468 ),469 ],470)471def test_wrap_text_visible_width(body, width, initial_indent):472 """``wrap_text`` of styled input produces the same line layout as473 ``wrap_text`` of the ANSI-stripped input.474475 ANSI escape bytes must not count toward the width budget, regardless476 of whether they appear in the body, in ``initial_indent``, or when a477 styled token has to be broken in the middle.478 """479 styled = click.formatting.wrap_text(480 body, width=width, initial_indent=initial_indent481 )482 plain = click.formatting.wrap_text(483 strip_ansi(body), width=width, initial_indent=strip_ansi(initial_indent)484 )485486 styled_visible = [strip_ansi(line) for line in styled.splitlines()]487 assert styled_visible == plain.splitlines()488489490def test_write_usage_styled_prefix_keeps_options_on_one_line():491 """End-to-end: a downstream-styled ``Usage:`` prefix should not split492 ``[OPTIONS]`` across two lines.493 """494 styled_prefix = "\x1b[38;2;38;139;210m\x1b[1mUsage:\x1b[0m "495496 formatter = click.HelpFormatter(width=40)497 formatter.write_usage("cli", "[OPTIONS]", prefix=styled_prefix)498 rendered = formatter.getvalue()499500 visible = strip_ansi(rendered)501 assert visible == "Usage: cli [OPTIONS]\n"502503504@pytest.mark.parametrize(505 ("formatter_kwargs", "current_indent", "prog", "args", "prefix", "expected"),506 [507 # Issue #3360: the default prefix used to emit only508 # a blank line because ``wrap_text("", initial_indent=usage_prefix)``509 # returned ``""`` and discarded the prefix.510 pytest.param(511 {},512 0,513 "Program",514 "",515 None,516 "Usage: Program\n",517 id="empty-args-default-prefix",518 ),519 # A caller-supplied prefix is preserved verbatim.520 pytest.param(521 {},522 0,523 "Program",524 "",525 "Run: ",526 "Run: Program\n",527 id="empty-args-custom-prefix",528 ),529 # ``current_indent`` is preserved even with no args to render.530 pytest.param(531 {},532 4,533 "Program",534 "",535 None,536 "Usage: Program\n",537 id="empty-args-indented",538 ),539 # Prog too long to share a line with args: the wrap branch must not540 # emit a second line.541 pytest.param(542 {"width": 20},543 0,544 "VeryLongProgramName",545 "",546 None,547 "Usage: VeryLongProgramName\n",548 id="empty-args-long-prog",549 ),550 # With non-empty args, the separator space between prog and args is preserved.551 pytest.param(552 {},553 0,554 "Program",555 "[OPTIONS]",556 None,557 "Usage: Program [OPTIONS]\n",558 id="with-args-default-prefix",559 ),560 ],561)562def test_help_formatter_write_usage(563 formatter_kwargs, current_indent, prog, args, prefix, expected564):565 """``HelpFormatter.write_usage`` renders a single usage line whose566 trailing separator tracks whether ``args`` is non-empty.567 """568 f = click.HelpFormatter(**formatter_kwargs)569 f.current_indent = current_indent570 if prefix is None:571 f.write_usage(prog, args)572 else:573 f.write_usage(prog, args, prefix=prefix)574 assert f.getvalue() == expected575576577def test_help_formatter_write_usage_without_args_styled_prefix():578 """A downstream-styled prefix is preserved when ``args`` is empty:579 the ANSI escape sequences survive, only the trailing separator is580 removed.581 """582 styled_prefix = "\x1b[38;2;38;139;210m\x1b[1mUsage:\x1b[0m "583 f = click.HelpFormatter()584 f.write_usage("cli", prefix=styled_prefix)585 rendered = f.getvalue()586 assert strip_ansi(rendered) == "Usage: cli\n"587 assert "\x1b[" in rendered588589590@pytest.mark.parametrize(591 ("command_kwargs", "expected_usage_line"),592 [593 # End-to-end regression for #3360: an empty ``options_metavar`` with594 # no parameters used to render a blank usage line.595 pytest.param(596 {"options_metavar": ""},597 "Usage: cli",598 id="empty-options-metavar-no-params",599 ),600 # End-to-end regression: ``options_metavar=None`` is the documented601 # way to suppress the ``[OPTIONS]`` slot entirely.602 pytest.param(603 {"options_metavar": None},604 "Usage: cli",605 id="none-options-metavar-no-params",606 ),607 ],608)609def test_command_write_usage_no_args(runner, command_kwargs, expected_usage_line):610 """End-to-end: a command with no parameters and an empty or absent611 ``options_metavar`` renders a usage line with just the program name,612 no trailing space.613 """614 cli = click.Command("cli", **command_kwargs)615 result = runner.invoke(cli, ["--help"])616 assert result.output.splitlines()[0] == expected_usage_line
modified:tests/test_imports.py+2 added
25 unmodified lines
26"""2728ALLOWED_IMPORTS = {29 "__future__",30 "abc",31 "codecs",32 "collections",33 "collections.abc",34 "configparser",
14 unmodified lines
49 "sys",50 "threading",51 "types",52 "typing",53 "uuid",54 "weakref",55}5657if WIN:
23 unmodified lines
modified:tests/test_options.py+887 added-21 removed
139 unmodified lines
140 pass141142 result = runner.invoke(cli, [unknown_flag])143 assert result.exception144 assert f"No such option: {unknown_flag}" in result.output144 assert f"No such option '{unknown_flag}'." in result.output145146147@pytest.mark.parametrize(148 ("value", "expect"),149 [150 ("--cat", "Did you mean --count?"),151 ("--bounds", "(Possible options: --bound, --count)"),152 ("--bount", "(Possible options: --bound, --count)"),150 ("--cat", "Did you mean '--count'?"),151 ("--bounds", "(Did you mean one of: '--bound', '--count'?)"),152 ("--bount", "(Did you mean one of: '--bound', '--count'?)"),153 ],154)155def test_suggest_possible_options(runner, value, expect):156 cli = click.Command(
1248 unmodified lines
1405 param = click.Option(["-a", "x"], default=True, flag_value=4)1406 assert param.type is click.INT1407 param = click.Option(["-b", "x"], flag_value=8)1408 assert param.type is click.INT1409 # Non-basic types auto-detect as UNPROCESSED to avoid stringification.1410 param = click.Option(["-c", "x"], flag_value=EngineType.OSS)1411 assert param.type is click.UNPROCESSED1412 param = click.Option(["-d", "x"], flag_value=frozenset())1413 assert param.type is click.UNPROCESSED141414151416@pytest.mark.parametrize(1417 ("opt_params", "args", "expected"),
713 unmodified lines
2131 {"type": EngineType, "flag_value": EngineType.OSS, "default": True},2132 [],2133 EngineType.OSS,2134 ),2130 # Type is not specified and default to string, so the default value is2131 # returned as a string, even if it is a boolean. Also, defaults to the2132 # flag_value instead of the default value to support legacy behavior.2135 # Type is not specified. For string flag_value, STRING type is used and2136 # the default value is converted to string. For non-basic types (like2137 # enums), UNPROCESSED is used and values pass through unchanged.2138 ({"flag_value": "1", "default": True}, [], "1"),2139 ({"flag_value": "1", "default": 42}, [], "42"),2135 ({"flag_value": EngineType.OSS, "default": True}, [], "EngineType.OSS"),2136 ({"flag_value": EngineType.OSS, "default": 42}, [], "42"),2140 ({"flag_value": EngineType.OSS, "default": True}, [], EngineType.OSS),2141 ({"flag_value": EngineType.OSS, "default": 42}, [], 42),2142 # See: the result is the same if we force the type to be str.2143 ({"type": str, "flag_value": 1, "default": True}, [], "1"),2144 ({"type": str, "flag_value": 1, "default": 42}, [], "42"),2145 ({"type": str, "flag_value": "1", "default": True}, [], "1"),
57 unmodified lines
2203 {"flag_value": EngineType.PRO, "type": UNPROCESSED},2204 ["--opt2"],2205 EngineType.PRO,2206 ),2202 # Check that passing exotic flag values like classes is supported, but are2203 # rendered to strings when the type is not specified.2207 # Exotic flag values like classes are passed through unchanged when no2208 # explicit type is given (UNPROCESSED is auto-detected).2209 # https://github.com/pallets/click/issues/20122210 # https://github.com/pallets/click/issues/31212211 (2212 {"flag_value": Class1, "default": True},2213 {"flag_value": Class2},2214 [],2209 "<class 'test_options.Class1'>",2215 Class1,2216 ),2217 (2218 {"flag_value": Class1, "default": True},2219 {"flag_value": Class2},2220 ["--opt1"],2215 "<class 'test_options.Class1'>",2221 Class1,2222 ),2223 (2224 {"flag_value": Class1, "default": True},2225 {"flag_value": Class2},2226 ["--opt2"],2221 "<class 'test_options.Class2'>",2227 Class2,2228 ),2223 # Even the default is processed as a string.2229 # String and None defaults pass through unchanged.2230 ({"flag_value": Class1, "default": "True"}, {"flag_value": Class2}, [], "True"),2231 ({"flag_value": Class1, "default": None}, {"flag_value": Class2}, [], None),2232 # To get the classes as-is, we need to specify the type as UNPROCESSED.2233 # https://github.com/pallets/click/issues/3121
16 unmodified lines
2250 Class2,2251 ),2252 # Setting the default to a class, an instance of the class is returned instead2253 # of the class itself, because the default is allowed to be callable (and2248 # consummd). And this happens whatever the type is.2254 # consumed). And this happens whatever the type is.2255 (2256 {"flag_value": Class1, "default": Class1},2257 {"flag_value": Class2},2258 [],2253 re.compile(r"'<test_options.Class1 object at 0x[0-9A-Fa-f]+>'"),2259 re.compile(r"<test_options.Class1 object at 0x[0-9A-Fa-f]+>"),2260 ),2261 (2262 {"flag_value": Class1, "default": Class2},2263 {"flag_value": Class2},2264 [],2259 re.compile(r"'<test_options.Class2 object at 0x[0-9A-Fa-f]+>'"),2265 re.compile(r"<test_options.Class2 object at 0x[0-9A-Fa-f]+>"),2266 ),2267 (2268 {"flag_value": Class1, "type": UNPROCESSED, "default": Class1},2269 {"flag_value": Class2, "type": UNPROCESSED},
57 unmodified lines
2327 {"flag_value": Class1, "type": UNPROCESSED, "default": True},2328 ["--opt"],2329 Class1,2330 ),2325 # Without UNPROCESSED, the class is str()-ified by the default STRING type.2326 ({"flag_value": Class1, "default": True}, [], "<class 'test_options.Class1'>"),2331 # Without explicit UNPROCESSED, the class still passes through unchanged2332 # because UNPROCESSED is auto-detected for non-basic flag_value types.2333 ({"flag_value": Class1, "default": True}, [], Class1),2334 (2335 {"flag_value": Class1, "default": True},2336 ["--opt"],2330 "<class 'test_options.Class1'>",2337 Class1,2338 ),2339 # Explicit default=Class1 (not via default=True alignment): callable IS invoked,2340 # because the user explicitly set a callable as the default.2341 (
137 unmodified lines
2479 ctx = click.Context(cli)2480 assert opt.get_default(ctx, call=True) is expected_get_default248124822483def test_flag_value_not_stringified_for_custom_types(runner):2484 """Non-basic flag_value types are passed through unchanged without2485 requiring ``type=click.UNPROCESSED``.24862487 Regression test for https://github.com/pallets/click/issues/20122488 """24892490 @click.command()2491 @click.option("--cls1", "config_cls", flag_value=Class1, default=True)2492 @click.option("--cls2", "config_cls", flag_value=Class2)2493 def cli(config_cls):2494 click.echo(repr(config_cls), nl=False)24952496 # Default activates --cls1 (default=True resolves to flag_value).2497 result = runner.invoke(cli, [])2498 assert result.exit_code == 02499 assert result.output == repr(Class1)25002501 result = runner.invoke(cli, ["--cls1"])2502 assert result.exit_code == 02503 assert result.output == repr(Class1)25042505 result = runner.invoke(cli, ["--cls2"])2506 assert result.exit_code == 02507 assert result.output == repr(Class2)25082509 # Enum flag_value without explicit type is also preserved.2510 @click.command()2511 @click.option("--oss", "engine", flag_value=EngineType.OSS, default=True)2512 @click.option("--pro", "engine", flag_value=EngineType.PRO)2513 def cli2(engine):2514 click.echo(repr(engine), nl=False)25152516 result = runner.invoke(cli2, [])2517 assert result.exit_code == 02518 assert result.output == repr(EngineType.OSS)25192520 result = runner.invoke(cli2, ["--pro"])2521 assert result.exit_code == 02522 assert result.output == repr(EngineType.PRO)252325242525def test_custom_type_frozenset_flag_value(runner):2526 """Check that frozenset is correctly handled as a type, a flag value and a default.25272528 Reproduces https://github.com/pallets/click/issues/2610
52 unmodified lines
2581 assert result.output == repr(expected)258225832584@pytest.mark.parametrize(2585 ("opts", "args", "expected"),2586 [2587 # #3403 reproducer: enable/disable pair with explicit ``default=True``2588 # on the positive flag, declared after (inner decorator) the negative.2589 # https://github.com/pallets/click/issues/34032590 pytest.param(2591 [2592 ("--without-xyz", {"flag_value": False}),2593 ("--with-xyz", {"flag_value": True, "default": True}),2594 ],2595 [],2596 True,2597 id="3403-reproducer-no-args",2598 ),2599 pytest.param(2600 [2601 ("--without-xyz", {"flag_value": False}),2602 ("--with-xyz", {"flag_value": True, "default": True}),2603 ],2604 ["--with-xyz"],2605 True,2606 id="3403-reproducer-with-only",2607 ),2608 pytest.param(2609 [2610 ("--without-xyz", {"flag_value": False}),2611 ("--with-xyz", {"flag_value": True, "default": True}),2612 ],2613 ["--without-xyz"],2614 False,2615 id="3403-reproducer-without-only",2616 ),2617 # When both flags are passed, the parser keeps the last value seen.2618 pytest.param(2619 [2620 ("--without-xyz", {"flag_value": False}),2621 ("--with-xyz", {"flag_value": True, "default": True}),2622 ],2623 ["--with-xyz", "--without-xyz"],2624 False,2625 id="3403-reproducer-with-then-without",2626 ),2627 pytest.param(2628 [2629 ("--without-xyz", {"flag_value": False}),2630 ("--with-xyz", {"flag_value": True, "default": True}),2631 ],2632 ["--without-xyz", "--with-xyz"],2633 True,2634 id="3403-reproducer-without-then-with",2635 ),2636 # Order-independence: explicit ``default=True`` on the OUTER2637 # decorator (declared first) must produce the same behavior.2638 pytest.param(2639 [2640 ("--with-xyz", {"flag_value": True, "default": True}),2641 ("--without-xyz", {"flag_value": False}),2642 ],2643 [],2644 True,2645 id="explicit-default-outer-no-args",2646 ),2647 pytest.param(2648 [2649 ("--with-xyz", {"flag_value": True, "default": True}),2650 ("--without-xyz", {"flag_value": False}),2651 ],2652 ["--without-xyz"],2653 False,2654 id="explicit-default-outer-cmdline-overrides",2655 ),2656 # Explicit ``default=False`` on the negative flag wins over the2657 # auto-derived default of the positive one. Result value is False2658 # either way, but the assertion still guards source tracking.2659 pytest.param(2660 [2661 ("--with-xyz", {"flag_value": True}),2662 ("--without-xyz", {"flag_value": False, "default": False}),2663 ],2664 [],2665 False,2666 id="explicit-default-false-on-negative",2667 ),2668 # Explicit ``default=True`` on the negative flag is unusual but2669 # legal: post-#3239, it is a literal Python value, not a sentinel.2670 pytest.param(2671 [2672 ("--with-xyz", {"flag_value": True}),2673 ("--without-xyz", {"flag_value": False, "default": True}),2674 ],2675 [],2676 True,2677 id="explicit-default-true-on-negative",2678 ),2679 # Both options carry an explicit default: last-wins, so the option2680 # declared last in the source code keeps the slot. Confirms the2681 # explicit-beats-auto tie-break does not also promote first-declared2682 # over a later explicit default.2683 pytest.param(2684 [2685 ("--with-xyz", {"flag_value": True, "default": True}),2686 ("--without-xyz", {"flag_value": False, "default": False}),2687 ],2688 [],2689 False,2690 id="both-explicit-defaults-last-wins",2691 ),2692 pytest.param(2693 [2694 ("--without-xyz", {"flag_value": False, "default": False}),2695 ("--with-xyz", {"flag_value": True, "default": True}),2696 ],2697 [],2698 True,2699 id="both-explicit-defaults-last-wins-swapped",2700 ),2701 # No option has an explicit default: every boolean flag2702 # auto-derives ``default=False`` regardless of its ``flag_value``,2703 # so the slot is False either way. Last-wins applies under the hood2704 # but is not observable because both values are equal.2705 pytest.param(2706 [2707 ("--with-xyz", {"flag_value": True}),2708 ("--without-xyz", {"flag_value": False}),2709 ],2710 [],2711 False,2712 id="both-auto-defaults-positive-first",2713 ),2714 pytest.param(2715 [2716 ("--without-xyz", {"flag_value": False}),2717 ("--with-xyz", {"flag_value": True}),2718 ],2719 [],2720 False,2721 id="both-auto-defaults-negative-first",2722 ),2723 # Explicit ``default=False`` matching the auto-derived value:2724 # the explicit option still wins the slot. Confirms tracking is2725 # source-based and not value-based.2726 pytest.param(2727 [2728 ("--with-xyz", {"flag_value": True, "default": False}),2729 ("--without-xyz", {"flag_value": False}),2730 ],2731 [],2732 False,2733 id="explicit-default-matches-auto-still-wins",2734 ),2735 # Three-flag group: the explicit default wins regardless of its2736 # position in the decorator stack.2737 pytest.param(2738 [2739 ("--auto-a", {"flag_value": True}),2740 ("--explicit", {"flag_value": False, "default": False}),2741 ("--auto-b", {"flag_value": True}),2742 ],2743 [],2744 False,2745 id="three-flags-explicit-in-middle",2746 ),2747 pytest.param(2748 [2749 ("--auto-a", {"flag_value": True}),2750 ("--auto-b", {"flag_value": False}),2751 ("--explicit", {"flag_value": True, "default": True}),2752 ],2753 [],2754 True,2755 id="three-flags-explicit-last",2756 ),2757 pytest.param(2758 [2759 ("--explicit", {"flag_value": False, "default": False}),2760 ("--auto-a", {"flag_value": True}),2761 ("--auto-b", {"flag_value": True}),2762 ],2763 [],2764 False,2765 id="three-flags-explicit-first",2766 ),2767 # Three-state pattern: explicit ``default=None`` on one option2768 # must beat a sibling's auto-derived ``False``.2769 pytest.param(2770 [2771 ("--without-xyz", {"flag_value": False}),2772 ("--with-xyz", {"flag_value": True, "default": None}),2773 ],2774 [],2775 None,2776 id="explicit-default-none-three-state",2777 ),2778 pytest.param(2779 [2780 ("--without-xyz", {"flag_value": False}),2781 ("--with-xyz", {"flag_value": True, "default": None}),2782 ],2783 ["--with-xyz"],2784 True,2785 id="explicit-default-none-three-state-with",2786 ),2787 pytest.param(2788 [2789 ("--without-xyz", {"flag_value": False}),2790 ("--with-xyz", {"flag_value": True, "default": None}),2791 ],2792 ["--without-xyz"],2793 False,2794 id="explicit-default-none-three-state-without",2795 ),2796 # Command-line input always beats any default, regardless of2797 # which option carried the explicit default.2798 pytest.param(2799 [2800 ("--with-xyz", {"flag_value": True, "default": True}),2801 ("--without-xyz", {"flag_value": False}),2802 ],2803 ["--without-xyz"],2804 False,2805 id="cmdline-beats-explicit-default",2806 ),2807 pytest.param(2808 [2809 ("--without-xyz", {"flag_value": False, "default": False}),2810 ("--with-xyz", {"flag_value": True}),2811 ],2812 ["--with-xyz"],2813 True,2814 id="cmdline-beats-explicit-default-symmetric",2815 ),2816 ],2817)2818def test_bool_flag_group_competition(runner, opts, args, expected):2819 """Competing boolean flags sharing a single parameter name.28202821 Verifies the arbitration rules between options that target the same2822 variable name in a feature-switch group.28232824 Regression test for https://github.com/pallets/click/issues/34032825 """28262827 @click.command()2828 def cli(enable_xyz):2829 click.echo(repr(enable_xyz), nl=False)28302831 for opt_name, opt_kwargs in opts:2832 cli = click.option(opt_name, "enable_xyz", **opt_kwargs)(cli)28332834 result = runner.invoke(cli, args)2835 assert result.exit_code == 0, result.output2836 assert result.output == repr(expected)283728382839@pytest.mark.parametrize(2840 ("envvar_value", "args", "expected"),2841 [2842 # An env var on one option in the group provides ENVIRONMENT source,2843 # which beats any sibling's DEFAULT regardless of explicit-default.2844 ("1", [], True),2845 ("0", [], False),2846 # Command-line still beats the env var.2847 ("0", ["--with-xyz"], True),2848 ("1", ["--without-xyz"], False),2849 ],2850)2851def test_bool_flag_group_competition_with_envvar(2852 runner, monkeypatch, envvar_value, args, expected2853):2854 monkeypatch.setenv("XYZ", envvar_value)28552856 @click.command()2857 @click.option("--without-xyz", "enable_xyz", flag_value=False)2858 @click.option(2859 "--with-xyz",2860 "enable_xyz",2861 flag_value=True,2862 default=False,2863 envvar="XYZ",2864 )2865 def cli(enable_xyz):2866 click.echo(repr(enable_xyz), nl=False)28672868 result = runner.invoke(cli, args)2869 assert result.exit_code == 0, result.output2870 assert result.output == repr(expected)287128722873@pytest.mark.parametrize(2874 ("default_map", "args", "expected"),2875 [2876 # ``default_map`` provides DEFAULT_MAP source, beating either default.2877 ({"enable_xyz": True}, [], True),2878 ({"enable_xyz": False}, [], False),2879 # Command-line still beats default_map.2880 ({"enable_xyz": False}, ["--with-xyz"], True),2881 ({"enable_xyz": True}, ["--without-xyz"], False),2882 ],2883)2884def test_bool_flag_group_competition_with_default_map(2885 runner, default_map, args, expected2886):2887 @click.command()2888 @click.option("--without-xyz", "enable_xyz", flag_value=False)2889 @click.option("--with-xyz", "enable_xyz", flag_value=True, default=True)2890 def cli(enable_xyz):2891 click.echo(repr(enable_xyz), nl=False)28922893 result = runner.invoke(cli, args, default_map=default_map)2894 assert result.exit_code == 0, result.output2895 assert result.output == repr(expected)289628972898@pytest.mark.parametrize(2899 ("opts", "args", "expected"),2900 [2901 # Non-boolean feature switch group: classic --upper/--lower2902 # pattern. The option with ``default=True`` acts as the default2903 # via the substitution rule (#3239) for non-boolean ``flag_value``.2904 pytest.param(2905 [2906 ("--upper", {"flag_value": "upper", "default": True}),2907 ("--lower", {"flag_value": "lower"}),2908 ],2909 [],2910 "upper",2911 id="string-default-true-substitutes-to-flag-value",2912 ),2913 pytest.param(2914 [2915 ("--upper", {"flag_value": "upper", "default": True}),2916 ("--lower", {"flag_value": "lower"}),2917 ],2918 ["--upper"],2919 "upper",2920 id="string-default-true-cmdline-positive",2921 ),2922 pytest.param(2923 [2924 ("--upper", {"flag_value": "upper", "default": True}),2925 ("--lower", {"flag_value": "lower"}),2926 ],2927 ["--lower"],2928 "lower",2929 id="string-default-true-cmdline-overrides",2930 ),2931 # Explicit literal string default beats sibling's absent default.2932 # Confirms the explicit-beats-absent rule applies regardless of type.2933 pytest.param(2934 [2935 ("--upper", {"flag_value": "upper", "default": "lower"}),2936 ("--lower", {"flag_value": "lower"}),2937 ],2938 [],2939 "lower",2940 id="string-explicit-default-wins-over-absent",2941 ),2942 pytest.param(2943 [2944 ("--upper", {"flag_value": "upper"}),2945 ("--lower", {"flag_value": "lower", "default": "upper"}),2946 ],2947 [],2948 "upper",2949 id="string-explicit-default-wins-from-second-position",2950 ),2951 # Empty string as ``flag_value``: still a legal value, including2952 # under the ``default=True`` substitution rule.2953 pytest.param(2954 [2955 ("--empty", {"flag_value": "", "default": True}),2956 ("--filled", {"flag_value": "filled"}),2957 ],2958 [],2959 "",2960 id="empty-string-flag-value-default-true",2961 ),2962 pytest.param(2963 [2964 ("--empty", {"flag_value": "", "default": True}),2965 ("--filled", {"flag_value": "filled"}),2966 ],2967 ["--empty"],2968 "",2969 id="empty-string-flag-value-cmdline",2970 ),2971 # Empty string as ``default``: explicit empty string beats2972 # the sibling's absent default.2973 pytest.param(2974 [2975 ("--upper", {"flag_value": "upper", "default": ""}),2976 ("--lower", {"flag_value": "lower"}),2977 ],2978 [],2979 "",2980 id="empty-string-explicit-default",2981 ),2982 # ``flag_value=None`` is a legal flag value: when the option is2983 # activated, the function receives ``None``.2984 pytest.param(2985 [2986 ("--none", {"flag_value": None, "default": "fallback"}),2987 ("--other", {"flag_value": "other"}),2988 ],2989 [],2990 "fallback",2991 id="none-flag-value-default-fallback",2992 ),2993 pytest.param(2994 [2995 ("--none", {"flag_value": None, "default": "fallback"}),2996 ("--other", {"flag_value": "other"}),2997 ],2998 ["--none"],2999 None,3000 id="none-flag-value-cmdline-passes-none",3001 ),3002 pytest.param(3003 [3004 ("--none", {"flag_value": None, "default": "fallback"}),3005 ("--other", {"flag_value": "other"}),3006 ],3007 ["--other"],3008 "other",3009 id="none-flag-value-cmdline-passes-other",3010 ),3011 # Explicit ``default=None`` is a real value (not absence) and3012 # must beat a sibling's absent default. Three-state pattern for3013 # non-boolean flag groups.3014 pytest.param(3015 [3016 ("--upper", {"flag_value": "upper", "default": None}),3017 ("--lower", {"flag_value": "lower"}),3018 ],3019 [],3020 None,3021 id="explicit-default-none-three-state",3022 ),3023 pytest.param(3024 [3025 ("--upper", {"flag_value": "upper", "default": None}),3026 ("--lower", {"flag_value": "lower"}),3027 ],3028 ["--upper"],3029 "upper",3030 id="explicit-default-none-cmdline-upper",3031 ),3032 pytest.param(3033 [3034 ("--upper", {"flag_value": "upper", "default": None}),3035 ("--lower", {"flag_value": "lower"}),3036 ],3037 ["--lower"],3038 "lower",3039 id="explicit-default-none-cmdline-lower",3040 ),3041 # Passing ``default=UNSET`` explicitly is the same as not passing3042 # ``default`` at all, so the sibling's explicit default wins.3043 pytest.param(3044 [3045 ("--upper", {"flag_value": "upper", "default": UNSET}),3046 ("--lower", {"flag_value": "lower", "default": "lower"}),3047 ],3048 [],3049 "lower",3050 id="unset-default-equivalent-to-absent",3051 ),3052 pytest.param(3053 [3054 ("--upper", {"flag_value": "upper", "default": UNSET}),3055 ("--lower", {"flag_value": "lower", "default": "lower"}),3056 ],3057 ["--upper"],3058 "upper",3059 id="unset-default-cmdline-still-works",3060 ),3061 # Neither option has a default: the slot resolves to ``None``3062 # because non-boolean flags do not auto-derive a default.3063 pytest.param(3064 [3065 ("--upper", {"flag_value": "upper"}),3066 ("--lower", {"flag_value": "lower"}),3067 ],3068 [],3069 None,3070 id="non-boolean-no-defaults-resolves-to-none",3071 ),3072 pytest.param(3073 [3074 ("--upper", {"flag_value": "upper"}),3075 ("--lower", {"flag_value": "lower"}),3076 ],3077 ["--upper"],3078 "upper",3079 id="non-boolean-no-defaults-cmdline-still-works",3080 ),3081 # Three-flag string group: explicit default wins from any3082 # position in the decorator stack.3083 pytest.param(3084 [3085 ("--upper", {"flag_value": "upper"}),3086 ("--mixed", {"flag_value": "MiXeD", "default": "MiXeD"}),3087 ("--lower", {"flag_value": "lower"}),3088 ],3089 [],3090 "MiXeD",3091 id="three-flags-explicit-default-in-middle",3092 ),3093 pytest.param(3094 [3095 ("--upper", {"flag_value": "upper"}),3096 ("--lower", {"flag_value": "lower"}),3097 ("--default-choice", {"flag_value": "chosen", "default": True}),3098 ],3099 [],3100 "chosen",3101 id="three-flags-default-true-substitution-last",3102 ),3103 # Both options have explicit defaults: last-wins, so the option3104 # declared last keeps the slot, regardless of value type.3105 pytest.param(3106 [3107 ("--upper", {"flag_value": "upper", "default": "first"}),3108 ("--lower", {"flag_value": "lower", "default": "second"}),3109 ],3110 [],3111 "second",3112 id="both-explicit-defaults-string-last-wins",3113 ),3114 # Mixed boolean and non-boolean ``flag_value`` in the same group3115 # is allowed. Both options here carry an explicit default, so last-wins3116 # picks the option declared last regardless of value type. The boolean3117 # ``default=False`` is a literal value (post-#3239), not a sentinel.3118 pytest.param(3119 [3120 ("--bool-flag", {"flag_value": True, "default": False}),3121 ("--str-flag", {"flag_value": "named", "default": "explicit"}),3122 ],3123 [],3124 "explicit",3125 id="mixed-bool-and-string-last-wins",3126 ),3127 pytest.param(3128 [3129 ("--str-flag", {"flag_value": "named", "default": "explicit"}),3130 ("--bool-flag", {"flag_value": True, "default": False}),3131 ],3132 [],3133 False,3134 id="mixed-bool-and-string-last-wins-swapped",3135 ),3136 # Empty string default coexisting with ``default=True``3137 # substitution: ``default=""`` is explicit, ``default=True`` is also3138 # explicit (and substitutes to the option's ``flag_value``). Last-wins3139 # picks the option declared last.3140 pytest.param(3141 [3142 ("--upper", {"flag_value": "upper", "default": True}),3143 ("--blank", {"flag_value": "blank", "default": ""}),3144 ],3145 [],3146 "",3147 id="default-true-vs-empty-string-last-wins",3148 ),3149 pytest.param(3150 [3151 ("--blank", {"flag_value": "blank", "default": ""}),3152 ("--upper", {"flag_value": "upper", "default": True}),3153 ],3154 [],3155 "upper",3156 id="default-true-vs-empty-string-last-wins-swapped",3157 ),3158 ],3159)3160def test_flag_group_competition_non_boolean(runner, opts, args, expected):3161 """Same arbitration rules as :func:`test_bool_flag_group_competition`,3162 but for feature-switch groups with non-boolean ``flag_value``.3163 """31643165 @click.command()3166 def cli(case):3167 click.echo(repr(case), nl=False)31683169 for opt_name, opt_kwargs in opts:3170 cli = click.option(opt_name, "case", **opt_kwargs)(cli)31713172 result = runner.invoke(cli, args)3173 assert result.exit_code == 0, result.output3174 assert result.output == repr(expected)317531763177@pytest.mark.parametrize(3178 ("default_a", "default_b", "args", "expected"),3179 [3180 # ``default=UNSET`` and an absent ``default`` keyword must produce3181 # identical behavior. Both options here are bare boolean flags, so3182 # both auto-derive ``False`` and last-wins applies (``--a`` is3183 # processed last); the value is ``False`` either way.3184 (UNSET, UNSET, [], False),3185 # ``default=UNSET`` on one side, explicit on the other: the explicit3186 # one wins regardless of decorator order.3187 (UNSET, True, [], True),3188 (True, UNSET, [], True),3189 (UNSET, False, [], False),3190 (False, UNSET, [], False),3191 # ``default=None`` is a real value, distinct from ``UNSET``, and3192 # remains explicit even when the sibling carries an explicit3193 # boolean default (3-state).3194 (None, UNSET, [], None),3195 (UNSET, None, [], None),3196 # Explicit ``None`` competing with explicit boolean. The decorator3197 # order in this test puts ``--a`` last in ``params``, so the value3198 # carried by ``default_a`` wins these "both explicit" ties under3199 # last-wins.3200 (None, True, [], None),3201 (True, None, [], True),3202 ],3203)3204def test_flag_group_unset_vs_none_vs_explicit(3205 runner, default_a, default_b, args, expected3206):3207 """``UNSET`` as an explicit ``default`` must be indistinguishable from3208 omitting ``default`` entirely, while ``None`` is a real explicit value.3209 """3210 a_kwargs = {"flag_value": True}3211 if default_a is not UNSET:3212 a_kwargs["default"] = default_a3213 elif default_a is UNSET:3214 # Pass UNSET explicitly to verify it's treated as absent. Skip when3215 # the test wants the absent-keyword case (matches default behavior3216 # because ``Parameter.__init__`` defaults ``default`` to ``UNSET``).3217 a_kwargs["default"] = UNSET32183219 b_kwargs = {"flag_value": False}3220 if default_b is not UNSET:3221 b_kwargs["default"] = default_b3222 elif default_b is UNSET:3223 b_kwargs["default"] = UNSET32243225 @click.command()3226 @click.option("--b", "state", **b_kwargs)3227 @click.option("--a", "state", **a_kwargs)3228 def cli(state):3229 click.echo(repr(state), nl=False)32303231 result = runner.invoke(cli, args)3232 assert result.exit_code == 0, result.output3233 assert result.output == repr(expected)323432353236def test_flag_group_competition_duplicate_option_name(runner):3237 """The same option name declared twice on the same command is a user3238 error.3239 """32403241 @click.command()3242 @click.option("--xyz", default="first")3243 @click.option("--xyz", default="second")3244 def cli(xyz):3245 click.echo(repr(xyz), nl=False)32463247 result = runner.invoke(cli, [])3248 assert result.exit_code == 13249 assert isinstance(result.exception, UserWarning)3250 assert "used more than once" in str(result.exception)325132523253@pytest.mark.parametrize(3254 ("args", "expected"),3255 [3256 (["--with-xyz", "--with-xyz"], True),3257 (["--without-xyz", "--without-xyz"], False),3258 (["--with-xyz", "--without-xyz", "--with-xyz"], True),3259 (["--without-xyz", "--with-xyz", "--without-xyz"], False),3260 ],3261)3262def test_flag_group_competition_repeated_cmdline(runner, args, expected):3263 """Duplicate flags passed in different order to the CLI."""32643265 @click.command()3266 @click.option("--without-xyz", "enable_xyz", flag_value=False)3267 @click.option("--with-xyz", "enable_xyz", flag_value=True, default=True)3268 def cli(enable_xyz):3269 click.echo(repr(enable_xyz), nl=False)32703271 result = runner.invoke(cli, args)3272 assert result.exit_code == 0, result.output3273 assert result.output == repr(expected)327432753276@pytest.mark.parametrize(3277 ("opts", "args", "expected"),3278 [3279 pytest.param(3280 [3281 ("--a", {"flag_value": "a"}),3282 ("--b", {"flag_value": "b"}),3283 ("--c", {"flag_value": "c"}),3284 ("--d", {"flag_value": "d"}),3285 ],3286 [],3287 None,3288 id="four-flags-no-defaults-resolves-to-none",3289 ),3290 pytest.param(3291 [3292 ("--a", {"flag_value": "a"}),3293 ("--b", {"flag_value": "b", "default": "from-b"}),3294 ("--c", {"flag_value": "c"}),3295 ("--d", {"flag_value": "d"}),3296 ],3297 [],3298 "from-b",3299 id="four-flags-only-second-explicit-wins",3300 ),3301 pytest.param(3302 [3303 ("--a", {"flag_value": "a"}),3304 ("--b", {"flag_value": "b", "default": "from-b"}),3305 ("--c", {"flag_value": "c"}),3306 ("--d", {"flag_value": "d", "default": "from-d"}),3307 ],3308 [],3309 "from-d",3310 id="four-flags-two-explicit-last-wins",3311 ),3312 pytest.param(3313 [3314 ("--a", {"flag_value": "a"}),3315 ("--b", {"flag_value": "b"}),3316 ("--c", {"flag_value": "c"}),3317 ("--d", {"flag_value": "d"}),3318 ],3319 ["--c"],3320 "c",3321 id="four-flags-cmdline-beats-everything",3322 ),3323 ],3324)3325def test_flag_group_competition_four_flags(runner, opts, args, expected):3326 """Arbitration rules applies to groups of any size."""33273328 @click.command()3329 def cli(case):3330 click.echo(repr(case), nl=False)33313332 for opt_name, opt_kwargs in opts:3333 cli = click.option(opt_name, "case", **opt_kwargs)(cli)33343335 result = runner.invoke(cli, args)3336 assert result.exit_code == 0, result.output3337 assert result.output == repr(expected)333833393340@pytest.mark.parametrize(3341 ("env", "default_map", "args", "expected"),3342 [3343 # ``auto_envvar_prefix`` produces an ``ENVIRONMENT`` source through a3344 # different code path than an explicit ``envvar=`` keyword. It still3345 # must beat any sibling default and be beaten by command-line input.3346 pytest.param(3347 {"AUTO_ENABLE_XYZ": "1"},3348 None,3349 [],3350 True,3351 id="auto-envvar-prefix-beats-default",3352 ),3353 pytest.param(3354 {"AUTO_ENABLE_XYZ": "1"},3355 None,3356 ["--without-xyz"],3357 False,3358 id="auto-envvar-prefix-loses-to-cmdline",3359 ),3360 # ``Sentinel.UNSET`` in ``default_map`` must be skipped (#32243361 # carve-out): the lookup falls through to the parameter default.3362 # Inside a feature switch group, the explicit ``default=True`` on3363 # ``--with-xyz`` then wins over the sibling's auto-``False``.3364 pytest.param(3365 {},3366 {"enable_xyz": UNSET},3367 [],3368 True,3369 id="unset-default-map-falls-through-to-explicit-default",3370 ),3371 pytest.param(3372 {},3373 {"enable_xyz": False},3374 [],3375 False,3376 id="real-default-map-beats-explicit-default",3377 ),3378 ],3379)3380def test_flag_group_competition_envvar_prefix_and_unset_default_map(3381 runner, monkeypatch, env, default_map, args, expected3382):3383 for name, value in env.items():3384 monkeypatch.setenv(name, value)33853386 @click.command()3387 @click.option("--without-xyz", "enable_xyz", flag_value=False)3388 @click.option("--with-xyz", "enable_xyz", flag_value=True, default=True)3389 def cli(enable_xyz):3390 click.echo(repr(enable_xyz), nl=False)33913392 invoke_kwargs = {"auto_envvar_prefix": "AUTO"}3393 if default_map is not None:3394 invoke_kwargs["default_map"] = default_map33953396 result = runner.invoke(cli, args, **invoke_kwargs)3397 assert result.exit_code == 0, result.output3398 assert result.output == repr(expected)339934003401@pytest.mark.parametrize(3402 ("flag_type", "args", "expect_output"),3403 [3404 (str, [], "Default\n"),3405 (str, ["--theflag"], "FlagValue\n"),
36 unmodified lines
modified:tests/test_shell_completion.py+50 added-3 removed
355 unmodified lines
356 ("bash", {"COMP_WORDS": "", "COMP_CWORD": "0"}, "plain,a\nplain,b\n"),357 ("bash", {"COMP_WORDS": "a b", "COMP_CWORD": "1"}, "plain,b\n"),358 ("zsh", {"COMP_WORDS": "", "COMP_CWORD": "0"}, "plain\na\n_\nplain\nb\nbee\n"),359 ("zsh", {"COMP_WORDS": "a b", "COMP_CWORD": "1"}, "plain\nb\nbee\n"),360 ("fish", {"COMP_WORDS": "", "COMP_CWORD": ""}, "plain,a\nplain,b\tbee\n"),361 ("fish", {"COMP_WORDS": "a b", "COMP_CWORD": "b"}, "plain,b\tbee\n"),362 ("fish", {"COMP_WORDS": 'a "b', "COMP_CWORD": '"b'}, "plain,b\tbee\n"),360 ("fish", {"COMP_WORDS": "", "COMP_CWORD": ""}, "plain\na\n_\nplain\nb\nbee\n"),361 ("fish", {"COMP_WORDS": "a b", "COMP_CWORD": "b"}, "plain\nb\nbee\n"),362 ("fish", {"COMP_WORDS": 'a "b', "COMP_CWORD": '"b'}, "plain\nb\nbee\n"),363 ],364)365@pytest.mark.usefixtures("_patch_for_completion")366def test_full_complete(runner, shell, env, expect):
191 unmodified lines
558 with warnings.catch_warnings(record=True) as current_warnings:559 assert not current_warnings, "There should be no warnings to start"560 _get_completions(cli, args=[], incomplete="")561 assert not current_warnings, "There should be no warnings after either"562563564@pytest.mark.usefixtures("_patch_for_completion")565def test_fish_multiline_help_complete(runner):566 """Test Fish completion with multi-line help text doesn't cause errors."""567 cli = Command(568 "cli",569 params=[570 Option(571 ["--at", "--attachment-type"],572 type=(str, str),573 multiple=True,574 help=(575 "\b\nAttachment with explicit mimetype,\n--at image.jpg image/jpeg"576 ),577 ),578 Option(["--other"], help="Normal help"),579 ],580 )581582 result = runner.invoke(583 cli,584 env={585 "COMP_WORDS": "cli --",586 "COMP_CWORD": "--",587 "_CLI_COMPLETE": "fish_complete",588 },589 )590591 # Should not fail592 assert result.exit_code == 0593594 # Output should contain escaped newlines, not literal newlines595 # Fish expects: plain\n--at\n{help_with_\\n}596 lines = result.output.split("\n")597598 # Find the --at completion block (3 lines: type, value, help)599 for i in range(0, len(lines) - 2, 3):600 if lines[i] == "plain" and lines[i + 1] in ("--at", "--attachment-type"):601 help_line = lines[i + 2]602 # Help should have escaped newlines (\\n), not actual newlines603 assert "\\n" in help_line604 # Should contain the example text605 assert "image.jpg" in help_line.replace("\\n", " ")606 break607 else:608 pytest.fail("--at completion not found in output")
modified:tests/test_termui.py+484 added
1import contextlib2import io3import platform4import shlex5import shutil6import sys7import tempfile8import time9from unittest.mock import patch1011import pytest1213import click14import click._termui_impl15from click._compat import WIN16from click._termui_impl import Editor17from click._utils import UNSET
606 unmodified lines
624 """625 assert shlex.split(pager_env) == expected_parts626627628def _get_real_pager_command() -> str:629 """Return a real pager binary path used to exercise the pipe pager branch.630631 ..warning::632 Unix-only for now: ``more.com`` on Windows is interactive and goes633 through ``_tempfilepager`` rather than ``_pipepager``.634 """635 pager_path = shutil.which("cat")636 assert pager_path is not None, "cat not available"637 return pager_path638639640def _run_get_pager_file_with_real_pager(monkeypatch, capfd, writer, color=False):641 """Run through the pipe pager backend selected by ``PAGER``."""642 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)643 monkeypatch.setitem(644 click._termui_impl.os.environ, "PAGER", _get_real_pager_command()645 )646647 with click.get_pager_file(color=color) as pager:648 writer(pager)649650 # The real pager writes to the process stdout; stderr should stay quiet.651 out, err = capfd.readouterr()652 assert err == ""653 return out654655656def _write_pager_from_multiple_sites(pager):657 pager.write("prefix\n")658 click.echo("middle", file=pager)659 pager.write("suffix\n")660661662@pytest.mark.skipif(663 WIN,664 reason="Exercises the pipe pager path; Windows uses _tempfilepager.",665)666@pytest.mark.parametrize(667 ("writer", "color", "expected"),668 [669 pytest.param(670 _write_pager_from_multiple_sites,671 False,672 "prefix\nmiddle\nsuffix\n",673 id="multiple write sites",674 ),675 pytest.param(676 lambda pager: pager.write("hello\n"), False, "hello\n", id="plain text"677 ),678 pytest.param(679 lambda pager: pager.write(click.style("hello", fg="red") + "\n"),680 False,681 "hello\n",682 id="strip ansi",683 ),684 pytest.param(685 lambda pager: pager.write(click.style("hello", fg="red") + "\n"),686 True,687 click.style("hello", fg="red") + "\n",688 id="preserve ansi",689 ),690 pytest.param(lambda pager: pager.write(""), False, "", id="empty string"),691 ],692)693def test_get_pager_file_with_real_pager_binary_stream(694 monkeypatch, capfd, writer, color, expected695):696 """A real pager should exercise the BinaryIO branch."""697 output = _run_get_pager_file_with_real_pager(698 monkeypatch, capfd, writer, color=color699 )700701 assert output == expected702703704@pytest.mark.skipif(705 WIN,706 reason="Exercises the pipe pager path; Windows uses _tempfilepager.",707)708@pytest.mark.parametrize(709 ("color", "expected"),710 [711 pytest.param(False, "hello\n", id="strip ansi"),712 pytest.param(True, click.style("hello", fg="red") + "\n", id="preserve ansi"),713 ],714)715def test_echo_via_pager_real_pager_handles_ansi(monkeypatch, capfd, color, expected):716 """``echo_via_pager`` should honor ``color`` like ``get_pager_file``."""717 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)718 monkeypatch.setitem(719 click._termui_impl.os.environ, "PAGER", _get_real_pager_command()720 )721722 click.echo_via_pager(click.style("hello", fg="red"), color=color)723724 out, err = capfd.readouterr()725 assert err == ""726 assert out == expected727728729def test_get_pager_file_pager_missing_binary_falls_back(monkeypatch, tmp_path):730 """``PAGER`` pointing to a nonexistent binary falls back to the text stdout."""731 pager_out = tmp_path / "pager_out.txt"732733 monkeypatch.setitem(734 click._termui_impl.os.environ,735 "PAGER",736 "click-tests-nonexistent-pager-9b3f2",737 )738 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)739740 with pager_out.open("w", encoding="utf-8") as text_stream:741 monkeypatch.setattr(742 click._termui_impl, "_default_text_stdout", lambda: text_stream743 )744745 with click.get_pager_file() as pager:746 pager.write("hello\n")747748 assert pager_out.read_text(encoding="utf-8") == "hello\n"749750751def test_get_pager_file_pager_unset_falls_back_when_no_default(monkeypatch, tmp_path):752 """``PAGER`` unset still works when the platform default isn't installed."""753 pager_out = tmp_path / "pager_out.txt"754755 monkeypatch.delitem(click._termui_impl.os.environ, "PAGER", raising=False)756 monkeypatch.delitem(click._termui_impl.os.environ, "TERM", raising=False)757 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)758 monkeypatch.setattr(shutil, "which", lambda _name: None)759760 with pager_out.open("w", encoding="utf-8") as text_stream:761 monkeypatch.setattr(762 click._termui_impl, "_default_text_stdout", lambda: text_stream763 )764765 with click.get_pager_file() as pager:766 pager.write("hello\n")767768 assert pager_out.read_text(encoding="utf-8") == "hello\n"769770771@pytest.mark.parametrize(772 ("color", "expected"),773 [774 pytest.param(False, "hello\n", id="strip ansi"),775 pytest.param(True, click.style("hello", fg="red") + "\n", id="preserve ansi"),776 ],777)778def test_get_pager_file_nullpager_wraps_textio_stream(779 monkeypatch, tmp_path, color, expected780):781 """When paging falls back to a real TextIO stream, ``.buffer`` is wrapped."""782 pager_out = tmp_path / "pager_out.txt"783784 with pager_out.open("w", encoding="utf-8") as text_stream:785 monkeypatch.setattr(786 click._termui_impl, "_default_text_stdout", lambda: text_stream787 )788 monkeypatch.setattr(789 click._termui_impl, "isatty", lambda stream: stream is not sys.stdin790 )791792 with click.get_pager_file(color=color) as pager:793 pager.write(click.style("hello", fg="red") + "\n")794795 assert pager_out.read_text(encoding="utf-8") == expected796797798def test_get_pager_file_nullpager_keeps_stringio_stream(monkeypatch):799 """The no-stdout fallback should keep a text-only stream and set ``.color``."""800801 created = []802803 def make_stringio():804 stream = io.StringIO()805 created.append(stream)806 return stream807808 monkeypatch.setattr(sys, "stdout", None)809 monkeypatch.setattr(click._termui_impl, "StringIO", make_stringio)810 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: False)811812 styled_text = click.style("hello", fg="red")813814 with click.get_pager_file(color=False) as pager:815 assert pager is created[0]816 pager.write(styled_text)817818 assert created[0].getvalue() == styled_text819820821def test_get_pager_file_flushes_stream_on_exception(monkeypatch):822 """Exceptions should still flush the yielded stream in ``finally``."""823824 class FlushableTextStream(io.StringIO):825 def __init__(self):826 super().__init__()827 self.color = None828 self.flush_calls = 0829830 def flush(self):831 self.flush_calls += 1832833 stream = FlushableTextStream()834835 @contextlib.contextmanager836 def pager_contextmanager(color=None):837 yield stream, "utf-8", color838839 monkeypatch.setattr(840 click._termui_impl, "_pager_contextmanager", pager_contextmanager841 )842843 with pytest.raises(RuntimeError, match="boom"):844 with click.get_pager_file() as pager:845 assert pager is stream846 raise RuntimeError("boom")847848 assert stream.flush_calls == 1849850851def test_editor_unclosed_quote():852 """An unclosed quote in the editor command raises ValueError."""853 with pytest.raises(ValueError, match="No closing quotation"):854 Editor(editor='"unclosed').edit_files(["f.txt"])
360 unmodified lines
12151216 assert result.output == expected_output1217 assert not result.stderr1218 assert result.exit_code == 0 if expected not in (REPEAT, INVALID) else 1121912201221class _CustomTypeNoValue(click.ParamType):1222 name = "custom"12231224 def convert(self, value, param, ctx):1225 if len(value) < 4:1226 self.fail("Password must be at least 4 characters", param, ctx)1227 return value122812291230class _CustomTypeWithRawValue(click.ParamType):1231 name = "custom_raw"12321233 def convert(self, value, param, ctx):1234 if value == "bad":1235 self.fail(f"rejected: {value}", param, ctx)1236 return value123712381239class _PasswordLengthType(click.ParamType):1240 """Mirrors the issue's original use case: a password validator1241 that references the user-typed value in its error message without1242 quoting it.1243 """12441245 name = "password"12461247 def convert(self, value, param, ctx):1248 if len(value) < 10:1249 self.fail(f"{value} is too short", param, ctx)1250 return value125112521253class _MixedQuotedAndRawType(click.ParamType):1254 """Custom type that mentions the user input both quoted (built-in1255 pattern) and raw within the same message.1256 """12571258 name = "mixed"12591260 def convert(self, value, param, ctx):1261 self.fail(f"got {value!r} which is the same as {value}", param, ctx)126212631264class _StaticMessageType(click.ParamType):1265 """Custom type whose error message never references the value."""12661267 name = "static"12681269 def convert(self, value, param, ctx):1270 self.fail("Authentication failed for this account", param, ctx)127112721273class _RejectAllRawType(click.ParamType):1274 """Always rejects, with the raw value (unquoted) in the message."""12751276 name = "reject_all_raw"12771278 def convert(self, value, param, ctx):1279 self.fail(f"rejected: {value}", param, ctx)128012811282class _MultiRawType(click.ParamType):1283 """Mentions the raw value multiple times in the same message."""12841285 name = "multi_raw"12861287 def convert(self, value, param, ctx):1288 self.fail(f"got {value} but {value} is bad", param, ctx)128912901291class _MultiReprType(click.ParamType):1292 """Mentions ``repr(value)`` multiple times in the same message."""12931294 name = "multi_repr"12951296 def convert(self, value, param, ctx):1297 self.fail(f"got {value!r} and {value!r}", param, ctx)129812991300class _ApostropheReprType(click.ParamType):1301 """Custom type whose ``repr(value)`` switches to double quotes when1302 the value itself contains a single quote.1303 """13041305 name = "apostrophe_repr"13061307 def convert(self, value, param, ctx):1308 self.fail(f"rejected {value!r}", param, ctx)130913101311@pytest.mark.parametrize(1312 ("type", "user_input", "expected_fragment", "unexpected_fragment"),1313 [1314 pytest.param(1315 click.INT,1316 "bad",1317 "'***' is not a valid integer",1318 "bad",1319 id="builtin-int-masks-repr-value",1320 ),1321 pytest.param(1322 _CustomTypeNoValue(),1323 "bad",1324 "Password must be at least 4 characters",1325 None,1326 id="custom-no-value-shows-message",1327 ),1328 pytest.param(1329 _CustomTypeWithRawValue(),1330 "bad",1331 "rejected: '***'",1332 "bad",1333 id="custom-raw-value-masked",1334 ),1335 pytest.param(1336 _PasswordLengthType(),1337 "PASSWORD",1338 "'***' is too short",1339 "PASSWORD",1340 id="unquoted-custom-message-should-mask-not-fallback",1341 ),1342 pytest.param(1343 _MixedQuotedAndRawType(),1344 "leakybits",1345 "got '***' which is the same as '***'",1346 "leakybits",1347 id="mixed-quoted-and-raw-both-masked-at-source",1348 ),1349 pytest.param(1350 click.IntRange(min=10, max=99),1351 "1",1352 "is not in the range",1353 None,1354 id="intrange-numeric-substring-falls-back-to-generic",1355 ),1356 pytest.param(1357 _StaticMessageType(),1358 "ent",1359 "Authentication failed for this account",1360 None,1361 id="partial-word-match-falls-back-to-generic",1362 ),1363 # When the raw (unquoted) value appears in the message, mask it instead1364 # of replacing the whole message with a generic fallback that throws1365 # useful information away.1366 pytest.param(1367 _RejectAllRawType(),1368 "secret",1369 "rejected: '***'",1370 "secret",1371 id="raw-value-should-be-masked-not-fallback",1372 ),1373 # When the raw value occurs more than1374 # once unquoted, every occurrence must be masked.1375 pytest.param(1376 _MultiRawType(),1377 "secret",1378 "got '***' but '***' is bad",1379 "secret",1380 id="multi-occurrence-raw-mask-all",1381 ),1382 pytest.param(1383 _MultiReprType(),1384 "secret",1385 "got '***' and '***'",1386 "secret",1387 id="multi-occurrence-repr-mask-all",1388 ),1389 pytest.param(1390 _PasswordLengthType(),1391 "a.b*c+",1392 "'***' is too short",1393 "a.b*c+",1394 id="regex-special-chars-must-be-escaped",1395 ),1396 pytest.param(1397 _PasswordLengthType(),1398 "пароль",1399 "'***' is too short",1400 "пароль",1401 id="unicode-value-masked",1402 ),1403 pytest.param(1404 _ApostropheReprType(),1405 "it's",1406 "rejected '***'",1407 "it's",1408 id="apostrophe-in-value-uses-double-quote-repr",1409 ),1410 pytest.param(1411 _MixedQuotedAndRawType(),1412 "leakybits",1413 "got '***' which is the same as '***'",1414 "leakybits",1415 id="mixed-quoted-and-raw-mask-both",1416 ),1417 ],1418)1419def test_hide_input_error_message(1420 runner, type, user_input, expected_fragment, unexpected_fragment1421):1422 """https://github.com/pallets/click/issues/2809"""14231424 @click.command()1425 @click.option("--password", prompt=True, hide_input=True, type=type)1426 def cli(password):1427 click.echo(password)14281429 result = runner.invoke(cli, input=user_input)1430 assert expected_fragment in result.output1431 if unexpected_fragment is not None:1432 assert unexpected_fragment not in result.output143314341435def test_hide_input_confirmation_prompt_mismatch_unaffected(runner):1436 """The ``hide_input`` mask logic only applies to ``value_proc``1437 failures. The separate ``confirmation_prompt`` mismatch path must1438 keep emitting its own message, with no value leak from either entry.1439 """14401441 @click.command()1442 @click.option("--password", prompt=True, confirmation_prompt=True, hide_input=True)1443 def cli(password):1444 click.echo(f"got: {password}")14451446 # First pair mismatches, second pair matches.1447 result = runner.invoke(cli, input="firstone\nsecondone\nfinalone\nfinalone\n")1448 assert "Error: The two entered values do not match." in result.output1449 assert "firstone" not in result.output1450 assert "secondone" not in result.output1451 # Successful prompt echoes the final value back via the command body.1452 assert "got: finalone" in result.output1453 assert result.exit_code == 0145414551456def test_hide_input_value_never_leaks_when_err_true(runner):1457 """``click.prompt(..., err=True)`` routes its error message to1458 stderr. The masking logic must apply on that path too: the raw1459 input must not appear on either stream.1460 """14611462 @click.command()1463 def cli():1464 value = click.prompt(1465 "Password",1466 hide_input=True,1467 type=_PasswordLengthType(),1468 err=True,1469 )1470 click.echo(value)14711472 result = runner.invoke(cli, input="leaky\n", mix_stderr=False)1473 assert "leaky" not in result.stdout1474 assert "leaky" not in result.stderr
modified:tests/test_testing.py+218 added-16 removed
1import faulthandler2import io3import os4import pdb5import sys6from io import BytesIO
515 unmodified lines
522523 assert pdb.Pdb.__init__ is original524525525def test_faulthandler_enable(runner):526 """``faulthandler.enable()`` inside ``CliRunner`` should not crash with527 ``io.UnsupportedOperation: fileno``.526needs_fd_capture = pytest.mark.skipif(527 sys.platform == "win32",528 reason="fd capture not supported on Windows",529)530529 ``faulthandler.enable()`` needs a real OS file descriptor to register530 its signal handler. ``CliRunner`` replaces ``sys.stderr`` with a531 ``BytesIO`` wrapper that has no ``fileno()``, causing the call to fail.531533 Reproduce:https://github.com/pallets/click/issues/2865532def test_capture_invalid_mode():533 """Invalid capture mode raises ValueError."""534 with pytest.raises(ValueError, match="capture"):535 CliRunner(capture="invalid") # type: ignore[arg-type]536537538@pytest.mark.skipif(sys.platform != "win32", reason="Windows-only test")539def test_capture_fd_windows_error():540 """fd capture raises ValueError on Windows."""541 with pytest.raises(ValueError, match="not supported on Windows"):542 CliRunner(capture="fd")543544545@needs_fd_capture546def test_capture_fd_os_write():547 """capture='fd' captures writes to fd 1/2 that bypass sys.stdout."""548549 @click.command()550 def cli():551 click.echo("python stdout")552 os.write(1, b"fd stdout\n")553 os.write(2, b"fd stderr\n")554555 runner = CliRunner(capture="fd")556 result = runner.invoke(cli)557 assert "python stdout" in result.stdout558 assert "fd stdout" in result.stdout559 assert "fd stderr" in result.stderr560561562@needs_fd_capture563def test_capture_fd_stale_reference():564 """capture='fd' captures writes from stale stdout references (issue #2874).565566 Simulates ``from sys import stdout`` at import time, which grabs567 the real stdout connected to fd 1. The stale object's underlying568 FileIO uses fd 1, so redirecting fd 1 captures its writes.569 """570 # open(1, ..., closefd=False) creates a writer whose underlying571 # FileIO uses fd 1 directly. This mirrors the real scenario:572 # the original sys.stdout is a TextIOWrapper -> BufferedWriter ->573 # FileIO(fd=1).574 stale_stdout = open(1, "w", closefd=False) # noqa: SIM115575576 @click.command()537 @click.option("--flag", type=bool, default=True)538 def cli(flag):539 click.echo("Executing main function...")540 if flag:541 click.echo("Registering faulthandler")542 faulthandler.enable()543 click.echo("Finished executing main function.")577 def cli():578 stale_stdout.write("stale write\n")579 stale_stdout.flush()580 click.echo("normal write")581582 runner = CliRunner(capture="fd")545 result = runner.invoke(cli, ["--flag", True])583 result = runner.invoke(cli)584 assert "normal write" in result.stdout585 assert "stale write" in result.stdout586587588@needs_fd_capture589def test_capture_fd_logging_handler(tmp_path):590 """capture='fd' captures logging output from a handler holding a stale591 stderr reference (issue #2827).592593 stdlib logging.StreamHandler grabs sys.stderr at configuration time.594 Under normal CliRunner (sys-level capture), the handler still writes595 to the original stream object and output is lost. fd-level capture596 redirects the underlying file descriptor, so the writes are captured.597 """598 import logging599600 # Create a writer backed by the real fd 2, simulating a handler601 # configured at import time before pytest or CliRunner replaced602 # sys.stderr. open(2, closefd=False) mirrors the real scenario:603 # the original sys.stderr is a TextIOWrapper -> BufferedWriter ->604 # FileIO(fd=2).605 stale_stderr = open(2, "w", closefd=False) # noqa: SIM115606 handler = logging.StreamHandler(stale_stderr)607 handler.setFormatter(logging.Formatter("%(message)s"))608609 logger = logging.getLogger(f"click_test_{tmp_path.name}")610 logger.addHandler(handler)611 logger.setLevel(logging.INFO)612 logger.propagate = False613614 @click.command()615 def cli():616 logger.info("log from stale handler")617 click.echo("normal echo")618619 # sys-level capture misses the log line (it bypasses sys.stderr).620 runner_sys = CliRunner(capture="sys")621 result_sys = runner_sys.invoke(cli)622 assert "normal echo" in result_sys.output623 assert "log from stale handler" not in result_sys.output624625 # fd-level capture catches it by redirecting fd 2.626 runner_fd = CliRunner(capture="fd")627 result_fd = runner_fd.invoke(cli)628 assert "normal echo" in result_fd.output629 assert "log from stale handler" in result_fd.output630631 logger.removeHandler(handler)632633634@needs_fd_capture635def test_capture_fd_faulthandler():636 """faulthandler.enable() works with capture='fd' (issue #2865)."""637638 @click.command()639 def cli():640 faulthandler.enable()641 click.echo("after faulthandler")642643 runner = CliRunner(capture="fd")644 result = runner.invoke(cli)645 assert result.exit_code == 0646 assert "after faulthandler" in result.output647648649def test_capture_sys_fileno_raises():650 """capture='sys' leaves fileno() raising UnsupportedOperation, so user651 code that does ``os.dup2(w, sys.stdout.fileno())`` cannot mutate the host652 runner's stdout (issue #3384).653 """654655 @click.command()656 def cli():657 with pytest.raises(io.UnsupportedOperation):658 sys.stdout.fileno()659 with pytest.raises(io.UnsupportedOperation):660 sys.stderr.fileno()661 click.echo("ok")662663 runner = CliRunner(capture="sys")664 result = runner.invoke(cli)665 assert result.exit_code == 0, result.output547 assert "Finished executing main function." in result.output666 assert "ok" in result.stdout667668669@needs_fd_capture670def test_capture_fd_stderr_separation():671 """capture='fd' properly separates fd-level stdout and stderr."""672673 @click.command()674 def cli():675 click.echo("py-out")676 click.echo("py-err", err=True)677 os.write(1, b"fd-out\n")678 os.write(2, b"fd-err\n")679680 runner = CliRunner(capture="fd")681 result = runner.invoke(cli)682 assert "py-out" in result.stdout683 assert "fd-out" in result.stdout684 assert "py-err" in result.stderr685 assert "fd-err" in result.stderr686 # Mixed output has all of them687 assert "py-out" in result.output688 assert "py-err" in result.output689 assert "fd-out" in result.output690 assert "fd-err" in result.output691692693@needs_fd_capture694def test_capture_fd_nesting():695 """Nested CliRunner.invoke() with fd capture works correctly."""696697 @click.command("inner")698 def inner_cli():699 click.echo("inner")700701 @click.command("outer")702 def outer_cli():703 click.echo("outer")704 os.write(1, b"outer fd\n")705 inner_runner = CliRunner(capture="fd")706 inner_result = inner_runner.invoke(inner_cli)707 click.echo(f"inner captured: {inner_result.stdout.strip()}")708709 runner = CliRunner(capture="fd")710 result = runner.invoke(outer_cli)711 assert "outer" in result.stdout712 assert "outer fd" in result.stdout713 assert "inner captured: inner" in result.stdout714715716@needs_fd_capture717@pytest.mark.parametrize("runner_capture", ["sys", "fd"])718@pytest.mark.parametrize("pytest_fixture", ["capsys", "capfd"])719def test_capture_pytest_matrix(720 request: pytest.FixtureRequest,721 runner_capture: str,722 pytest_fixture: str,723) -> None:724 """Matrix of ``CliRunner`` capture modes and Pytest capture fixtures."""725 pytest_cap = request.getfixturevalue(pytest_fixture)726727 @click.command()728 def cli() -> None:729 click.echo("inside-stdout")730 click.echo("inside-stderr", err=True)731732 runner = CliRunner(capture=runner_capture)733 result = runner.invoke(cli)734735 # CliRunner sees Click's output.736 assert result.exit_code == 0737 assert "inside-stdout" in result.stdout738 assert "inside-stderr" in result.stderr739740 # Pytest capture machinery is still working after invoke().741 print("post-invoke-stdout")742 print("post-invoke-stderr", file=sys.stderr)743 captured = pytest_cap.readouterr()744 assert "post-invoke-stdout" in captured.out745 assert "post-invoke-stderr" in captured.err746747 # Click output is not leaking into Pytest.748 assert "inside-stdout" not in captured.out749 assert "inside-stderr" not in captured.err
modified:tests/test_types.py+19 added
49 unmodified lines
5051 assert expect in exc_info.value.message525354@pytest.mark.parametrize(55 ("error_message", "expected"),56 [57 ("bad value: nope", "bad value: nope"),58 ("", "nope"),59 ],60)61def test_func_param_type_uses_value_error_message(error_message, expected):62 def parse(value):63 raise ValueError(error_message if error_message else "")6465 func_type = click.types.FuncParamType(parse)6667 with pytest.raises(click.BadParameter) as exc_info:68 func_type.convert("nope", None, None)6970 assert expected in exc_info.value.message717273def test_float_range_no_clamp_open():74 with pytest.raises(TypeError):75 click.FloatRange(0, 1, max_open=True, clamp=True)76
200 unmodified lines
modified:tests/test_utils.py+46 added-9 removed
223 unmodified lines
224 except click.Abort:225 click.echo("interrupted")226227 out, err = capsys.readouterr()228 # On non-Windows, prompt is passed directly to getpass, not echoed separately228 assert out == "Password:\ninterrupted\n"229 assert out == "\ninterrupted\n"230231232@pytest.mark.skipif(WIN, reason="Different behavior on windows.")233@pytest.mark.parametrize(234 ("call", "expected_prompt"),235 [236 (lambda: click.prompt("Name"), "Name: "),237 (lambda: click.prompt("Pw", hide_input=True), "Pw: "),238 (lambda: click.prompt("IP", prompt_suffix="."), "IP."),239 (lambda: click.confirm("OK"), "OK [y/N]: "),240 ],241 ids=["prompt", "prompt-hidden", "prompt-custom-suffix", "confirm"],242)243def test_full_prompt_passed_to_readline(monkeypatch, call, expected_prompt):244 """On non-Windows, prompt and confirm pass the full prompt text to the245 underlying prompt function so readline handles editing correctly.246247 https://github.com/pallets/click/issues/2968248 https://github.com/pallets/click/pull/2969249 """250 received = []251252 def capture(text):253 received.append(text)254 return "y"255256 monkeypatch.setattr("click.termui.visible_prompt_func", capture)257 monkeypatch.setattr("click.termui.hidden_prompt_func", capture)258 call()259 assert received == [expected_prompt]260261262def test_prompts_eof(runner):263 """If too few lines of input are given, prompt should exit, not hang."""264265 @click.command
248 unmodified lines
514 out, err = capfd.readouterr()515 assert out == "Prompt to stdin with no suffix"516 assert err == ""517518 # On non-Windows the full prompt goes through redirect_stdout so519 # nothing leaks to stdout when err=True.520 # https://github.com/pallets/click/issues/2968521 emulate_input("asdlkj\n")522 click.prompt("Prompt to stderr", err=True)523 out, err = capfd.readouterr()490 assert out == " "491 assert err == "Prompt to stderr:"524 assert out == ""525 assert err == "Prompt to stderr: "526527 # https://github.com/pallets/click/issues/3019528 emulate_input("asdlkj\n")529 click.prompt("Prompt to stderr with no suffix", prompt_suffix="", err=True)530 out, err = capfd.readouterr()496 assert out == "x"497 assert err == "Prompt to stderr with no suffi"531 assert out == ""532 assert err == "Prompt to stderr with no suffix"533534 emulate_input("y\n")535 click.confirm("Prompt to stdin")536 out, err = capfd.readouterr()
5 unmodified lines
542 out, err = capfd.readouterr()543 assert out == "Prompt to stdin with no suffix [y/N]"544 assert err == ""545546 # https://github.com/pallets/click/issues/2968547 emulate_input("y\n")548 click.confirm("Prompt to stderr", err=True)549 out, err = capfd.readouterr()514 assert out == " "515 assert err == "Prompt to stderr [y/N]:"550 assert out == ""551 assert err == "Prompt to stderr [y/N]: "552553 # https://github.com/pallets/click/issues/3019554 emulate_input("y\n")555 click.confirm("Prompt to stderr with no suffix", prompt_suffix="", err=True)556 out, err = capfd.readouterr()520 assert out == "]"521 assert err == "Prompt to stderr with no suffix [y/N"557 assert out == ""558 assert err == "Prompt to stderr with no suffix [y/N]"559560 monkeypatch.setattr(click.termui, "isatty", lambda x: True)561 monkeypatch.setattr(click.termui, "getchar", lambda: " ")562
220 unmodified lines
modified:.gitignore+1 added
4 unmodified lines
5.coverage*6htmlcov/7.tox/8docs/_build/9.venv/
modified:CHANGES.rst+98 added
1.. currentmodule:: click23Version 8.4.04-------------56Unreleased78- :class:`ParamType` typing improvements. :pr:`3371`910 - :class:`ParamType` is now a generic abstract base class,11 parameterized by its converted value type.12 - :meth:`~ParamType.convert` return types are narrowed on all13 concrete types (``str`` for :class:`STRING`, ``int`` for14 :class:`INT`, etc.).15 - :meth:`~ParamType.to_info_dict` returns specific16 :class:`~typing.TypedDict` subclasses instead of17 ``dict[str, Any]``.18 - :class:`CompositeParamType` and the number-range base are now19 generic with abstract methods.20- Refactor ``convert_type`` to extract type inference into a private21 ``_guess_type`` helper, and add :func:`typing.overload` signatures.22 :pr:`3372`23- :class:`Parameter` typing improvements. :pr:`2805`2425 - :class:`Parameter` is now an abstract base class, making explicit26 that it cannot be instantiated directly.27 - :attr:`Parameter.name` is now ``str`` instead of ``str | None``.28 When ``expose_value=False``, the name is set to ``""`` instead29 of ``None``.30 - The ``ctx`` parameter of :meth:`Parameter.get_error_hint` is now31 typed as ``Context | None``, matching the runtime behavior.32- Split string values from ``default_map`` for parameters with ``nargs > 1``33 or :class:`Tuple` type, matching environment variable behavior.34 :issue:`2745` :pr:`3364`35- Auto-detect ``type=UNPROCESSED`` for ``flag_value`` of non-basic types36 (not ``str``, ``int``, ``float``, or ``bool``), so programmer-provided37 Python objects like classes and enum members are passed through unchanged38 instead of being stringified. Previously ``type=click.UNPROCESSED`` had39 to be set explicitly. :issue:`2012` :pr:`3363`40- The error hint now uses :meth:`Command.get_help_option_names` to pick41 non-shadowed help option names, so ``Try '... -h'`` no longer points to a42 subcommand option that shadows ``-h``. All surviving names are shown43 (``-h/--help``). :issue:`2790` :pr:`3208`44- Fix readline functionality on non-Windows platforms. Prompt text is now45 passed directly to readline instead of being printed separately, allowing46 proper backspace, line editing, and line wrapping behavior. :issue:`2968`47 :pr:`2969`48- Use :func:`os.startfile` on Windows to open URLs in :func:`open_url`,49 replacing the ``start`` built-in which cannot be invoked without50 ``shell=True``. :issue:`3164` :pr:`3186`51- Fix Fish shell completion errors when option help text contains newlines.52 :issue:`3043` :pr:`3126`53- Add :class:`NoSuchCommand` exception with suggestions for misspelled54 commands. :issue:`3107` :pr:`3228`55- Use :class:`ValueError` message when conversion in :class:`FuncParamType` would56 fail. :issue:`3105` :pr:`3211`57- Add ``click.get_pager_file`` for file-like access to an output58 pager. :pr:`1572` :pr:`3405`59- :class:`~click.formatting.TextWrapper` and60 :func:`~click.formatting.wrap_text` now measure line width in visible61 characters, ignoring ANSI escape sequences. :pr:`3420`62- Fix :meth:`HelpFormatter.write_usage` emitting only a blank line when63 called without ``args``. The usage prefix and program name are now64 written even when no arguments follow, and the trailing separator65 space is stripped so the line ends at the program name.66 :issue:`3360` :pr:`3434`67- Show custom error messages from types when :func:`prompt` with68 ``hide_input=True`` fails validation, instead of always showing a69 generic message. Built-in type messages mask the input value.70 :issue:`2809` :pr:`3256`71- Add ``capture`` parameter to :class:`CliRunner` with two modes: ``sys``72 (default) and ``fd``. ``fd`` redirects file descriptors ``1`` and ``2``73 via :func:`os.dup2` so output that bypasses ``sys.stdout`` (stale stream74 references, C extensions, subprocesses, ``faulthandler``) is captured75 with proper isolation. :issue:`854` :issue:`2412` :issue:`2468`76 :issue:`2497` :issue:`2761` :issue:`2827` :issue:`2865`77- Revert the ``8.3.3`` change that exposed the original file descriptor78 via ``fileno()`` on the redirected ``CliRunner`` streams in the default79 capture mode. ``os.dup2(w, sys.stdout.fileno())`` calls inside a CLI no80 longer mutate the host runner's stdout, which broke Pytest's ``fd``-level81 capture teardown. C-level consumers that need a real ``fd`` should use82 ``capture="fd"``. :issue:`3384` :pr:`3391`83- Mark additional built-in strings with ``gettext()`` to extend translation84 coverage. :pr:`2902`85- Fix feature switch groups (several ``flag_value`` options sharing one86 parameter name) silently dropping an explicit ``default`` when a sibling87 option without an explicit default was declared first. Arbitration is now88 source-aware: a more explicit :class:`ParameterSource` always wins, and89 within ``ParameterSource.DEFAULT``, an option that received an explicit90 ``default=`` keyword wins over a sibling whose default was auto-derived.91 The 8.3.x first-wins fallback for remaining ties was reverted to the92 pre-8.3.x last-wins fallback. :issue:`3403` :pr:`3404`93- Fix missing space between option help text and the ``(DEPRECATED)``94 label, and localize the option label so it matches the command label.95 The label and the ``DeprecationWarning`` reason suffix are now produced96 by shared helpers. :pr:`3423`97- Document short option stacking (``-abc`` is parsed as ``-a -b -c``) and98 clarify that multi-character short option names are not supported.99 :issue:`2779` :pr:`3431`100101Version 8.3.3102-------------103104Released 2026-04-20
1363 unmodified lines