Skip to content
Myr

enable deferred evaluation of annotations (#2270)

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

authored by David Lord · committed by GitHub · parents 988c683, ec258fe · Browse files · 18 files+643 added−619 removed
This commit

State

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

Diff stats

18 files+643 added−619 removed

  • tests:+2 added−0 removed
  • other:+641 added−619 removed

18 files+643 added−619 removed

modified:src/click/__init__.py+2 added
2 unmodified lines
3writing command line scripts fun. Unlike other modules, it's based4around a simple API that does not come with too much magic and is5composable.6"""7from __future__ import annotations89from .core import Argument as Argument10from .core import Command as Command11from .core import CommandCollection as CommandCollection12from .core import Context as Context
99 unmodified lines
modified:src/click/_compat.py+49 added-48 removed
1from __future__ import annotations23import codecs4import collections.abc as cabc5import io6import os7import re8import sys9import typing as t10from types import TracebackType11from weakref import WeakKeyDictionary1213CYGWIN = sys.platform.startswith("cygwin")14WIN = sys.platform.startswith("win")11auto_wrap_for_ansi: t.Optional[t.Callable[[t.TextIO], t.TextIO]] = None15auto_wrap_for_ansi: t.Callable[[t.TextIO], t.TextIO] | None = None16_ansi_re = re.compile(r"\033\[[;?0-9]*[a-zA-Z]")171819def _make_text_stream(20 stream: t.BinaryIO,17 encoding: t.Optional[str],18 errors: t.Optional[str],21 encoding: str | None,22 errors: str | None,23 force_readable: bool = False,24 force_writable: bool = False,25) -> t.TextIO:26 if encoding is None:
29 unmodified lines
56class _NonClosingTextIOWrapper(io.TextIOWrapper):57 def __init__(58 self,59 stream: t.BinaryIO,56 encoding: t.Optional[str],57 errors: t.Optional[str],60 encoding: str | None,61 errors: str | None,62 force_readable: bool = False,63 force_writable: bool = False,64 **extra: t.Any,65 ) -> None:
103 unmodified lines
169 return default170 return True171172169def _find_binary_reader(stream: t.IO[t.Any]) -> t.Optional[t.BinaryIO]:173def _find_binary_reader(stream: t.IO[t.Any]) -> t.BinaryIO | None:174 # We need to figure out if the given stream is already binary.175 # This can happen because the official docs recommend detaching176 # the streams to get binary streams. Some code might do this, so177 # we need to deal with this case explicitly.
9 unmodified lines
187188 return None189190187def _find_binary_writer(stream: t.IO[t.Any]) -> t.Optional[t.BinaryIO]:191def _find_binary_writer(stream: t.IO[t.Any]) -> t.BinaryIO | None:192 # We need to figure out if the given stream is already binary.193 # This can happen because the official docs recommend detaching194 # the streams to get binary streams. Some code might do this, so195 # we need to deal with this case explicitly.
18 unmodified lines
214 # but this at least will force Click to recover somehow.215 return is_ascii_encoding(getattr(stream, "encoding", None) or "ascii")216217214def _is_compat_stream_attr(stream: t.TextIO, attr: str, value: t.Optional[str]) -> bool:218def _is_compat_stream_attr(stream: t.TextIO, attr: str, value: str | None) -> bool:219 """A stream attribute is compatible if it is equal to the220 desired value or the desired value is unset and the attribute221 has a value.222 """
1 unmodified line
224 return stream_value == value or (value is None and stream_value is not None)225226227def _is_compatible_text_stream(224 stream: t.TextIO, encoding: t.Optional[str], errors: t.Optional[str]228 stream: t.TextIO, encoding: str | None, errors: str | None229) -> bool:230 """Check if a stream's encoding and errors attributes are231 compatible with the desired values.232 """
3 unmodified lines
236237238def _force_correct_text_stream(239 text_stream: t.IO[t.Any],236 encoding: t.Optional[str],237 errors: t.Optional[str],240 encoding: str | None,241 errors: str | None,242 is_binary: t.Callable[[t.IO[t.Any], bool], bool],239 find_binary: t.Callable[[t.IO[t.Any]], t.Optional[t.BinaryIO]],243 find_binary: t.Callable[[t.IO[t.Any]], t.BinaryIO | None],244 force_readable: bool = False,245 force_writable: bool = False,246) -> t.TextIO:247 if is_binary(text_stream, False):
34 unmodified lines
282283284def _force_correct_text_reader(285 text_reader: t.IO[t.Any],282 encoding: t.Optional[str],283 errors: t.Optional[str],286 encoding: str | None,287 errors: str | None,288 force_readable: bool = False,289) -> t.TextIO:290 return _force_correct_text_stream(291 text_reader,
6 unmodified lines
298299300def _force_correct_text_writer(301 text_writer: t.IO[t.Any],298 encoding: t.Optional[str],299 errors: t.Optional[str],302 encoding: str | None,303 errors: str | None,304 force_writable: bool = False,305) -> t.TextIO:306 return _force_correct_text_stream(307 text_writer,
25 unmodified lines
333 raise RuntimeError("Was not able to determine binary stream for sys.stderr.")334 return writer335336333def get_text_stdin(334 encoding: t.Optional[str] = None, errors: t.Optional[str] = None335) -> t.TextIO:337def get_text_stdin(encoding: str | None = None, errors: str | None = None) -> t.TextIO:338 rv = _get_windows_console_stream(sys.stdin, encoding, errors)339 if rv is not None:340 return rv341 return _force_correct_text_reader(sys.stdin, encoding, errors, force_readable=True)342343342def get_text_stdout(343 encoding: t.Optional[str] = None, errors: t.Optional[str] = None344) -> t.TextIO:344def get_text_stdout(encoding: str | None = None, errors: str | None = None) -> t.TextIO:345 rv = _get_windows_console_stream(sys.stdout, encoding, errors)346 if rv is not None:347 return rv348 return _force_correct_text_writer(sys.stdout, encoding, errors, force_writable=True)349350351def get_text_stderr(352 encoding: t.Optional[str] = None, errors: t.Optional[str] = None353) -> t.TextIO:351def get_text_stderr(encoding: str | None = None, errors: str | None = None) -> t.TextIO:352 rv = _get_windows_console_stream(sys.stderr, encoding, errors)353 if rv is not None:354 return rv355 return _force_correct_text_writer(sys.stderr, encoding, errors, force_writable=True)356357358def _wrap_io_open(361 file: t.Union[str, "os.PathLike[str]", int],359 file: str | os.PathLike[str] | int,360 mode: str,363 encoding: t.Optional[str],364 errors: t.Optional[str],361 encoding: str | None,362 errors: str | None,363) -> t.IO[t.Any]:364 """Handles not passing ``encoding`` and ``errors`` in binary mode."""365 if "b" in mode:366 return open(file, mode)
1 unmodified line
368 return open(file, mode, encoding=encoding, errors=errors)369370371def open_stream(374 filename: "t.Union[str, os.PathLike[str]]",372 filename: str | os.PathLike[str],373 mode: str = "r",376 encoding: t.Optional[str] = None,377 errors: t.Optional[str] = "strict",374 encoding: str | None = None,375 errors: str | None = "strict",376 atomic: bool = False,379) -> t.Tuple[t.IO[t.Any], bool]:377) -> tuple[t.IO[t.Any], bool]:378 binary = "b" in mode379 filename = os.fspath(filename)380381 # Standard streams first. These are simple because they ignore the
31 unmodified lines
413 import errno414 import random415416 try:419 perm: t.Optional[int] = os.stat(filename).st_mode417 perm: int | None = os.stat(filename).st_mode418 except OSError:419 perm = None420421 flags = os.O_RDWR | os.O_CREAT | os.O_EXCL
47 unmodified lines
469470 def __getattr__(self, name: str) -> t.Any:471 return getattr(self._f, name)472475 def __enter__(self) -> "_AtomicFile":473 def __enter__(self) -> _AtomicFile:474 return self475478 def __exit__(self, exc_type: t.Optional[t.Type[BaseException]], *_: t.Any) -> None:476 def __exit__(477 self,478 exc_type: type[BaseException] | None,479 exc_value: BaseException | None,480 tb: TracebackType | None,481 ) -> None:482 self.close(delete=exc_type is not None)483484 def __repr__(self) -> str:485 return repr(self._f)
10 unmodified lines
496 return stream.__class__.__module__.startswith("ipykernel.")497498499def should_strip_ansi(497 stream: t.Optional[t.IO[t.Any]] = None, color: t.Optional[bool] = None500 stream: t.IO[t.Any] | None = None, color: bool | None = None501) -> bool:502 if color is None:503 if stream is None:504 stream = sys.stdin
11 unmodified lines
516 import locale517518 return locale.getpreferredencoding()519517 _ansi_stream_wrappers: t.MutableMapping[t.TextIO, t.TextIO] = WeakKeyDictionary()520 _ansi_stream_wrappers: cabc.MutableMapping[t.TextIO, t.TextIO] = WeakKeyDictionary()521522 def auto_wrap_for_ansi( # noqa: F811520 stream: t.TextIO, color: t.Optional[bool] = None523 stream: t.TextIO, color: bool | None = None524 ) -> t.TextIO:525 """Support ANSI color and style codes on Windows by wrapping a526 stream with colorama.527 """
33 unmodified lines
561 def _get_argv_encoding() -> str:562 return getattr(sys.stdin, "encoding", None) or sys.getfilesystemencoding()563564 def _get_windows_console_stream(562 f: t.TextIO, encoding: t.Optional[str], errors: t.Optional[str]563 ) -> t.Optional[t.TextIO]:565 f: t.TextIO, encoding: str | None, errors: str | None566 ) -> t.TextIO | None:567 return None568569570def term_len(x: str) -> int:
7 unmodified lines
578 return False579580581def _make_cached_stream_func(579 src_func: t.Callable[[], t.Optional[t.TextIO]],582 src_func: t.Callable[[], t.TextIO | None],583 wrapper_func: t.Callable[[], t.TextIO],581) -> t.Callable[[], t.Optional[t.TextIO]]:582 cache: t.MutableMapping[t.TextIO, t.TextIO] = WeakKeyDictionary()584) -> t.Callable[[], t.TextIO | None]:585 cache: cabc.MutableMapping[t.TextIO, t.TextIO] = WeakKeyDictionary()586584 def func() -> t.Optional[t.TextIO]:587 def func() -> t.TextIO | None:588 stream = src_func()589590 if stream is None:591 return None
18 unmodified lines
610_default_text_stdout = _make_cached_stream_func(lambda: sys.stdout, get_text_stdout)611_default_text_stderr = _make_cached_stream_func(lambda: sys.stderr, get_text_stderr)612613611binary_streams: t.Mapping[str, t.Callable[[], t.BinaryIO]] = {614binary_streams: cabc.Mapping[str, t.Callable[[], t.BinaryIO]] = {615 "stdin": get_binary_stdin,616 "stdout": get_binary_stdout,617 "stderr": get_binary_stderr,618}619617text_streams: t.Mapping[618 str, t.Callable[[t.Optional[str], t.Optional[str]], t.TextIO]619] = {620text_streams: cabc.Mapping[str, t.Callable[[str | None, str | None], t.TextIO]] = {621 "stdin": get_text_stdin,622 "stdout": get_text_stdout,623 "stderr": get_text_stderr,624}
modified:src/click/_termui_impl.py+35 added-34 removed
1 unmodified line
2This module contains implementations for the termui module. To keep the3import time of Click down, some infrequently used functionality is4placed in this module and only imported as needed.5"""6from __future__ import annotations78import collections.abc as cabc9import contextlib10import math11import os12import sys
26 unmodified lines
3940class ProgressBar(t.Generic[V]):41 def __init__(42 self,40 iterable: t.Optional[t.Iterable[V]],41 length: t.Optional[int] = None,43 iterable: cabc.Iterable[V] | None,44 length: int | None = None,45 fill_char: str = "#",46 empty_char: str = " ",47 bar_template: str = "%(bar)s",48 info_sep: str = " ",49 show_eta: bool = True,47 show_percent: t.Optional[bool] = None,50 show_percent: bool | None = None,51 show_pos: bool = False,49 item_show_func: t.Optional[t.Callable[[t.Optional[V]], t.Optional[str]]] = None,50 label: t.Optional[str] = None,51 file: t.Optional[t.TextIO] = None,52 color: t.Optional[bool] = None,52 item_show_func: t.Callable[[V | None], str | None] | None = None,53 label: str | None = None,54 file: t.TextIO | None = None,55 color: bool | None = None,56 update_min_steps: int = 1,57 width: int = 30,58 ) -> None:59 self.fill_char = fill_char
30 unmodified lines
90 length = None91 if iterable is None:92 if length is None:93 raise TypeError("iterable or length is required")91 iterable = t.cast(t.Iterable[V], range(length))92 self.iter: t.Iterable[V] = iter(iterable)94 iterable = t.cast("cabc.Iterable[V]", range(length))95 self.iter: cabc.Iterable[V] = iter(iterable)96 self.length = length97 self.pos = 095 self.avg: t.List[float] = []98 self.avg: list[float] = []99 self.last_eta: float100 self.start: float101 self.start = self.last_eta = time.time()102 self.eta_known: bool = False103 self.finished: bool = False101 self.max_width: t.Optional[int] = None104 self.max_width: int | None = None105 self.entered: bool = False103 self.current_item: t.Optional[V] = None106 self.current_item: V | None = None107 self.is_hidden: bool = not isatty(self.file)105 self._last_line: t.Optional[str] = None108 self._last_line: str | None = None109107 def __enter__(self) -> "ProgressBar[V]":110 def __enter__(self) -> ProgressBar[V]:111 self.entered = True112 self.render_progress()113 return self114115 def __exit__(116 self,114 exc_type: t.Optional[t.Type[BaseException]],115 exc_value: t.Optional[BaseException],116 tb: t.Optional[TracebackType],117 exc_type: type[BaseException] | None,118 exc_value: BaseException | None,119 tb: TracebackType | None,120 ) -> None:121 self.render_finish()122120 def __iter__(self) -> t.Iterator[V]:123 def __iter__(self) -> cabc.Iterator[V]:124 if not self.entered:125 raise RuntimeError("You need to use progress bars in a with block.")126 self.render_progress()127 return self.generator()
166 unmodified lines
294 self.avg = self.avg[-6:] + [step]295296 self.eta_known = self.length is not None297295 def update(self, n_steps: int, current_item: t.Optional[V] = None) -> None:298 def update(self, n_steps: int, current_item: V | None = None) -> None:299 """Update the progress bar by advancing a specified number of300 steps, and optionally set the ``current_item`` for this new301 position.302
22 unmodified lines
325 self.eta_known = False326 self.current_item = None327 self.finished = True328326 def generator(self) -> t.Iterator[V]:329 def generator(self) -> cabc.Iterator[V]:330 """Return a generator which yields the items added to the bar331 during construction, and updates the progress bar *after* the332 yielded block returns.333 """
25 unmodified lines
359 self.finish()360 self.render_progress()361362360def pager(generator: t.Iterable[str], color: t.Optional[bool] = None) -> None:363def pager(generator: cabc.Iterable[str], color: bool | None = None) -> None:364 """Decide what method to use for paging through text."""365 stdout = _default_text_stdout()366367 # There are no standard streams attached to write to. For example,
26 unmodified lines
394 finally:395 os.unlink(filename)396397395def _pipepager(generator: t.Iterable[str], cmd: str, color: t.Optional[bool]) -> None:398def _pipepager(generator: cabc.Iterable[str], cmd: str, color: bool | None) -> None:399 """Page through text by feeding it to another program. Invoking a400 pager through this might support colors.401 """402 import subprocess
41 unmodified lines
444 else:445 break446447445def _tempfilepager(446 generator: t.Iterable[str], cmd: str, color: t.Optional[bool]447) -> None:448def _tempfilepager(generator: cabc.Iterable[str], cmd: str, color: bool | None) -> None:449 """Page through text by invoking a program on a temporary file."""450 import tempfile451452 fd, filename = tempfile.mkstemp()
11 unmodified lines
464 os.unlink(filename)465466467def _nullpager(467 stream: t.TextIO, generator: t.Iterable[str], color: t.Optional[bool]468 stream: t.TextIO, generator: cabc.Iterable[str], color: bool | None469) -> None:470 """Simply print unformatted text. This is the ultimate fallback."""471 for text in generator:472 if not color:
3 unmodified lines
476477class Editor:478 def __init__(479 self,479 editor: t.Optional[str] = None,480 env: t.Optional[t.Mapping[str, str]] = None,480 editor: str | None = None,481 env: cabc.Mapping[str, str] | None = None,482 require_save: bool = True,483 extension: str = ".txt",484 ) -> None:485 self.editor = editor
18 unmodified lines
504 def edit_file(self, filename: str) -> None:505 import subprocess506507 editor = self.get_editor()507 environ: t.Optional[t.Dict[str, str]] = None508 environ: dict[str, str] | None = None509510 if self.env:511 environ = os.environ.copy()512 environ.update(self.env)
9 unmodified lines
522 raise ClickException(523 _("{editor}: Editing failed: {e}").format(editor=editor, e=e)524 ) from e525525 def edit(self, text: t.Optional[t.AnyStr]) -> t.Optional[t.AnyStr]:526 def edit(self, text: t.AnyStr | None) -> t.AnyStr | None:527 import tempfile528529 if not text:530 data = b""
99 unmodified lines
630 return 0631 return 1632633633def _translate_ch_to_exc(ch: str) -> t.Optional[BaseException]:634def _translate_ch_to_exc(ch: str) -> None:635 if ch == "\x03":636 raise KeyboardInterrupt()637638 if ch == "\x04" and not WIN: # Unix-like, Ctrl+D
8 unmodified lines
647if WIN:648 import msvcrt649650 @contextlib.contextmanager650 def raw_terminal() -> t.Iterator[int]:651 def raw_terminal() -> cabc.Iterator[int]:652 yield -1653654 def getchar(echo: bool) -> str:655 # The function `getch` will return a bytes object corresponding to
46 unmodified lines
702 import tty703 import termios704705 @contextlib.contextmanager705 def raw_terminal() -> t.Iterator[int]:706 f: t.Optional[t.TextIO]706 def raw_terminal() -> cabc.Iterator[int]:707 f: t.TextIO | None708 fd: int709710 if not isatty(sys.stdin):711 f = open("/dev/tty")
29 unmodified lines
modified:src/click/_textwrap.py+6 added-4 removed
1from __future__ import annotations23import collections.abc as cabc4import textwrap2import typing as t5from contextlib import contextmanager678class TextWrapper(textwrap.TextWrapper):9 def _handle_long_word(10 self,9 reversed_chunks: t.List[str],10 cur_line: t.List[str],11 reversed_chunks: list[str],12 cur_line: list[str],13 cur_len: int,14 width: int,15 ) -> None:16 space_left = max(width - cur_len, 1)
7 unmodified lines
24 elif not cur_line:25 cur_line.append(reversed_chunks.pop())2627 @contextmanager26 def extra_indent(self, indent: str) -> t.Iterator[None]:28 def extra_indent(self, indent: str) -> cabc.Iterator[None]:29 old_initial_indent = self.initial_indent30 old_subsequent_indent = self.subsequent_indent31 self.initial_indent += indent32 self.subsequent_indent += indent
19 unmodified lines
modified:src/click/_winconsole.py+7 added-4 removed
4 unmodified lines
5# There are some general differences in regards to how this works6# compared to the original patches as we do not need to patch7# the entire interpreter but just work in our little world of8# echo and prompt.9from __future__ import annotations1011import collections.abc as cabc12import io13import sys14import time15import typing as t
182 unmodified lines
198 except Exception:199 pass200 return self.buffer.write(x)201199 def writelines(self, lines: t.Iterable[t.AnyStr]) -> None:202 def writelines(self, lines: cabc.Iterable[t.AnyStr]) -> None:203 for line in lines:204 self.write(line)205206 def __getattr__(self, name: str) -> t.Any:
35 unmodified lines
242 )243 return t.cast(t.TextIO, ConsoleStream(text_stream, buffer_stream))244245243_stream_factories: t.Mapping[int, t.Callable[[t.BinaryIO], t.TextIO]] = {246_stream_factories: cabc.Mapping[int, t.Callable[[t.BinaryIO], t.TextIO]] = {247 0: _get_text_stdin,248 1: _get_text_stdout,249 2: _get_text_stderr,250}
12 unmodified lines
263 return bool(GetConsoleMode(handle, byref(DWORD())))264265266def _get_windows_console_stream(264 f: t.TextIO, encoding: t.Optional[str], errors: t.Optional[str]265) -> t.Optional[t.TextIO]:267 f: t.TextIO, encoding: str | None, errors: str | None268) -> t.TextIO | None:269 if (270 get_buffer is not None271 and encoding in {"utf-16-le", None}272 and errors in {"strict", None}
10 unmodified lines
modified:src/click/core.py+205 added-212 removed
1from __future__ import annotations23import collections.abc as cabc4import enum5import errno6import inspect7import os8import sys9import typing as t10from collections import abc11from contextlib import AbstractContextManager12from contextlib import contextmanager13from contextlib import ExitStack14from functools import update_wrapper15from gettext import gettext as _
25 unmodified lines
41from .utils import make_str42from .utils import PacifyFlushWrapper4344if t.TYPE_CHECKING:41 import typing_extensions as te45 from .shell_completion import CompletionItem4644F = t.TypeVar("F", bound=t.Callable[..., t.Any])47F = t.TypeVar("F", bound="t.Callable[..., t.Any]")48V = t.TypeVar("V")495051def _complete_visible_commands(49 ctx: "Context", incomplete: str50) -> t.Iterator[t.Tuple[str, "Command"]]:52 ctx: Context, incomplete: str53) -> cabc.Iterator[tuple[str, Command]]:54 """List all the subcommands of a group that start with the55 incomplete value and aren't hidden.5657 :param ctx: Invocation context for the group.
9 unmodified lines
67 yield name, command686970def _check_nested_chain(68 base_command: "Group", cmd_name: str, cmd: "Command", register: bool = False71 base_command: Group, cmd_name: str, cmd: Command, register: bool = False72) -> None:73 if not base_command.chain or not isinstance(cmd, Group):74 return75
10 unmodified lines
8687 raise RuntimeError(message)888987def batch(iterable: t.Iterable[V], batch_size: int) -> t.List[t.Tuple[V, ...]]:90def batch(iterable: cabc.Iterable[V], batch_size: int) -> list[tuple[V, ...]]:91 return list(zip(*repeat(iter(iterable), batch_size)))929394@contextmanager95def augment_usage_errors(93 ctx: "Context", param: t.Optional["Parameter"] = None94) -> t.Iterator[None]:96 ctx: Context, param: Parameter | None = None97) -> cabc.Iterator[None]:98 """Context manager that attaches extra information to exceptions."""99 try:100 yield101 except BadParameter as e:
8 unmodified lines
110 raise111112113def iter_params_for_processing(111 invocation_order: t.Sequence["Parameter"],112 declaration_order: t.Sequence["Parameter"],113) -> t.List["Parameter"]:114 invocation_order: cabc.Sequence[Parameter],115 declaration_order: cabc.Sequence[Parameter],116) -> list[Parameter]:117 """Given a sequence of parameters in the order as should be considered118 for processing and an iterable of parameters that exist, this returns119 a list in the correct order as they should be processed.120 """121119 def sort_key(item: "Parameter") -> t.Tuple[bool, float]:122 def sort_key(item: Parameter) -> tuple[bool, float]:123 try:124 idx: float = invocation_order.index(item)125 except ValueError:126 idx = float("inf")
130 unmodified lines
257258 #: The formatter class to create with :meth:`make_formatter`.259 #:260 #: .. versionadded:: 8.0258 formatter_class: t.Type["HelpFormatter"] = HelpFormatter261 formatter_class: type[HelpFormatter] = HelpFormatter262263 def __init__(264 self,262 command: "Command",263 parent: t.Optional["Context"] = None,264 info_name: t.Optional[str] = None,265 obj: t.Optional[t.Any] = None,266 auto_envvar_prefix: t.Optional[str] = None,267 default_map: t.Optional[t.MutableMapping[str, t.Any]] = None,268 terminal_width: t.Optional[int] = None,269 max_content_width: t.Optional[int] = None,265 command: Command,266 parent: Context | None = None,267 info_name: str | None = None,268 obj: t.Any | None = None,269 auto_envvar_prefix: str | None = None,270 default_map: cabc.MutableMapping[str, t.Any] | None = None,271 terminal_width: int | None = None,272 max_content_width: int | None = None,273 resilient_parsing: bool = False,271 allow_extra_args: t.Optional[bool] = None,272 allow_interspersed_args: t.Optional[bool] = None,273 ignore_unknown_options: t.Optional[bool] = None,274 help_option_names: t.Optional[t.List[str]] = None,275 token_normalize_func: t.Optional[t.Callable[[str], str]] = None,276 color: t.Optional[bool] = None,277 show_default: t.Optional[bool] = None,274 allow_extra_args: bool | None = None,275 allow_interspersed_args: bool | None = None,276 ignore_unknown_options: bool | None = None,277 help_option_names: list[str] | None = None,278 token_normalize_func: t.Callable[[str], str] | None = None,279 color: bool | None = None,280 show_default: bool | None = None,281 ) -> None:282 #: the parent context or `None` if none exists.283 self.parent = parent284 #: the :class:`Command` for this context.
1 unmodified line
286 #: the descriptive information name287 self.info_name = info_name288 #: Map of parameter names to their parsed values. Parameters289 #: with ``expose_value=False`` are not stored.287 self.params: t.Dict[str, t.Any] = {}290 self.params: dict[str, t.Any] = {}291 #: the leftover arguments.289 self.args: t.List[str] = []292 self.args: list[str] = []293 #: protected arguments. These are arguments that are prepended294 #: to `args` when certain parsing scenarios are encountered but295 #: must be never propagated to another arguments. This is used296 #: to implement nested parsing.294 self._protected_args: t.List[str] = []297 self._protected_args: list[str] = []298 #: the collected prefixes of the command's options.296 self._opt_prefixes: t.Set[str] = set(parent._opt_prefixes) if parent else set()299 self._opt_prefixes: set[str] = set(parent._opt_prefixes) if parent else set()300301 if obj is None and parent is not None:302 obj = parent.obj303304 #: the user object stored.305 self.obj: t.Any = obj303 self._meta: t.Dict[str, t.Any] = getattr(parent, "meta", {})306 self._meta: dict[str, t.Any] = getattr(parent, "meta", {})307308 #: A dictionary (-like object) with defaults for parameters.309 if (310 default_map is None
2 unmodified lines
313 and parent.default_map is not None314 ):315 default_map = parent.default_map.get(info_name)316314 self.default_map: t.Optional[t.MutableMapping[str, t.Any]] = default_map317 self.default_map: cabc.MutableMapping[str, t.Any] | None = default_map318319 #: This flag indicates if a subcommand is going to be executed. A320 #: group callback can use this information to figure out if it's321 #: being executed directly or because the execution flow passes
3 unmodified lines
325 #: If chaining is enabled this will be set to ``'*'`` in case326 #: any commands are executed. It is however not possible to327 #: figure out which ones. If you require this knowledge you328 #: should use a :func:`result_callback`.326 self.invoked_subcommand: t.Optional[str] = None329 self.invoked_subcommand: str | None = None330331 if terminal_width is None and parent is not None:332 terminal_width = parent.terminal_width333334 #: The width of the terminal (None is autodetection).332 self.terminal_width: t.Optional[int] = terminal_width335 self.terminal_width: int | None = terminal_width336337 if max_content_width is None and parent is not None:338 max_content_width = parent.max_content_width339340 #: The maximum width of formatted content (None implies a sensible341 #: default which is 80 for most things).339 self.max_content_width: t.Optional[int] = max_content_width342 self.max_content_width: int | None = max_content_width343344 if allow_extra_args is None:345 allow_extra_args = command.allow_extra_args346
31 unmodified lines
378 else:379 help_option_names = ["--help"]380381 #: The names for the help options.379 self.help_option_names: t.List[str] = help_option_names382 self.help_option_names: list[str] = help_option_names383384 if token_normalize_func is None and parent is not None:385 token_normalize_func = parent.token_normalize_func386387 #: An optional normalization function for tokens. This is388 #: options, choices, commands etc.386 self.token_normalize_func: t.Optional[387 t.Callable[[str], str]388 ] = token_normalize_func389 self.token_normalize_func: t.Callable[[str], str] | None = token_normalize_func390391 #: Indicates if resilient parsing is enabled. In that case Click392 #: will do its best to not cause any failures and default values393 #: will be ignored. Useful for completion.
16 unmodified lines
410411 if auto_envvar_prefix is not None:412 auto_envvar_prefix = auto_envvar_prefix.replace("-", "_")413413 self.auto_envvar_prefix: t.Optional[str] = auto_envvar_prefix414 self.auto_envvar_prefix: str | None = auto_envvar_prefix415416 if color is None and parent is not None:417 color = parent.color418419 #: Controls if styling output is wanted or not.419 self.color: t.Optional[bool] = color420 self.color: bool | None = color421422 if show_default is None and parent is not None:423 show_default = parent.show_default424425 #: Show option default values when formatting help text.425 self.show_default: t.Optional[bool] = show_default426 self.show_default: bool | None = show_default427427 self._close_callbacks: t.List[t.Callable[[], t.Any]] = []428 self._close_callbacks: list[t.Callable[[], t.Any]] = []429 self._depth = 0429 self._parameter_source: t.Dict[str, ParameterSource] = {}430 self._parameter_source: dict[str, ParameterSource] = {}431 self._exit_stack = ExitStack()432433 @property433 def protected_args(self) -> t.List[str]:434 def protected_args(self) -> list[str]:435 import warnings436437 warnings.warn(438 "'protected_args' is deprecated and will be removed in Click 9.0."
2 unmodified lines
441 stacklevel=2,442 )443 return self._protected_args444444 def to_info_dict(self) -> t.Dict[str, t.Any]:445 def to_info_dict(self) -> dict[str, t.Any]:446 """Gather information that could be useful for a tool generating447 user-facing documentation. This traverses the entire CLI448 structure.449
12 unmodified lines
462 "ignore_unknown_options": self.ignore_unknown_options,463 "auto_envvar_prefix": self.auto_envvar_prefix,464 }465465 def __enter__(self) -> "Context":466 def __enter__(self) -> Context:467 self._depth += 1468 push_context(self)469 return self470471 def __exit__(472 self,472 exc_type: t.Optional[t.Type[BaseException]],473 exc_value: t.Optional[BaseException],474 tb: t.Optional[TracebackType],473 exc_type: type[BaseException] | None,474 exc_value: BaseException | None,475 tb: TracebackType | None,476 ) -> None:477 self._depth -= 1478 if self._depth == 0:479 self.close()480 pop_context()481482 @contextmanager482 def scope(self, cleanup: bool = True) -> t.Iterator["Context"]:483 def scope(self, cleanup: bool = True) -> cabc.Iterator[Context]:484 """This helper method can be used with the context object to promote485 it to the current thread local (see :func:`get_current_context`).486 The default behavior of this is to invoke the cleanup functions which487 can be disabled by setting `cleanup` to `False`. The cleanup
29 unmodified lines
517 if not cleanup:518 self._depth -= 1519520 @property520 def meta(self) -> t.Dict[str, t.Any]:521 def meta(self) -> dict[str, t.Any]:522 """This is a dictionary which is shared with all the contexts523 that are nested. It exists so that click utilities can store some524 state here if they need to. It is however the responsibility of525 that code to manage this dictionary well.
32 unmodified lines
558 return self.formatter_class(559 width=self.terminal_width, max_width=self.max_content_width560 )561561 def with_resource(self, context_manager: t.ContextManager[V]) -> V:562 def with_resource(self, context_manager: AbstractContextManager[V]) -> V:563 """Register a resource as if it were used in a ``with``564 statement. The resource will be cleaned up when the context is565 popped.566
60 unmodified lines
627628 rv = f"{' '.join(parent_command_path)} {rv}"629 return rv.lstrip()630630 def find_root(self) -> "Context":631 def find_root(self) -> Context:632 """Finds the outermost context."""633 node = self634 while node.parent is not None:635 node = node.parent636 return node637637 def find_object(self, object_type: t.Type[V]) -> t.Optional[V]:638 def find_object(self, object_type: type[V]) -> V | None:639 """Finds the closest object of a given type."""639 node: t.Optional["Context"] = self640 node: Context | None = self641642 while node is not None:643 if isinstance(node.obj, object_type):644 return node.obj
1 unmodified line
646 node = node.parent647648 return None649649 def ensure_object(self, object_type: t.Type[V]) -> V:650 def ensure_object(self, object_type: type[V]) -> V:651 """Like :meth:`find_object` but sets the innermost object to a652 new instance of `object_type` if it does not exist.653 """654 rv = self.find_object(object_type)
1 unmodified line
656 self.obj = rv = object_type()657 return rv658659 @t.overload659 def lookup_default(660 self, name: str, call: "te.Literal[True]" = True661 ) -> t.Optional[t.Any]:660 def lookup_default(self, name: str, call: t.Literal[True] = True) -> t.Any | None:661 ...662663 @t.overload664 def lookup_default(666 self, name: str, call: "te.Literal[False]" = ...667 ) -> t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]]:665 self, name: str, call: t.Literal[False] = ...666 ) -> t.Any | t.Callable[[], t.Any] | None:667 ...668670 def lookup_default(self, name: str, call: bool = True) -> t.Optional[t.Any]:669 def lookup_default(self, name: str, call: bool = True) -> t.Any | None:670 """Get the default for a parameter from :attr:`default_map`.671672 :param name: Name of the parameter.673 :param call: If the default is a callable, call it. Disable to
11 unmodified lines
685 return value686687 return None688690 def fail(self, message: str) -> "te.NoReturn":689 def fail(self, message: str) -> t.NoReturn:690 """Aborts the execution of the program with a specific error691 message.692693 :param message: the error message to fail with.694 """695 raise UsageError(message, self)696698 def abort(self) -> "te.NoReturn":697 def abort(self) -> t.NoReturn:698 """Aborts the script."""699 raise Abort()700702 def exit(self, code: int = 0) -> "te.NoReturn":701 def exit(self, code: int = 0) -> t.NoReturn:702 """Exits the application with a given exit code."""703 raise Exit(code)704705 def get_usage(self) -> str:
7 unmodified lines
713 context and command.714 """715 return self.command.get_help(self)716718 def _make_sub_context(self, command: "Command") -> "Context":717 def _make_sub_context(self, command: Command) -> Context:718 """Create a new context of the same type as this context, but719 for a new command.720721 :meta private:
2 unmodified lines
724725 @t.overload726 def invoke(727 __self, # noqa: B902729 __callback: "t.Callable[..., V]",728 __callback: t.Callable[..., V],729 *args: t.Any,730 **kwargs: t.Any,731 ) -> V:732 ...733734 @t.overload735 def invoke(736 __self, # noqa: B902738 __callback: "Command",737 __callback: Command,738 *args: t.Any,739 **kwargs: t.Any,740 ) -> t.Any:741 ...742743 def invoke(744 __self, # noqa: B902746 __callback: t.Union["Command", "t.Callable[..., V]"],745 __callback: Command | t.Callable[..., V],746 *args: t.Any,747 **kwargs: t.Any,749 ) -> t.Union[t.Any, V]:748 ) -> t.Any | V:749 """Invokes a command callback in exactly the way it expects. There750 are two ways to invoke this method:751752 1. the first argument can be a callback and all other arguments and
40 unmodified lines
793 with ctx:794 return __callback(*args, **kwargs)795796 def forward(798 __self, __cmd: "Command", *args: t.Any, **kwargs: t.Any # noqa: B902797 __self, __cmd: Command, *args: t.Any, **kwargs: t.Any # noqa: B902798 ) -> t.Any:799 """Similar to :meth:`invoke` but fills in default keyword800 arguments from the current context if the other command expects801 it. This cannot invoke callbacks directly, only other commands.
20 unmodified lines
822 :param source: A member of :class:`~click.core.ParameterSource`.823 """824 self._parameter_source[name] = source825827 def get_parameter_source(self, name: str) -> t.Optional[ParameterSource]:826 def get_parameter_source(self, name: str) -> ParameterSource | None:827 """Get the source of a parameter. This indicates the location828 from which the value of the parameter was obtained.829830 This can be useful for determining when a user specified a value
58 unmodified lines
889890 #: The context class to create with :meth:`make_context`.891 #:892 #: .. versionadded:: 8.0894 context_class: t.Type[Context] = Context893 context_class: type[Context] = Context894895 #: the default for the :attr:`Context.allow_extra_args` flag.896 allow_extra_args = False897
4 unmodified lines
902 ignore_unknown_options = False903904 def __init__(905 self,907 name: t.Optional[str],908 context_settings: t.Optional[t.MutableMapping[str, t.Any]] = None,909 callback: t.Optional[t.Callable[..., t.Any]] = None,910 params: t.Optional[t.List["Parameter"]] = None,911 help: t.Optional[str] = None,912 epilog: t.Optional[str] = None,913 short_help: t.Optional[str] = None,914 options_metavar: t.Optional[str] = "[OPTIONS]",906 name: str | None,907 context_settings: cabc.MutableMapping[str, t.Any] | None = None,908 callback: t.Callable[..., t.Any] | None = None,909 params: list[Parameter] | None = None,910 help: str | None = None,911 epilog: str | None = None,912 short_help: str | None = None,913 options_metavar: str | None = "[OPTIONS]",914 add_help_option: bool = True,915 no_args_is_help: bool = False,916 hidden: bool = False,917 deprecated: bool = False,
7 unmodified lines
925 if context_settings is None:926 context_settings = {}927928 #: an optional dictionary with defaults passed to the context.930 self.context_settings: t.MutableMapping[str, t.Any] = context_settings929 self.context_settings: cabc.MutableMapping[str, t.Any] = context_settings930931 #: the callback to execute when the command fires. This might be932 #: `None` in which case nothing happens.933 self.callback = callback934 #: the list of parameters for this command in the order they935 #: should show up in the help page and execute. Eager parameters936 #: will automatically be handled before non eager ones.938 self.params: t.List["Parameter"] = params or []937 self.params: list[Parameter] = params or []938 self.help = help939 self.epilog = epilog940 self.options_metavar = options_metavar941 self.short_help = short_help
1 unmodified line
943 self.no_args_is_help = no_args_is_help944 self.hidden = hidden945 self.deprecated = deprecated946948 def to_info_dict(self, ctx: Context) -> t.Dict[str, t.Any]:947 def to_info_dict(self, ctx: Context) -> dict[str, t.Any]:948 return {949 "name": self.name,950 "params": [param.to_info_dict() for param in self.get_params(ctx)],951 "help": self.help,
14 unmodified lines
966 formatter = ctx.make_formatter()967 self.format_usage(ctx, formatter)968 return formatter.getvalue().rstrip("\n")969971 def get_params(self, ctx: Context) -> t.List["Parameter"]:970 def get_params(self, ctx: Context) -> list[Parameter]:971 rv = self.params972 help_option = self.get_help_option(ctx)973974 if help_option is not None:
8 unmodified lines
983 """984 pieces = self.collect_usage_pieces(ctx)985 formatter.write_usage(ctx.command_path, " ".join(pieces))986988 def collect_usage_pieces(self, ctx: Context) -> t.List[str]:987 def collect_usage_pieces(self, ctx: Context) -> list[str]:988 """Returns all the pieces that go into the usage line and returns989 it as a list of strings.990 """991 rv = [self.options_metavar] if self.options_metavar else []
2 unmodified lines
994 rv.extend(param.get_usage_pieces(ctx))995996 return rv997999 def get_help_option_names(self, ctx: Context) -> t.List[str]:998 def get_help_option_names(self, ctx: Context) -> list[str]:999 """Returns the names for the help option."""1000 all_names = set(ctx.help_option_names)1001 for param in self.params:1002 all_names.difference_update(param.opts)1003 all_names.difference_update(param.secondary_opts)1004 return list(all_names)10051007 def get_help_option(self, ctx: Context) -> t.Optional["Option"]:1006 def get_help_option(self, ctx: Context) -> Option | None:1007 """Returns the help option object."""1008 help_options = self.get_help_option_names(ctx)10091010 if not help_options or not self.add_help_option:1011 return None10121014 def show_help(ctx: Context, param: "Parameter", value: str) -> None:1013 def show_help(ctx: Context, param: Parameter, value: str) -> None:1014 if value and not ctx.resilient_parsing:1015 echo(ctx.get_help(), color=ctx.color)1016 ctx.exit()1017
94 unmodified lines
1112 formatter.write_text(epilog)11131114 def make_context(1115 self,1117 info_name: t.Optional[str],1118 args: t.List[str],1119 parent: t.Optional[Context] = None,1116 info_name: str | None,1117 args: list[str],1118 parent: Context | None = None,1119 **extra: t.Any,1120 ) -> Context:1121 """This function when given an info name and arguments will kick1122 off the parsing and create a new :class:`Context`. It does not
24 unmodified lines
1147 with ctx.scope(cleanup=False):1148 self.parse_args(ctx, args)1149 return ctx11501152 def parse_args(self, ctx: Context, args: t.List[str]) -> t.List[str]:1151 def parse_args(self, ctx: Context, args: list[str]) -> list[str]:1152 if not args and self.no_args_is_help and not ctx.resilient_parsing:1153 echo(ctx.get_help(), color=ctx.color)1154 ctx.exit()1155
28 unmodified lines
11841185 if self.callback is not None:1186 return ctx.invoke(self.callback, **ctx.params)11871189 def shell_complete(self, ctx: Context, incomplete: str) -> t.List["CompletionItem"]:1188 def shell_complete(self, ctx: Context, incomplete: str) -> list[CompletionItem]:1189 """Return a list of completions for the incomplete value. Looks1190 at the names of options and chained multi-commands.11911192 Any command could be part of a chained multi-command, so sibling
5 unmodified lines
1198 .. versionadded:: 8.01199 """1200 from click.shell_completion import CompletionItem12011203 results: t.List["CompletionItem"] = []1202 results: list[CompletionItem] = []12031204 if incomplete and not incomplete[0].isalnum():1205 for param in self.get_params(ctx):1206 if (
27 unmodified lines
12341235 @t.overload1236 def main(1237 self,1239 args: t.Optional[t.Sequence[str]] = None,1240 prog_name: t.Optional[str] = None,1241 complete_var: t.Optional[str] = None,1242 standalone_mode: "te.Literal[True]" = True,1238 args: cabc.Sequence[str] | None = None,1239 prog_name: str | None = None,1240 complete_var: str | None = None,1241 standalone_mode: t.Literal[True] = True,1242 **extra: t.Any,1244 ) -> "te.NoReturn":1243 ) -> t.NoReturn:1244 ...12451246 @t.overload1247 def main(1248 self,1250 args: t.Optional[t.Sequence[str]] = None,1251 prog_name: t.Optional[str] = None,1252 complete_var: t.Optional[str] = None,1249 args: cabc.Sequence[str] | None = None,1250 prog_name: str | None = None,1251 complete_var: str | None = None,1252 standalone_mode: bool = ...,1253 **extra: t.Any,1254 ) -> t.Any:1255 ...12561257 def main(1258 self,1260 args: t.Optional[t.Sequence[str]] = None,1261 prog_name: t.Optional[str] = None,1262 complete_var: t.Optional[str] = None,1259 args: cabc.Sequence[str] | None = None,1260 prog_name: str | None = None,1261 complete_var: str | None = None,1262 standalone_mode: bool = True,1263 windows_expand_args: bool = True,1264 **extra: t.Any,1265 ) -> t.Any:
102 unmodified lines
1368 sys.exit(1)13691370 def _main_shell_completion(1371 self,1373 ctx_args: t.MutableMapping[str, t.Any],1372 ctx_args: cabc.MutableMapping[str, t.Any],1373 prog_name: str,1375 complete_var: t.Optional[str] = None,1374 complete_var: str | None = None,1375 ) -> None:1376 """Check if the shell is asking for tab completion, process1377 that, then exit early. Called from :meth:`main` before the1378 program is invoked.
77 unmodified lines
1456 #: as the default :class:`Command` class. This is useful to make all1457 #: subcommands use a custom command class.1458 #:1459 #: .. versionadded:: 8.01461 command_class: t.Optional[t.Type[Command]] = None1460 command_class: type[Command] | None = None14611462 #: If set, this is used by the group's :meth:`group` decorator1463 #: as the default :class:`Group` class. This is useful to make all1464 #: subgroups use a custom group class.
3 unmodified lines
1468 #: default class. This makes a custom group class continue to make1469 #: custom groups.1470 #:1471 #: .. versionadded:: 8.01473 group_class: t.Optional[t.Union[t.Type["Group"], t.Type[type]]] = None1472 group_class: type[Group] | type[type] | None = None1473 # Literal[type] isn't valid, so use Type[type]14741475 def __init__(1476 self,1478 name: t.Optional[str] = None,1479 commands: t.Optional[1480 t.Union[t.MutableMapping[str, Command], t.Sequence[Command]]1481 ] = None,1477 name: str | None = None,1478 commands: cabc.MutableMapping[str, Command]1479 | cabc.Sequence[Command]1480 | None = None,1481 invoke_without_command: bool = False,1483 no_args_is_help: t.Optional[bool] = None,1484 subcommand_metavar: t.Optional[str] = None,1482 no_args_is_help: bool | None = None,1483 subcommand_metavar: str | None = None,1484 chain: bool = False,1486 result_callback: t.Optional[t.Callable[..., t.Any]] = None,1485 result_callback: t.Callable[..., t.Any] | None = None,1486 **kwargs: t.Any,1487 ) -> None:1488 super().__init__(name, **kwargs)1489
2 unmodified lines
1492 elif isinstance(commands, abc.Sequence):1493 commands = {c.name: c for c in commands if c.name is not None}14941495 #: The registered subcommands by their exported names.1497 self.commands: t.MutableMapping[str, Command] = commands1496 self.commands: cabc.MutableMapping[str, Command] = commands14971498 if no_args_is_help is None:1499 no_args_is_help = not invoke_without_command1500
18 unmodified lines
1519 raise RuntimeError(1520 "A group in chain mode cannot have optional arguments."1521 )15221524 def to_info_dict(self, ctx: Context) -> t.Dict[str, t.Any]:1523 def to_info_dict(self, ctx: Context) -> dict[str, t.Any]:1524 info_dict = super().to_info_dict(ctx)1525 commands = {}15261527 for name in self.list_commands(ctx):
9 unmodified lines
15371538 info_dict.update(commands=commands, chain=self.chain)1539 return info_dict15401542 def add_command(self, cmd: Command, name: t.Optional[str] = None) -> None:1541 def add_command(self, cmd: Command, name: str | None = None) -> None:1542 """Registers another :class:`Command` with this group. If the name1543 is not provided, the name of the command is used.1544 """1545 name = name or cmd.name
13 unmodified lines
1559 ...15601561 def command(1562 self, *args: t.Any, **kwargs: t.Any1564 ) -> t.Union[t.Callable[[t.Callable[..., t.Any]], Command], Command]:1563 ) -> t.Callable[[t.Callable[..., t.Any]], Command] | Command:1564 """A shortcut decorator for declaring and attaching a command to1565 the group. This takes the same arguments as :func:`command` and1566 immediately registers the created command with this group by1567 calling :meth:`add_command`.
8 unmodified lines
1576 Added the :attr:`command_class` attribute.1577 """1578 from .decorators import command15791581 func: t.Optional[t.Callable[..., t.Any]] = None1580 func: t.Callable[..., t.Any] | None = None15811582 if args and callable(args[0]):1583 assert (1584 len(args) == 1 and not kwargs
14 unmodified lines
15991600 return decorator16011602 @t.overload1604 def group(self, __func: t.Callable[..., t.Any]) -> "Group":1603 def group(self, __func: t.Callable[..., t.Any]) -> Group:1604 ...16051606 @t.overload1607 def group(1608 self, *args: t.Any, **kwargs: t.Any1610 ) -> t.Callable[[t.Callable[..., t.Any]], "Group"]:1609 ) -> t.Callable[[t.Callable[..., t.Any]], Group]:1610 ...16111612 def group(1613 self, *args: t.Any, **kwargs: t.Any1615 ) -> t.Union[t.Callable[[t.Callable[..., t.Any]], "Group"], "Group"]:1614 ) -> t.Callable[[t.Callable[..., t.Any]], Group] | Group:1615 """A shortcut decorator for declaring and attaching a group to1616 the group. This takes the same arguments as :func:`group` and1617 immediately registers the created group with this group by1618 calling :meth:`add_command`.
8 unmodified lines
1627 Added the :attr:`group_class` attribute.1628 """1629 from .decorators import group16301632 func: t.Optional[t.Callable[..., t.Any]] = None1631 func: t.Callable[..., t.Any] | None = None16321633 if args and callable(args[0]):1634 assert (1635 len(args) == 1 and not kwargs
6 unmodified lines
1642 kwargs["cls"] = type(self)1643 else:1644 kwargs["cls"] = self.group_class16451647 def decorator(f: t.Callable[..., t.Any]) -> "Group":1646 def decorator(f: t.Callable[..., t.Any]) -> Group:1647 cmd: Group = group(*args, **kwargs)(f)1648 self.add_command(cmd)1649 return cmd1650
46 unmodified lines
1697 return rv16981699 return decorator17001702 def get_command(self, ctx: Context, cmd_name: str) -> t.Optional[Command]:1701 def get_command(self, ctx: Context, cmd_name: str) -> Command | None:1702 """Given a context and a command name, this returns a :class:`Command`1703 object if it exists or returns ``None``.1704 """1705 return self.commands.get(cmd_name)17061708 def list_commands(self, ctx: Context) -> t.List[str]:1707 def list_commands(self, ctx: Context) -> list[str]:1708 """Returns a list of subcommand names in the order they should appear."""1709 return sorted(self.commands)17101712 def collect_usage_pieces(self, ctx: Context) -> t.List[str]:1711 def collect_usage_pieces(self, ctx: Context) -> list[str]:1712 rv = super().collect_usage_pieces(ctx)1713 rv.append(self.subcommand_metavar)1714 return rv1715
28 unmodified lines
1744 if rows:1745 with formatter.section(_("Commands")):1746 formatter.write_dl(rows)17471749 def parse_args(self, ctx: Context, args: t.List[str]) -> t.List[str]:1748 def parse_args(self, ctx: Context, args: list[str]) -> list[str]:1749 if not args and self.no_args_is_help and not ctx.resilient_parsing:1750 echo(ctx.get_help(), color=ctx.color)1751 ctx.exit()1752
75 unmodified lines
1828 rv.append(sub_ctx.command.invoke(sub_ctx))1829 return _process_result(rv)18301831 def resolve_command(1833 self, ctx: Context, args: t.List[str]1834 ) -> t.Tuple[t.Optional[str], t.Optional[Command], t.List[str]]:1832 self, ctx: Context, args: list[str]1833 ) -> tuple[str | None, Command | None, list[str]]:1834 cmd_name = make_str(args[0])1835 original_cmd_name = cmd_name18361837 # Get the command
16 unmodified lines
1854 self.parse_args(ctx, ctx.args)1855 ctx.fail(_("No such command {name!r}.").format(name=original_cmd_name))1856 return cmd_name if cmd else None, cmd, args[1:]18571859 def shell_complete(self, ctx: Context, incomplete: str) -> t.List["CompletionItem"]:1858 def shell_complete(self, ctx: Context, incomplete: str) -> list[CompletionItem]:1859 """Return a list of completions for the incomplete value. Looks1860 at the names of options, subcommands, and chained1861 multi-commands.1862
36 unmodified lines
1899 """19001901 def __init__(1902 self,1904 name: t.Optional[str] = None,1905 sources: t.Optional[t.List[Group]] = None,1903 name: str | None = None,1904 sources: list[Group] | None = None,1905 **kwargs: t.Any,1906 ) -> None:1907 super().__init__(name, **kwargs)1908 #: The list of registered groups.1910 self.sources: t.List[Group] = sources or []1909 self.sources: list[Group] = sources or []19101911 def add_source(self, group: Group) -> None:1912 """Add a group as a source of commands."""1913 self.sources.append(group)19141916 def get_command(self, ctx: Context, cmd_name: str) -> t.Optional[Command]:1915 def get_command(self, ctx: Context, cmd_name: str) -> Command | None:1916 rv = super().get_command(ctx, cmd_name)19171918 if rv is not None:1919 return rv
8 unmodified lines
1928 return rv19291930 return None19311933 def list_commands(self, ctx: Context) -> t.List[str]:1934 rv: t.Set[str] = set(super().list_commands(ctx))1932 def list_commands(self, ctx: Context) -> list[str]:1933 rv: set[str] = set(super().list_commands(ctx))19341935 for source in self.sources:1936 rv.update(source.list_commands(ctx))19371938 return sorted(rv)193919401942def _check_iter(value: t.Any) -> t.Iterator[t.Any]:1941def _check_iter(value: t.Any) -> cabc.Iterator[t.Any]:1942 """Check if the value is iterable but not a string. Raises a type1943 error, or return an iterator over the value.1944 """1945 if isinstance(value, str):
79 unmodified lines
2025 param_type_name = "parameter"20262027 def __init__(2028 self,2030 param_decls: t.Optional[t.Sequence[str]] = None,2031 type: t.Optional[t.Union[types.ParamType, t.Any]] = None,2029 param_decls: cabc.Sequence[str] | None = None,2030 type: types.ParamType | t.Any | None = None,2031 required: bool = False,2033 default: t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]] = None,2034 callback: t.Optional[t.Callable[[Context, "Parameter", t.Any], t.Any]] = None,2035 nargs: t.Optional[int] = None,2032 default: t.Any | t.Callable[[], t.Any] | None = None,2033 callback: t.Callable[[Context, Parameter, t.Any], t.Any] | None = None,2034 nargs: int | None = None,2035 multiple: bool = False,2037 metavar: t.Optional[str] = None,2036 metavar: str | None = None,2037 expose_value: bool = True,2038 is_eager: bool = False,2040 envvar: t.Optional[t.Union[str, t.Sequence[str]]] = None,2041 shell_complete: t.Optional[2042 t.Callable[2043 [Context, "Parameter", str],2044 t.Union[t.List["CompletionItem"], t.List[str]],2045 ]2046 ] = None,2039 envvar: str | cabc.Sequence[str] | None = None,2040 shell_complete: t.Callable[2041 [Context, Parameter, str], list[CompletionItem] | list[str]2042 ]2043 | None = None,2044 ) -> None:2048 self.name: t.Optional[str]2049 self.opts: t.List[str]2050 self.secondary_opts: t.List[str]2045 self.name: str | None2046 self.opts: list[str]2047 self.secondary_opts: list[str]2048 self.name, self.opts, self.secondary_opts = self._parse_decls(2049 param_decls or (), expose_value2050 )2051 self.type: types.ParamType = types.convert_type(type, default)
57 unmodified lines
2109 raise ValueError(2110 f"'default' {subject} must match nargs={nargs}."2111 )21122116 def to_info_dict(self) -> t.Dict[str, t.Any]:2113 def to_info_dict(self) -> dict[str, t.Any]:2114 """Gather information that could be useful for a tool generating2115 user-facing documentation.21162117 Use :meth:`click.Context.to_info_dict` to traverse the entire
17 unmodified lines
2135 def __repr__(self) -> str:2136 return f"<{self.__class__.__name__} {self.name}>"21372138 def _parse_decls(2142 self, decls: t.Sequence[str], expose_value: bool2143 ) -> t.Tuple[t.Optional[str], t.List[str], t.List[str]]:2139 self, decls: cabc.Sequence[str], expose_value: bool2140 ) -> tuple[str | None, list[str], list[str]]:2141 raise NotImplementedError()21422143 @property2144 def human_readable_name(self) -> str:
16 unmodified lines
21612162 return metavar21632164 @t.overload2168 def get_default(2169 self, ctx: Context, call: "te.Literal[True]" = True2170 ) -> t.Optional[t.Any]:2165 def get_default(self, ctx: Context, call: t.Literal[True] = True) -> t.Any | None:2166 ...21672168 @t.overload2169 def get_default(2170 self, ctx: Context, call: bool = ...2176 ) -> t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]]:2171 ) -> t.Any | t.Callable[[], t.Any] | None:2172 ...21732174 def get_default(2175 self, ctx: Context, call: bool = True2181 ) -> t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]]:2176 ) -> t.Any | t.Callable[[], t.Any] | None:2177 """Get the default for the parameter. Tries2178 :meth:`Context.lookup_default` first, then the local default.21792180 :param ctx: Current context.
26 unmodified lines
2207 def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None:2208 raise NotImplementedError()22092210 def consume_value(2216 self, ctx: Context, opts: t.Mapping[str, t.Any]2217 ) -> t.Tuple[t.Any, ParameterSource]:2211 self, ctx: Context, opts: cabc.Mapping[str, t.Any]2212 ) -> tuple[t.Any, ParameterSource]:2213 value = opts.get(self.name) # type: ignore2214 source = ParameterSource.COMMANDLINE22152216 if value is None:
16 unmodified lines
2233 """2234 if value is None:2235 return () if self.multiple or self.nargs == -1 else None22362242 def check_iter(value: t.Any) -> t.Iterator[t.Any]:2237 def check_iter(value: t.Any) -> cabc.Iterator[t.Any]:2238 try:2239 return _check_iter(value)2240 except TypeError:2241 # This should only happen when passing in args manually,
9 unmodified lines
2251 return self.type(value, param=self, ctx=ctx)22522253 elif self.nargs == -1:22542260 def convert(value: t.Any) -> t.Any: # t.Tuple[t.Any, ...]2255 def convert(value: t.Any) -> t.Any: # tuple[t.Any, ...]2256 return tuple(self.type(x, self, ctx) for x in check_iter(value))22572258 else: # nargs > 122592265 def convert(value: t.Any) -> t.Any: # t.Tuple[t.Any, ...]2260 def convert(value: t.Any) -> t.Any: # tuple[t.Any, ...]2261 value = tuple(check_iter(value))22622263 if len(value) != self.nargs:2264 raise BadParameter(
32 unmodified lines
2297 value = self.callback(ctx, self, value)22982299 return value23002306 def resolve_envvar_value(self, ctx: Context) -> t.Optional[str]:2301 def resolve_envvar_value(self, ctx: Context) -> str | None:2302 if self.envvar is None:2303 return None23042305 if isinstance(self.envvar, str):
9 unmodified lines
2315 return rv23162317 return None23182324 def value_from_envvar(self, ctx: Context) -> t.Optional[t.Any]:2325 rv: t.Optional[t.Any] = self.resolve_envvar_value(ctx)2319 def value_from_envvar(self, ctx: Context) -> t.Any | None:2320 rv: t.Any | None = self.resolve_envvar_value(ctx)23212322 if rv is not None and self.nargs != 1:2323 rv = self.type.split_envvar_value(rv)23242325 return rv23262327 def handle_parse_result(2333 self, ctx: Context, opts: t.Mapping[str, t.Any], args: t.List[str]2334 ) -> t.Tuple[t.Any, t.List[str]]:2328 self, ctx: Context, opts: cabc.Mapping[str, t.Any], args: list[str]2329 ) -> tuple[t.Any, list[str]]:2330 with augment_usage_errors(ctx, param=self):2331 value, source = self.consume_value(ctx, opts)2332 ctx.set_parameter_source(self.name, source) # type: ignore2333
9 unmodified lines
2343 ctx.params[self.name] = value # type: ignore23442345 return value, args23462352 def get_help_record(self, ctx: Context) -> t.Optional[t.Tuple[str, str]]:2347 def get_help_record(self, ctx: Context) -> tuple[str, str] | None:2348 pass23492355 def get_usage_pieces(self, ctx: Context) -> t.List[str]:2350 def get_usage_pieces(self, ctx: Context) -> list[str]:2351 return []23522353 def get_error_hint(self, ctx: Context) -> str:2354 """Get a stringified version of the param for use in error messages to
1 unmodified line
2356 """2357 hint_list = self.opts or [self.human_readable_name]2358 return " / ".join(f"'{x}'" for x in hint_list)23592365 def shell_complete(self, ctx: Context, incomplete: str) -> t.List["CompletionItem"]:2360 def shell_complete(self, ctx: Context, incomplete: str) -> list[CompletionItem]:2361 """Return a list of completions for the incomplete value. If a2362 ``shell_complete`` function was given during init, it is used.2363 Otherwise, the :attr:`type`2364 :meth:`~click.types.ParamType.shell_complete` function is used.
10 unmodified lines
2375 from click.shell_completion import CompletionItem23762377 results = [CompletionItem(c) for c in results]23782384 return t.cast(t.List["CompletionItem"], results)2379 return t.cast("list[CompletionItem]", results)23802381 return self.type.shell_complete(ctx, self, incomplete)23822383
61 unmodified lines
2445 param_type_name = "option"24462447 def __init__(2448 self,2454 param_decls: t.Optional[t.Sequence[str]] = None,2455 show_default: t.Union[bool, str, None] = None,2456 prompt: t.Union[bool, str] = False,2457 confirmation_prompt: t.Union[bool, str] = False,2449 param_decls: cabc.Sequence[str] | None = None,2450 show_default: bool | str | None = None,2451 prompt: bool | str = False,2452 confirmation_prompt: bool | str = False,2453 prompt_required: bool = True,2454 hide_input: bool = False,2460 is_flag: t.Optional[bool] = None,2461 flag_value: t.Optional[t.Any] = None,2455 is_flag: bool | None = None,2456 flag_value: t.Any | None = None,2457 multiple: bool = False,2458 count: bool = False,2459 allow_from_autoenv: bool = True,2465 type: t.Optional[t.Union[types.ParamType, t.Any]] = None,2466 help: t.Optional[str] = None,2460 type: types.ParamType | t.Any | None = None,2461 help: str | None = None,2462 hidden: bool = False,2463 show_choices: bool = True,2464 show_envvar: bool = False,2465 **attrs: t.Any,
7 unmodified lines
2473 if prompt is True:2474 if self.name is None:2475 raise TypeError("'name' is required with 'prompt=True'.")24762482 prompt_text: t.Optional[str] = self.name.replace("_", " ").capitalize()2477 prompt_text: str | None = self.name.replace("_", " ").capitalize()2478 elif prompt is False:2479 prompt_text = None2480 else:2481 prompt_text = prompt
22 unmodified lines
2504 # Not a flag, and prompt is not enabled, can be used as a2505 # flag if flag_value is set.2506 self._flag_needs_value = flag_value is not None25072513 self.default: t.Union[t.Any, t.Callable[[], t.Any]]2508 self.default: t.Any | t.Callable[[], t.Any]25092510 if is_flag and default_is_missing and not self.required:2511 if multiple:2512 self.default = ()
48 unmodified lines
25612562 if self.is_flag:2563 raise TypeError("'count' is not valid with 'is_flag'.")25642570 def to_info_dict(self) -> t.Dict[str, t.Any]:2565 def to_info_dict(self) -> dict[str, t.Any]:2566 info_dict = super().to_info_dict()2567 info_dict.update(2568 help=self.help,2569 prompt=self.prompt,
4 unmodified lines
2574 )2575 return info_dict25762577 def _parse_decls(2583 self, decls: t.Sequence[str], expose_value: bool2584 ) -> t.Tuple[t.Optional[str], t.List[str], t.List[str]]:2578 self, decls: cabc.Sequence[str], expose_value: bool2579 ) -> tuple[str | None, list[str], list[str]]:2580 opts = []2581 secondary_opts = []2582 name = None2583 possible_names = []
81 unmodified lines
2665 action=action,2666 nargs=self.nargs,2667 )26682674 def get_help_record(self, ctx: Context) -> t.Optional[t.Tuple[str, str]]:2669 def get_help_record(self, ctx: Context) -> tuple[str, str] | None:2670 if self.hidden:2671 return None26722673 any_prefix_is_slash = False26742680 def _write_opts(opts: t.Sequence[str]) -> str:2675 def _write_opts(opts: cabc.Sequence[str]) -> str:2676 nonlocal any_prefix_is_slash26772678 rv, any_slashes = join_options(opts)2679
94 unmodified lines
27742775 return ("; " if any_prefix_is_slash else " / ").join(rv), help27762777 @t.overload2783 def get_default(2784 self, ctx: Context, call: "te.Literal[True]" = True2785 ) -> t.Optional[t.Any]:2778 def get_default(self, ctx: Context, call: t.Literal[True] = True) -> t.Any | None:2779 ...27802781 @t.overload2782 def get_default(2783 self, ctx: Context, call: bool = ...2791 ) -> t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]]:2784 ) -> t.Any | t.Callable[[], t.Any] | None:2785 ...27862787 def get_default(2788 self, ctx: Context, call: bool = True2796 ) -> t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]]:2789 ) -> t.Any | t.Callable[[], t.Any] | None:2790 # If we're a non boolean flag our default is more complex because2791 # we need to look at all flags in the same group to figure out2792 # if we're the default one in which case we return the flag2793 # value as default.
31 unmodified lines
2825 confirmation_prompt=self.confirmation_prompt,2826 value_proc=lambda x: self.process_value(ctx, x),2827 )28282836 def resolve_envvar_value(self, ctx: Context) -> t.Optional[str]:2829 def resolve_envvar_value(self, ctx: Context) -> str | None:2830 rv = super().resolve_envvar_value(ctx)28312832 if rv is not None:2833 return rv
10 unmodified lines
2844 return rv28452846 return None28472855 def value_from_envvar(self, ctx: Context) -> t.Optional[t.Any]:2856 rv: t.Optional[t.Any] = self.resolve_envvar_value(ctx)2848 def value_from_envvar(self, ctx: Context) -> t.Any | None:2849 rv: t.Any | None = self.resolve_envvar_value(ctx)28502851 if rv is None:2852 return None2853
7 unmodified lines
28612862 return rv28632864 def consume_value(2872 self, ctx: Context, opts: t.Mapping[str, "Parameter"]2873 ) -> t.Tuple[t.Any, ParameterSource]:2865 self, ctx: Context, opts: cabc.Mapping[str, Parameter]2866 ) -> tuple[t.Any, ParameterSource]:2867 value, source = super().consume_value(ctx, opts)28682869 # The parser will emit a sentinel value if the option can be2870 # given as a flag without a value. This is different from None
39 unmodified lines
2910 param_type_name = "argument"29112912 def __init__(2913 self,2921 param_decls: t.Sequence[str],2922 required: t.Optional[bool] = None,2914 param_decls: cabc.Sequence[str],2915 required: bool | None = None,2916 **attrs: t.Any,2917 ) -> None:2918 if required is None:2919 if attrs.get("default") is not None:
28 unmodified lines
2948 var += "..."2949 return var29502951 def _parse_decls(2959 self, decls: t.Sequence[str], expose_value: bool2960 ) -> t.Tuple[t.Optional[str], t.List[str], t.List[str]]:2952 self, decls: cabc.Sequence[str], expose_value: bool2953 ) -> tuple[str | None, list[str], list[str]]:2954 if not decls:2955 if not expose_value:2956 return None, [], []2957 raise TypeError("Could not determine name for argument")
6 unmodified lines
2964 f" {len(decls)}."2965 )2966 return name, [arg], []29672975 def get_usage_pieces(self, ctx: Context) -> t.List[str]:2968 def get_usage_pieces(self, ctx: Context) -> list[str]:2969 return [self.make_metavar()]29702971 def get_error_hint(self, ctx: Context) -> str:2972 return f"'{self.make_metavar()}'"
27 unmodified lines
modified:src/click/decorators.py+39 added-37 removed
1from __future__ import annotations23import inspect4import typing as t5from functools import update_wrapper6from gettext import gettext as _
14 unmodified lines
2122R = t.TypeVar("R")23T = t.TypeVar("T")24_AnyCallable = t.Callable[..., t.Any]23FC = t.TypeVar("FC", bound=t.Union[_AnyCallable, Command])25FC = t.TypeVar("FC", bound="_AnyCallable | Command")262726def pass_context(f: "t.Callable[te.Concatenate[Context, P], R]") -> "t.Callable[P, R]":28def pass_context(f: t.Callable[te.Concatenate[Context, P], R]) -> t.Callable[P, R]:29 """Marks a callback as wanting to receive the current context30 object as first argument.31 """3231 def new_func(*args: "P.args", **kwargs: "P.kwargs") -> "R":33 def new_func(*args: P.args, **kwargs: P.kwargs) -> R:34 return f(get_current_context(), *args, **kwargs)3536 return update_wrapper(new_func, f)373837def pass_obj(f: "t.Callable[te.Concatenate[t.Any, P], R]") -> "t.Callable[P, R]":39def pass_obj(f: t.Callable[te.Concatenate[T, P], R]) -> t.Callable[P, R]:40 """Similar to :func:`pass_context`, but only pass the object on the41 context onwards (:attr:`Context.obj`). This is useful if that object42 represents the state of a nested system.43 """4443 def new_func(*args: "P.args", **kwargs: "P.kwargs") -> "R":45 def new_func(*args: P.args, **kwargs: P.kwargs) -> R:46 return f(get_current_context().obj, *args, **kwargs)4748 return update_wrapper(new_func, f)495051def make_pass_decorator(50 object_type: t.Type[T], ensure: bool = False51) -> t.Callable[["t.Callable[te.Concatenate[T, P], R]"], "t.Callable[P, R]"]:52 object_type: type[T], ensure: bool = False53) -> t.Callable[[t.Callable[te.Concatenate[T, P], R]], t.Callable[P, R]]:54 """Given an object type this creates a decorator that will work55 similar to :func:`pass_obj` but instead of passing the object of the56 current context, it will find the innermost context of type57 :func:`object_type`.
14 unmodified lines
72 :param ensure: if set to `True`, a new object will be created and73 remembered on the context if it's not there yet.74 """7574 def decorator(f: "t.Callable[te.Concatenate[T, P], R]") -> "t.Callable[P, R]":75 def new_func(*args: "P.args", **kwargs: "P.kwargs") -> "R":76 def decorator(f: t.Callable[te.Concatenate[T, P], R]) -> t.Callable[P, R]:77 def new_func(*args: P.args, **kwargs: P.kwargs) -> R:78 ctx = get_current_context()7978 obj: t.Optional[T]80 obj: T | None81 if ensure:82 obj = ctx.ensure_object(object_type)83 else:84 obj = ctx.find_object(object_type)
12 unmodified lines
97 return decorator # type: ignore[return-value]9899100def pass_meta_key(99 key: str, *, doc_description: t.Optional[str] = None100) -> "t.Callable[[t.Callable[te.Concatenate[t.Any, P], R]], t.Callable[P, R]]":101 key: str, *, doc_description: str | None = None102) -> t.Callable[[t.Callable[te.Concatenate[T, P], R]], t.Callable[P, R]]:103 """Create a decorator that passes a key from104 :attr:`click.Context.meta` as the first argument to the decorated105 function.106
4 unmodified lines
111112 .. versionadded:: 8.0113 """114113 def decorator(f: "t.Callable[te.Concatenate[t.Any, P], R]") -> "t.Callable[P, R]":114 def new_func(*args: "P.args", **kwargs: "P.kwargs") -> R:115 def decorator(f: t.Callable[te.Concatenate[T, P], R]) -> t.Callable[P, R]:116 def new_func(*args: P.args, **kwargs: P.kwargs) -> R:117 ctx = get_current_context()118 obj = ctx.meta[key]119 return ctx.invoke(f, obj, *args, **kwargs)120
21 unmodified lines
142# variant: with positional name and with positional or keyword cls argument:143# @command(namearg, CommandCls, ...) or @command(namearg, cls=CommandCls, ...)144@t.overload145def command(144 name: t.Optional[str],145 cls: t.Type[CmdType],146 name: str | None,147 cls: type[CmdType],148 **attrs: t.Any,149) -> t.Callable[[_AnyCallable], CmdType]:150 ...151
2 unmodified lines
154@t.overload155def command(156 name: None = None,157 *,156 cls: t.Type[CmdType],158 cls: type[CmdType],159 **attrs: t.Any,160) -> t.Callable[[_AnyCallable], CmdType]:161 ...162163164# variant: with optional string name, no cls argument provided.165@t.overload166def command(165 name: t.Optional[str] = ..., cls: None = None, **attrs: t.Any167 name: str | None = ..., cls: None = None, **attrs: t.Any168) -> t.Callable[[_AnyCallable], Command]:169 ...170171172def command(171 name: t.Union[t.Optional[str], _AnyCallable] = None,172 cls: t.Optional[t.Type[CmdType]] = None,173 name: str | _AnyCallable | None = None,174 cls: type[CmdType] | None = None,175 **attrs: t.Any,174) -> t.Union[Command, t.Callable[[_AnyCallable], t.Union[Command, CmdType]]]:176) -> Command | t.Callable[[_AnyCallable], Command | CmdType]:177 r"""Creates a new :class:`Command` and uses the decorated function as178 callback. This will also automatically attach all decorated179 :func:`option`\s and :func:`argument`\s as parameters to the command.180
21 unmodified lines
202 The ``params`` argument can be used. Decorated params are203 appended to the end of the list.204 """205204 func: t.Optional[t.Callable[[_AnyCallable], t.Any]] = None206 func: t.Callable[[_AnyCallable], t.Any] | None = None207208 if callable(name):209 func = name210 name = None211 assert cls is None, "Use 'command(cls=cls)(callable)' to specify a class."212 assert not attrs, "Use 'command(**kwargs)(callable)' to provide arguments."213214 if cls is None:213 cls = t.cast(t.Type[CmdType], Command)215 cls = t.cast("type[CmdType]", Command)216217 def decorator(f: _AnyCallable) -> CmdType:218 if isinstance(f, Command):219 raise TypeError("Attempted to convert a callback into a command twice.")
43 unmodified lines
263# variant: with positional name and with positional or keyword cls argument:264# @group(namearg, GroupCls, ...) or @group(namearg, cls=GroupCls, ...)265@t.overload266def group(265 name: t.Optional[str],266 cls: t.Type[GrpType],267 name: str | None,268 cls: type[GrpType],269 **attrs: t.Any,270) -> t.Callable[[_AnyCallable], GrpType]:271 ...272
2 unmodified lines
275@t.overload276def group(277 name: None = None,278 *,277 cls: t.Type[GrpType],279 cls: type[GrpType],280 **attrs: t.Any,281) -> t.Callable[[_AnyCallable], GrpType]:282 ...283284285# variant: with optional string name, no cls argument provided.286@t.overload287def group(286 name: t.Optional[str] = ..., cls: None = None, **attrs: t.Any288 name: str | None = ..., cls: None = None, **attrs: t.Any289) -> t.Callable[[_AnyCallable], Group]:290 ...291292293def group(292 name: t.Union[str, _AnyCallable, None] = None,293 cls: t.Optional[t.Type[GrpType]] = None,294 name: str | _AnyCallable | None = None,295 cls: type[GrpType] | None = None,296 **attrs: t.Any,295) -> t.Union[Group, t.Callable[[_AnyCallable], t.Union[Group, GrpType]]]:297) -> Group | t.Callable[[_AnyCallable], Group | GrpType]:298 """Creates a new :class:`Group` with a function as callback. This299 works otherwise the same as :func:`command` just that the `cls`300 parameter is set to :class:`Group`.301302 .. versionchanged:: 8.1303 This decorator can be applied without parentheses.304 """305 if cls is None:304 cls = t.cast(t.Type[GrpType], Group)306 cls = t.cast("type[GrpType]", Group)307308 if callable(name):309 return command(cls=cls, **attrs)(name)310
10 unmodified lines
321 f.__click_params__.append(param) # type: ignore322323324def argument(323 *param_decls: str, cls: t.Optional[t.Type[Argument]] = None, **attrs: t.Any325 *param_decls: str, cls: type[Argument] | None = None, **attrs: t.Any326) -> t.Callable[[FC], FC]:327 """Attaches an argument to the command. All positional arguments are328 passed as parameter declarations to :class:`Argument`; all keyword329 arguments are forwarded unchanged (except ``cls``).
19 unmodified lines
349 return decorator350351352def option(351 *param_decls: str, cls: t.Optional[t.Type[Option]] = None, **attrs: t.Any353 *param_decls: str, cls: type[Option] | None = None, **attrs: t.Any354) -> t.Callable[[FC], FC]:355 """Attaches an option to the command. All positional arguments are356 passed as parameter declarations to :class:`Option`; all keyword357 arguments are forwarded unchanged (except ``cls``).
60 unmodified lines
418 return option(*param_decls, **kwargs)419420421def version_option(420 version: t.Optional[str] = None,422 version: str | None = None,423 *param_decls: str,422 package_name: t.Optional[str] = None,423 prog_name: t.Optional[str] = None,424 message: t.Optional[str] = None,424 package_name: str | None = None,425 prog_name: str | None = None,426 message: str | None = None,427 **kwargs: t.Any,428) -> t.Callable[[FC], FC]:429 """Add a ``--version`` option which immediately prints the version430 number and exits the program.
125 unmodified lines
modified:src/click/exceptions.py+22 added-21 removed
1from __future__ import annotations23import collections.abc as cabc4import typing as t5from gettext import gettext as _6from gettext import ngettext7
6 unmodified lines
14 from .core import Context15 from .core import Parameter161715def _join_param_hints(16 param_hint: t.Optional[t.Union[t.Sequence[str], str]]17) -> t.Optional[str]:18def _join_param_hints(param_hint: cabc.Sequence[str] | str | None) -> str | None:19 if param_hint is not None and not isinstance(param_hint, str):20 return " / ".join(repr(x) for x in param_hint)2122 return param_hint
14 unmodified lines
3738 def __str__(self) -> str:39 return self.message4040 def show(self, file: t.Optional[t.IO[t.Any]] = None) -> None:41 def show(self, file: t.IO[t.Any] | None = None) -> None:42 if file is None:43 file = get_text_stderr()4445 echo(_("Error: {message}").format(message=self.format_message()), file=file)
9 unmodified lines
55 """5657 exit_code = 25858 def __init__(self, message: str, ctx: t.Optional["Context"] = None) -> None:59 def __init__(self, message: str, ctx: Context | None = None) -> None:60 super().__init__(message)61 self.ctx = ctx61 self.cmd: t.Optional["Command"] = self.ctx.command if self.ctx else None62 self.cmd: Command | None = self.ctx.command if self.ctx else None6363 def show(self, file: t.Optional[t.IO[t.Any]] = None) -> None:64 def show(self, file: t.IO[t.Any] | None = None) -> None:65 if file is None:66 file = get_text_stderr()67 color = None68 hint = ""
35 unmodified lines
104105 def __init__(106 self,107 message: str,107 ctx: t.Optional["Context"] = None,108 param: t.Optional["Parameter"] = None,109 param_hint: t.Optional[str] = None,108 ctx: Context | None = None,109 param: Parameter | None = None,110 param_hint: str | None = None,111 ) -> None:112 super().__init__(message, ctx)113 self.param = param114 self.param_hint = param_hint
24 unmodified lines
139 """140141 def __init__(142 self,142 message: t.Optional[str] = None,143 ctx: t.Optional["Context"] = None,144 param: t.Optional["Parameter"] = None,145 param_hint: t.Optional[str] = None,146 param_type: t.Optional[str] = None,143 message: str | None = None,144 ctx: Context | None = None,145 param: Parameter | None = None,146 param_hint: str | None = None,147 param_type: str | None = None,148 ) -> None:149 super().__init__(message or "", ctx, param, param_hint)150 self.param_type = param_type151152 def format_message(self) -> str:153 if self.param_hint is not None:153 param_hint: t.Optional[str] = self.param_hint154 param_hint: str | None = self.param_hint155 elif self.param is not None:156 param_hint = self.param.get_error_hint(self.ctx) # type: ignore157 else:158 param_hint = None
45 unmodified lines
204205 def __init__(206 self,207 option_name: str,207 message: t.Optional[str] = None,208 possibilities: t.Optional[t.Sequence[str]] = None,209 ctx: t.Optional["Context"] = None,208 message: str | None = None,209 possibilities: cabc.Sequence[str] | None = None,210 ctx: Context | None = None,211 ) -> None:212 if message is None:213 message = _("No such option: {name}").format(name=option_name)214
24 unmodified lines
239 :param option_name: the name of the option being used incorrectly.240 """241242 def __init__(242 self, option_name: str, message: str, ctx: t.Optional["Context"] = None243 self, option_name: str, message: str, ctx: Context | None = None244 ) -> None:245 super().__init__(message, ctx)246 self.option_name = option_name247
9 unmodified lines
257258class FileError(ClickException):259 """Raised if a file cannot be opened."""260260 def __init__(self, filename: str, hint: t.Optional[str] = None) -> None:261 def __init__(self, filename: str, hint: str | None = None) -> None:262 if hint is None:263 hint = _("unknown error")264265 super().__init__(hint)
24 unmodified lines
modified:src/click/formatting.py+18 added-18 removed
1import typing as t1from __future__ import annotations23import collections.abc as cabc4from contextlib import contextmanager5from gettext import gettext as _67from ._compat import term_len8from .parser import _split_opt910# Can force a width. This is used by the test system9FORCED_WIDTH: t.Optional[int] = None11FORCED_WIDTH: int | None = None121312def measure_table(rows: t.Iterable[t.Tuple[str, str]]) -> t.Tuple[int, ...]:13 widths: t.Dict[int, int] = {}14def measure_table(rows: cabc.Iterable[tuple[str, str]]) -> tuple[int, ...]:15 widths: dict[int, int] = {}1617 for row in rows:18 for idx, col in enumerate(row):19 widths[idx] = max(widths.get(idx, 0), term_len(col))
1 unmodified line
21 return tuple(y for x, y in sorted(widths.items()))222324def iter_rows(23 rows: t.Iterable[t.Tuple[str, str]], col_count: int24) -> t.Iterator[t.Tuple[str, ...]]:25 rows: cabc.Iterable[tuple[str, str]], col_count: int26) -> cabc.Iterator[tuple[str, ...]]:27 for row in rows:28 yield row + ("",) * (col_count - len(row))2930
33 unmodified lines
64 )65 if not preserve_paragraphs:66 return wrapper.fill(text)6766 p: t.List[t.Tuple[int, bool, str]] = []67 buf: t.List[str] = []68 p: list[tuple[int, bool, str]] = []69 buf: list[str] = []70 indent = None7172 def _flush_par() -> None:73 if not buf:
41 unmodified lines
115116 def __init__(117 self,118 indent_increment: int = 2,117 width: t.Optional[int] = None,118 max_width: t.Optional[int] = None,119 width: int | None = None,120 max_width: int | None = None,121 ) -> None:122 import shutil123124 self.indent_increment = indent_increment
4 unmodified lines
129 if width is None:130 width = max(min(shutil.get_terminal_size().columns, max_width) - 2, 50)131 self.width = width132 self.current_indent = 0131 self.buffer: t.List[str] = []133 self.buffer: list[str] = []134135 def write(self, string: str) -> None:136 """Writes a unicode string into the internal buffer."""137 self.buffer.append(string)
5 unmodified lines
143 def dedent(self) -> None:144 """Decreases the indentation."""145 self.current_indent -= self.indent_increment146145 def write_usage(146 self, prog: str, args: str = "", prefix: t.Optional[str] = None147 ) -> None:147 def write_usage(self, prog: str, args: str = "", prefix: str | None = None) -> None:148 """Writes a usage line into the buffer.149150 :param prog: the program name.151 :param args: whitespace separated list of arguments.
56 unmodified lines
208 self.write("\n")209210 def write_dl(211 self,212 rows: t.Sequence[t.Tuple[str, str]],212 rows: cabc.Sequence[tuple[str, str]],213 col_max: int = 30,214 col_spacing: int = 2,215 ) -> None:216 """Writes a definition list into the buffer. This is how options
34 unmodified lines
251 else:252 self.write("\n")253254 @contextmanager255 def section(self, name: str) -> t.Iterator[None]:255 def section(self, name: str) -> cabc.Iterator[None]:256 """Helpful context manager that writes a paragraph, a heading,257 and the indents.258259 :param name: the section name that is written as heading.
6 unmodified lines
266 finally:267 self.dedent()268269 @contextmanager270 def indentation(self) -> t.Iterator[None]:270 def indentation(self) -> cabc.Iterator[None]:271 """A context manager that increases the indentation."""272 self.indent()273 try:274 yield
4 unmodified lines
279 """Returns the buffer contents."""280 return "".join(self.buffer)281282283def join_options(options: t.Sequence[str]) -> t.Tuple[str, bool]:283def join_options(options: cabc.Sequence[str]) -> tuple[str, bool]:284 """Given a list of option strings this joins them in the most appropriate285 way and returns them in the form ``(formatted_string,286 any_prefix_is_slash)`` where the second item in the tuple is a flag that287 indicates if any of the option prefixes was a slash.
14 unmodified lines
modified:src/click/globals.py+7 added-6 removed
1from __future__ import annotations23import typing as t4from threading import local56if t.TYPE_CHECKING:5 import typing_extensions as te7 from .core import Context89_local = local()101112@t.overload12def get_current_context(silent: "te.Literal[False]" = False) -> "Context":13def get_current_context(silent: t.Literal[False] = False) -> Context:14 ...151617@t.overload17def get_current_context(silent: bool = ...) -> t.Optional["Context"]:18def get_current_context(silent: bool = ...) -> Context | None:19 ...202121def get_current_context(silent: bool = False) -> t.Optional["Context"]:22def get_current_context(silent: bool = False) -> Context | None:23 """Returns the current click context. This can be used as a way to24 access the current context object from anywhere. This is a more implicit25 alternative to the :func:`pass_context` decorator. This function is26 primarily useful for helpers such as :func:`echo` which might be
15 unmodified lines
4243 return None444545def push_context(ctx: "Context") -> None:46def push_context(ctx: Context) -> None:47 """Pushes a new context to the current stack."""48 _local.__dict__.setdefault("stack", []).append(ctx)4950
1 unmodified line
52 """Removes the top level from the stack."""53 _local.stack.pop()545555def resolve_color_default(color: t.Optional[bool] = None) -> t.Optional[bool]:56def resolve_color_default(color: bool | None = None) -> bool | None:57 """Internal helper to get the default value of the color flag. If a58 value is passed it's returned unchanged, otherwise it's looked up from59 the current context.60 """
9 unmodified lines
modified:src/click/parser.py+37 added-37 removed
19 unmodified lines
20# This code uses parts of optparse written by Gregory P. Ward and21# maintained by the Python Software Foundation.22# Copyright 2001-2006 Gregory P. Ward23# Copyright 2002-2006 Python Software Foundation24from __future__ import annotations2526import collections.abc as cabc27import typing as t28from collections import deque29from gettext import gettext as _30from gettext import ngettext
3 unmodified lines
34from .exceptions import NoSuchOption35from .exceptions import UsageError3637if t.TYPE_CHECKING:35 import typing_extensions as te38 from .core import Argument as CoreArgument39 from .core import Context40 from .core import Option as CoreOption41 from .core import Parameter as CoreParameter
6 unmodified lines
48_flag_needs_value = object()495051def _unpack_args(50 args: t.Sequence[str], nargs_spec: t.Sequence[int]51) -> t.Tuple[t.Sequence[t.Union[str, t.Sequence[t.Optional[str]], None]], t.List[str]]:52 args: cabc.Sequence[str], nargs_spec: cabc.Sequence[int]53) -> tuple[cabc.Sequence[str | cabc.Sequence[str | None] | None], 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
3 unmodified lines
61 Missing items are filled with `None`.62 """63 args = deque(args)64 nargs_spec = deque(nargs_spec)63 rv: t.List[t.Union[str, t.Tuple[t.Optional[str], ...], None]] = []64 spos: t.Optional[int] = None65 rv: list[str | tuple[str | None, ...] | None] = []66 spos: int | None = None6766 def _fetch(c: "te.Deque[V]") -> t.Optional[V]:68 def _fetch(c: deque[V]) -> V | None:69 try:70 if spos is None:71 return c.popleft()72 else:
34 unmodified lines
107108 return tuple(rv), list(args)109110109def _split_opt(opt: str) -> t.Tuple[str, str]:111def _split_opt(opt: str) -> tuple[str, str]:112 first = opt[:1]113 if first.isalnum():114 return "", opt115 if opt[1:2] == first:116 return opt[:2], opt[2:]117 return first, opt[1:]118119118def _normalize_opt(opt: str, ctx: t.Optional["Context"]) -> str:120def _normalize_opt(opt: str, ctx: Context | None) -> str:121 if ctx is None or ctx.token_normalize_func is None:122 return opt123 prefix, opt = _split_opt(opt)124 return f"{prefix}{ctx.token_normalize_func(opt)}"
1 unmodified line
126127class _Option:128 def __init__(129 self,128 obj: "CoreOption",129 opts: t.Sequence[str],130 dest: t.Optional[str],131 action: t.Optional[str] = None,130 obj: CoreOption,131 opts: cabc.Sequence[str],132 dest: str | None,133 action: str | None = None,134 nargs: int = 1,133 const: t.Optional[t.Any] = None,135 const: t.Any | None = None,136 ):137 self._short_opts = []138 self._long_opts = []137 self.prefixes: t.Set[str] = set()139 self.prefixes: set[str] = set()140141 for opt in opts:142 prefix, value = _split_opt(opt)143 if not prefix:
17 unmodified lines
161 @property162 def takes_value(self) -> bool:163 return self.action in ("store", "append")164163 def process(self, value: t.Any, state: "_ParsingState") -> None:165 def process(self, value: t.Any, state: _ParsingState) -> None:166 if self.action == "store":167 state.opts[self.dest] = value # type: ignore168 elif self.action == "store_const":169 state.opts[self.dest] = self.const # type: ignore
8 unmodified lines
178 state.order.append(self.obj)179180181class _Argument:180 def __init__(self, obj: "CoreArgument", dest: t.Optional[str], nargs: int = 1):182 def __init__(self, obj: CoreArgument, dest: str | None, nargs: int = 1):183 self.dest = dest184 self.nargs = nargs185 self.obj = obj186187 def process(188 self,187 value: t.Union[t.Optional[str], t.Sequence[t.Optional[str]]],188 state: "_ParsingState",189 value: str | cabc.Sequence[str | None] | None,190 state: _ParsingState,191 ) -> None:192 if self.nargs > 1:193 assert value is not None194 holes = sum(1 for x in value if x is None)
15 unmodified lines
210 state.order.append(self.obj)211212213class _ParsingState:212 def __init__(self, rargs: t.List[str]) -> None:213 self.opts: t.Dict[str, t.Any] = {}214 self.largs: t.List[str] = []214 def __init__(self, rargs: list[str]) -> None:215 self.opts: dict[str, t.Any] = {}216 self.largs: list[str] = []217 self.rargs = rargs216 self.order: t.List["CoreParameter"] = []218 self.order: list[CoreParameter] = []219220221class _OptionParser:222 """The option parser is an internal class that is ultimately used to
11 unmodified lines
234 .. deprecated:: 8.2235 Will be removed in Click 9.0.236 """237236 def __init__(self, ctx: t.Optional["Context"] = None) -> None:238 def __init__(self, ctx: Context | None = None) -> None:239 #: The :class:`~click.Context` for this parser. This might be240 #: `None` for some advanced use cases.241 self.ctx = ctx242 #: This controls how the parser deals with interspersed arguments.
10 unmodified lines
253 if ctx is not None:254 self.allow_interspersed_args = ctx.allow_interspersed_args255 self.ignore_unknown_options = ctx.ignore_unknown_options256255 self._short_opt: t.Dict[str, _Option] = {}256 self._long_opt: t.Dict[str, _Option] = {}257 self._short_opt: dict[str, _Option] = {}258 self._long_opt: dict[str, _Option] = {}259 self._opt_prefixes = {"-", "--"}258 self._args: t.List[_Argument] = []260 self._args: list[_Argument] = []261262 def add_option(263 self,262 obj: "CoreOption",263 opts: t.Sequence[str],264 dest: t.Optional[str],265 action: t.Optional[str] = None,264 obj: CoreOption,265 opts: cabc.Sequence[str],266 dest: str | None,267 action: str | None = None,268 nargs: int = 1,267 const: t.Optional[t.Any] = None,269 const: t.Any | None = None,270 ) -> None:271 """Adds a new option named `dest` to the parser. The destination272 is not inferred (unlike with optparse) and needs to be explicitly273 provided. Action can be any of ``store``, ``store_const``,
9 unmodified lines
283 self._short_opt[opt] = option284 for opt in option._long_opts:285 self._long_opt[opt] = option286285 def add_argument(286 self, obj: "CoreArgument", dest: t.Optional[str], nargs: int = 1287 ) -> None:287 def add_argument(self, obj: CoreArgument, dest: str | None, nargs: int = 1) -> None:288 """Adds a positional argument named `dest` to the parser.289290 The `obj` can be used to identify the option in the order list291 that is returned from the parser.292 """293 self._args.append(_Argument(obj, dest=dest, nargs=nargs))294295 def parse_args(296 self, args: t.List[str]297 ) -> t.Tuple[t.Dict[str, t.Any], t.List[str], t.List["CoreParameter"]]:296 self, args: list[str]297 ) -> tuple[dict[str, t.Any], list[str], list[CoreParameter]]:298 """Parses positional arguments and returns ``(values, args, order)``299 for the parsed options and arguments as well as the leftover300 arguments if there are any. The order is a list of objects as they301 appear on the command line. If arguments appear multiple times they
55 unmodified lines
357 # *empty* -- still a subset of [arg0, ..., arg(i-1)], but358 # not a very interesting subset!359360 def _match_long_opt(361 self, opt: str, explicit_value: t.Optional[str], state: _ParsingState361 self, opt: str, explicit_value: str | None, state: _ParsingState362 ) -> None:363 if opt not in self._long_opt:364 from difflib import get_close_matches365
164 unmodified lines
modified:src/click/shell_completion.py+23 added-22 removed
1from __future__ import annotations23import collections.abc as cabc4import os5import re6import typing as t7from gettext import gettext as _
9 unmodified lines
171819def shell_complete(20 cli: Command,18 ctx_args: t.MutableMapping[str, t.Any],21 ctx_args: cabc.MutableMapping[str, t.Any],22 prog_name: str,23 complete_var: str,24 instruction: str,25) -> int:
52 unmodified lines
78 def __init__(79 self,80 value: t.Any,81 type: str = "plain",79 help: t.Optional[str] = None,82 help: str | None = None,83 **kwargs: t.Any,84 ) -> None:85 self.value: t.Any = value86 self.type: str = type84 self.help: t.Optional[str] = help87 self.help: str | None = help88 self._info = kwargs8990 def __getattr__(self, name: str) -> t.Any:91 return self._info.get(name)
125 unmodified lines
217218 def __init__(219 self,220 cli: Command,218 ctx_args: t.MutableMapping[str, t.Any],221 ctx_args: cabc.MutableMapping[str, t.Any],222 prog_name: str,223 complete_var: str,224 ) -> None:225 self.cli = cli
8 unmodified lines
234 """235 safe_name = re.sub(r"\W*", "", self.prog_name.replace("-", "_"), flags=re.ASCII)236 return f"_{safe_name}_completion"237235 def source_vars(self) -> t.Dict[str, t.Any]:238 def source_vars(self) -> dict[str, t.Any]:239 """Vars for formatting :attr:`source_template`.240241 By default this provides ``complete_func``, ``complete_var``,242 and ``prog_name``.
11 unmodified lines
254 :meth:`source_vars`.255 """256 return self.source_template % self.source_vars()257255 def get_completion_args(self) -> t.Tuple[t.List[str], str]:258 def get_completion_args(self) -> tuple[list[str], str]:259 """Use the env vars defined by the shell script to return a260 tuple of ``args, incomplete``. This must be implemented by261 subclasses.262 """263 raise NotImplementedError264262 def get_completions(263 self, args: t.List[str], incomplete: str264 ) -> t.List[CompletionItem]:265 def get_completions(self, args: list[str], incomplete: str) -> list[CompletionItem]:266 """Determine the context and last complete command or parameter267 from the complete args. Call that object's ``shell_complete``268 method to get the completions for the incomplete value.269
60 unmodified lines
330 def source(self) -> str:331 self._check_version()332 return super().source()333333 def get_completion_args(self) -> t.Tuple[t.List[str], str]:334 def get_completion_args(self) -> tuple[list[str], str]:335 cwords = split_arg_string(os.environ["COMP_WORDS"])336 cword = int(os.environ["COMP_CWORD"])337 args = cwords[1:cword]338
13 unmodified lines
352353 name = "zsh"354 source_template = _SOURCE_ZSH355355 def get_completion_args(self) -> t.Tuple[t.List[str], str]:356 def get_completion_args(self) -> tuple[list[str], str]:357 cwords = split_arg_string(os.environ["COMP_WORDS"])358 cword = int(os.environ["COMP_CWORD"])359 args = cwords[1:cword]360
13 unmodified lines
374375 name = "fish"376 source_template = _SOURCE_FISH377377 def get_completion_args(self) -> t.Tuple[t.List[str], str]:378 def get_completion_args(self) -> tuple[list[str], str]:379 cwords = split_arg_string(os.environ["COMP_WORDS"])380 incomplete = os.environ["COMP_CWORD"]381 args = cwords[1:]382
10 unmodified lines
393394 return f"{item.type},{item.value}"395396396ShellCompleteType = t.TypeVar("ShellCompleteType", bound=t.Type[ShellComplete])397ShellCompleteType = t.TypeVar("ShellCompleteType", bound="type[ShellComplete]")398399399_available_shells: t.Dict[str, t.Type[ShellComplete]] = {400_available_shells: dict[str, type[ShellComplete]] = {401 "bash": BashComplete,402 "fish": FishComplete,403 "zsh": ZshComplete,404}405406407def add_completion_class(407 cls: ShellCompleteType, name: t.Optional[str] = None408 cls: ShellCompleteType, name: str | None = None409) -> ShellCompleteType:410 """Register a :class:`ShellComplete` subclass under the given name.411 The name will be provided by the completion instruction environment412 variable during completion.
10 unmodified lines
423424 return cls425426426def get_completion_class(shell: str) -> t.Optional[t.Type[ShellComplete]]:427def get_completion_class(shell: str) -> type[ShellComplete] | None:428 """Look up a registered :class:`ShellComplete` subclass by the name429 provided by the completion instruction environment variable. If the430 name isn't registered, returns ``None``.431
1 unmodified line
433 """434 return _available_shells.get(shell)435436436def split_arg_string(string: str) -> t.List[str]:437def split_arg_string(string: str) -> list[str]:438 """Split an argument string as with :func:`shlex.split`, but don't439 fail if the string is incomplete. Ignores a missing closing quote or440 incomplete escape sequence and uses the partial token as-is.441
62 unmodified lines
504 c = value[0]505 return c in ctx._opt_prefixes506507507def _is_incomplete_option(ctx: Context, args: t.List[str], param: Parameter) -> bool:508def _is_incomplete_option(ctx: Context, args: list[str], param: Parameter) -> bool:509 """Determine if the given parameter is an option that needs a value.510511 :param args: List of complete args before the incomplete value.512 :param param: Option object being checked.
17 unmodified lines
530531532def _resolve_context(533 cli: Command,533 ctx_args: t.MutableMapping[str, t.Any],534 ctx_args: cabc.MutableMapping[str, t.Any],535 prog_name: str,535 args: t.List[str],536 args: list[str],537) -> Context:538 """Produce the context hierarchy starting with the command and539 traversing the complete arguments. This only follows the commands,540 it doesn't trigger input prompts or callbacks.
45 unmodified lines
586 return ctx587588589def _resolve_incomplete(589 ctx: Context, args: t.List[str], incomplete: str590) -> t.Tuple[t.Union[Command, Parameter], str]:590 ctx: Context, args: list[str], incomplete: str591) -> tuple[Command | Parameter, str]:592 """Find the Click object that will handle the completion of the593 incomplete value. Return the object and the incomplete value.594595 :param ctx: Invocation context for the command represented by
38 unmodified lines
modified:src/click/termui.py+45 added-43 removed
1from __future__ import annotations23import collections.abc as cabc4import inspect5import io6import itertools7import sys8import typing as t9from contextlib import AbstractContextManager10from gettext import gettext as _1112from ._compat import isatty13from ._compat import strip_ansi
46 unmodified lines
60def _build_prompt(61 text: str,62 suffix: str,63 show_default: bool = False,60 default: t.Optional[t.Any] = None,64 default: t.Any | None = None,65 show_choices: bool = True,62 type: t.Optional[ParamType] = None,66 type: ParamType | None = None,67) -> str:68 prompt = text69 if type is not None and show_choices and isinstance(type, Choice):70 prompt += f" ({', '.join(map(str, type.choices))})"
10 unmodified lines
818283def prompt(84 text: str,81 default: t.Optional[t.Any] = None,85 default: t.Any | None = None,86 hide_input: bool = False,83 confirmation_prompt: t.Union[bool, str] = False,84 type: t.Optional[t.Union[ParamType, t.Any]] = None,85 value_proc: t.Optional[t.Callable[[str], t.Any]] = None,87 confirmation_prompt: bool | str = False,88 type: ParamType | t.Any | None = None,89 value_proc: t.Callable[[str], t.Any] | None = None,90 prompt_suffix: str = ": ",91 show_default: bool = True,92 err: bool = False,93 show_choices: bool = True,
98 unmodified lines
192193194def confirm(195 text: str,192 default: t.Optional[bool] = False,196 default: bool | None = False,197 abort: bool = False,198 prompt_suffix: str = ": ",199 show_default: bool = True,200 err: bool = False,
51 unmodified lines
252 return rv253254255def echo_via_pager(252 text_or_generator: t.Union[t.Iterable[str], t.Callable[[], t.Iterable[str]], str],253 color: t.Optional[bool] = None,256 text_or_generator: cabc.Iterable[str] | t.Callable[[], cabc.Iterable[str]] | str,257 color: bool | None = None,258) -> None:259 """This function takes a text and shows it via an environment specific260 pager on stdout.261
7 unmodified lines
269 """270 color = resolve_color_default(color)271272 if inspect.isgeneratorfunction(text_or_generator):269 i = t.cast(t.Callable[[], t.Iterable[str]], text_or_generator)()273 i = t.cast("t.Callable[[], cabc.Iterable[str]]", text_or_generator)()274 elif isinstance(text_or_generator, str):275 i = [text_or_generator]276 else:273 i = iter(t.cast(t.Iterable[str], text_or_generator))277 i = iter(t.cast("cabc.Iterable[str]", text_or_generator))278279 # convert every element of i to a text type if necessary280 text_generator = (el if isinstance(el, str) else str(el) for el in i)281
2 unmodified lines
284 return pager(itertools.chain(text_generator, "\n"), color)285286287def progressbar(284 iterable: t.Optional[t.Iterable[V]] = None,285 length: t.Optional[int] = None,286 label: t.Optional[str] = None,288 iterable: cabc.Iterable[V] | None = None,289 length: int | None = None,290 label: str | None = None,291 show_eta: bool = True,288 show_percent: t.Optional[bool] = None,292 show_percent: bool | None = None,293 show_pos: bool = False,290 item_show_func: t.Optional[t.Callable[[t.Optional[V]], t.Optional[str]]] = None,294 item_show_func: t.Callable[[V | None], str | None] | None = None,295 fill_char: str = "#",296 empty_char: str = "-",297 bar_template: str = "%(label)s [%(bar)s] %(info)s",298 info_sep: str = " ",299 width: int = 36,296 file: t.Optional[t.TextIO] = None,297 color: t.Optional[bool] = None,300 file: t.TextIO | None = None,301 color: bool | None = None,302 update_min_steps: int = 1,299) -> "ProgressBar[V]":303) -> ProgressBar[V]:304 """This function creates an iterable context manager that can be used305 to iterate over something while showing a progress bar. It will306 either iterate over the `iterable` or `length` items (that are counted307 up). While iteration happens, this function will print a rendered
141 unmodified lines
449 # ANSI escape \033[2J clears the screen, \033[1;1H moves the cursor450 echo("\033[2J\033[1;1H", nl=False)451452449def _interpret_color(450 color: t.Union[int, t.Tuple[int, int, int], str], offset: int = 0451) -> str:453def _interpret_color(color: int | tuple[int, int, int] | str, offset: int = 0) -> str:454 if isinstance(color, int):455 return f"{38 + offset};5;{color:d}"456457 if isinstance(color, (tuple, list)):
4 unmodified lines
462463464def style(465 text: t.Any,464 fg: t.Optional[t.Union[int, t.Tuple[int, int, int], str]] = None,465 bg: t.Optional[t.Union[int, t.Tuple[int, int, int], str]] = None,466 bold: t.Optional[bool] = None,467 dim: t.Optional[bool] = None,468 underline: t.Optional[bool] = None,469 overline: t.Optional[bool] = None,470 italic: t.Optional[bool] = None,471 blink: t.Optional[bool] = None,472 reverse: t.Optional[bool] = None,473 strikethrough: t.Optional[bool] = None,466 fg: int | tuple[int, int, int] | str | None = None,467 bg: int | tuple[int, int, int] | str | None = None,468 bold: bool | None = None,469 dim: bool | None = None,470 underline: bool | None = None,471 overline: bool | None = None,472 italic: bool | None = None,473 blink: bool | None = None,474 reverse: bool | None = None,475 strikethrough: bool | None = None,476 reset: bool = True,477) -> str:478 """Styles a text with ANSI styles and returns the new string. By479 default the styling is self contained which means that at the end
122 unmodified lines
602 return strip_ansi(text)603604605def secho(604 message: t.Optional[t.Any] = None,605 file: t.Optional[t.IO[t.AnyStr]] = None,606 message: t.Any | None = None,607 file: t.IO[t.AnyStr] | None = None,608 nl: bool = True,609 err: bool = False,608 color: t.Optional[bool] = None,610 color: bool | None = None,611 **styles: t.Any,612) -> None:613 """This function combines :func:`echo` and :func:`style` into one614 call. As such the following two calls are the same::
21 unmodified lines
636 return echo(message, file=file, nl=nl, err=err, color=color)637638639def edit(638 text: t.Optional[t.AnyStr] = None,639 editor: t.Optional[str] = None,640 env: t.Optional[t.Mapping[str, str]] = None,640 text: t.AnyStr | None = None,641 editor: str | None = None,642 env: cabc.Mapping[str, str] | None = None,643 require_save: bool = True,644 extension: str = ".txt",643 filename: t.Optional[str] = None,644) -> t.Optional[t.AnyStr]:645 filename: str | None = None,646) -> t.AnyStr | None:647 r"""Edits the given text in the defined editor. If an editor is given648 (should be the full path to the executable but the regular operating649 system search path is used for finding the executable) it overrides650 the detected editor. Optionally, some environment variables can be
61 unmodified lines
712713714# If this is provided, getchar() calls into this instead. This is used715# for unittesting purposes.714_getchar: t.Optional[t.Callable[[bool], str]] = None716_getchar: t.Callable[[bool], str] | None = None717718719def getchar(echo: bool = False) -> str:720 """Fetches a single character from the terminal and returns it. This
24 unmodified lines
745746 return _getchar(echo)747748747def raw_terminal() -> t.ContextManager[int]:749def raw_terminal() -> AbstractContextManager[int]:750 from ._termui_impl import raw_terminal as f751752 return f()753754753def pause(info: t.Optional[str] = None, err: bool = False) -> None:755def pause(info: str | None = None, err: bool = False) -> None:756 """This command stops execution and waits for the user to press any757 key to continue. This is similar to the Windows batch "pause"758 command. If the program is not run through a terminal, this command759 will instead do nothing.
27 unmodified lines
modified:src/click/testing.py+32 added-30 removed
1from __future__ import annotations23import collections.abc as cabc4import contextlib5import io6import os7import shlex
35 unmodified lines
4344 def readline(self, n: int = -1) -> bytes:45 return self._echo(self._input.readline(n))4644 def readlines(self) -> t.List[bytes]:47 def readlines(self) -> list[bytes]:48 return [self._echo(x) for x in self._input.readlines()]4947 def __iter__(self) -> t.Iterator[bytes]:50 def __iter__(self) -> cabc.Iterator[bytes]:51 return iter(self._echo(x) for x in self._input)5253 def __repr__(self) -> str:54 return repr(self._input)555657@contextlib.contextmanager55def _pause_echo(stream: t.Optional[EchoingStdin]) -> t.Iterator[None]:58def _pause_echo(stream: EchoingStdin | None) -> cabc.Iterator[None]:59 if stream is None:60 yield61 else:62 stream._paused = True
18 unmodified lines
81 return self._mode828384def make_input_stream(82 input: t.Optional[t.Union[str, bytes, t.IO[t.Any]]], charset: str85 input: str | bytes | t.IO[t.Any] | None, charset: str86) -> t.BinaryIO:87 # Is already an input stream.88 if hasattr(input, "read"):86 rv = _find_binary_reader(t.cast(t.IO[t.Any], input))89 rv = _find_binary_reader(t.cast("t.IO[t.Any]", input))9091 if rv is not None:92 return rv93
11 unmodified lines
105 """Holds the captured result of an invoked CLI script."""106107 def __init__(108 self,106 runner: "CliRunner",109 runner: CliRunner,110 stdout_bytes: bytes,108 stderr_bytes: t.Optional[bytes],111 stderr_bytes: bytes | None,112 return_value: t.Any,113 exit_code: int,111 exception: t.Optional[BaseException],112 exc_info: t.Optional[113 t.Tuple[t.Type[BaseException], BaseException, TracebackType]114 ] = None,114 exception: BaseException | None,115 exc_info: tuple[type[BaseException], BaseException, TracebackType]116 | None = None,117 ):118 #: The runner that created the result119 self.runner = runner120 #: The standard output as bytes.
58 unmodified lines
179180 def __init__(181 self,182 charset: str = "utf-8",181 env: t.Optional[t.Mapping[str, t.Optional[str]]] = None,183 env: cabc.Mapping[str, str | None] | None = None,184 echo_stdin: bool = False,185 mix_stderr: bool = True,186 ) -> None:187 self.charset = charset186 self.env: t.Mapping[str, t.Optional[str]] = env or {}188 self.env: cabc.Mapping[str, str | None] = env or {}189 self.echo_stdin = echo_stdin190 self.mix_stderr = mix_stderr191190 def get_default_prog_name(self, cli: "Command") -> str:192 def get_default_prog_name(self, cli: Command) -> str:193 """Given a command object it will return the default program name194 for it. The default is the `name` attribute or ``"root"`` if not195 set.196 """197 return cli.name or "root"198199 def make_env(198 self, overrides: t.Optional[t.Mapping[str, t.Optional[str]]] = None199 ) -> t.Mapping[str, t.Optional[str]]:200 self, overrides: cabc.Mapping[str, str | None] | None = None201 ) -> cabc.Mapping[str, str | None]:202 """Returns the environment overrides for invoking a script."""203 rv = dict(self.env)204 if overrides:205 rv.update(overrides)
1 unmodified line
207208 @contextlib.contextmanager209 def isolation(210 self,209 input: t.Optional[t.Union[str, bytes, t.IO[t.Any]]] = None,210 env: t.Optional[t.Mapping[str, t.Optional[str]]] = None,211 input: str | bytes | t.IO[t.Any] | None = None,212 env: cabc.Mapping[str, str | None] | None = None,213 color: bool = False,212 ) -> t.Iterator[t.Tuple[io.BytesIO, t.Optional[io.BytesIO]]]:214 ) -> cabc.Iterator[tuple[io.BytesIO, io.BytesIO | None]]:215 """A context manager that sets up the isolation for invoking of a216 command line tool. This sets up stdin with the given input data217 and `os.environ` with the overrides from the given dictionary.218 This also rebinds some internals in Click to be mocked (like the
57 unmodified lines
276 errors="backslashreplace",277 )278279 @_pause_echo(echo_input) # type: ignore278 def visible_input(prompt: t.Optional[str] = None) -> str:280 def visible_input(prompt: str | None = None) -> str:281 sys.stdout.write(prompt or "")282 val = text_input.readline().rstrip("\r\n")283 sys.stdout.write(f"{val}\n")284 sys.stdout.flush()285 return val286287 @_pause_echo(echo_input) # type: ignore286 def hidden_input(prompt: t.Optional[str] = None) -> str:288 def hidden_input(prompt: str | None = None) -> str:289 sys.stdout.write(f"{prompt or ''}\n")290 sys.stdout.flush()291 return text_input.readline().rstrip("\r\n")292
9 unmodified lines
302303 default_color = color304305 def should_strip_ansi(304 stream: t.Optional[t.IO[t.Any]] = None, color: t.Optional[bool] = None306 stream: t.IO[t.Any] | None = None, color: bool | None = None307 ) -> bool:308 if color is None:309 return not default_color310 return not color
38 unmodified lines
349 formatting.FORCED_WIDTH = old_forced_width350351 def invoke(352 self,351 cli: "Command",352 args: t.Optional[t.Union[str, t.Sequence[str]]] = None,353 input: t.Optional[t.Union[str, bytes, t.IO[t.Any]]] = None,354 env: t.Optional[t.Mapping[str, t.Optional[str]]] = None,353 cli: Command,354 args: str | cabc.Sequence[str] | None = None,355 input: str | bytes | t.IO[t.Any] | None = None,356 env: cabc.Mapping[str, str | None] | None = None,357 catch_exceptions: bool = True,358 color: bool = False,359 **extra: t.Any,360 ) -> Result:
33 unmodified lines
394 """395 exc_info = None396 with self.isolation(input=input, env=env, color=color) as outstreams:397 return_value = None396 exception: t.Optional[BaseException] = None398 exception: BaseException | None = None399 exit_code = 0400401 if isinstance(args, str):402 args = shlex.split(args)
6 unmodified lines
409 try:410 return_value = cli.main(args=args or (), prog_name=prog_name, **extra)411 except SystemExit as e:412 exc_info = sys.exc_info()411 e_code = t.cast(t.Optional[t.Union[int, t.Any]], e.code)413 e_code = t.cast("int | t.Any | None", e.code)414415 if e_code is None:416 e_code = 0417
32 unmodified lines
450 )451452 @contextlib.contextmanager453 def isolated_filesystem(452 self, temp_dir: t.Optional[t.Union[str, "os.PathLike[str]"]] = None453 ) -> t.Iterator[str]:454 self, temp_dir: str | os.PathLike[str] | None = None455 ) -> cabc.Iterator[str]:456 """A context manager that creates a temporary directory and457 changes the current working directory to it. This isolates tests458 that affect the contents of the CWD to prevent them from459 interfering with each other.
22 unmodified lines
modified:src/click/types.py+76 added-71 removed
1from __future__ import annotations23import collections.abc as cabc4import os5import stat6import sys7import typing as t
44 unmodified lines
52 #: means any whitespace. For all parameters the general rule is that53 #: whitespace splits them up. The exception are paths and files which54 #: are split by ``os.path.pathsep`` by default (":" on Unix and ";" on55 #: Windows).53 envvar_list_splitter: t.ClassVar[t.Optional[str]] = None56 envvar_list_splitter: t.ClassVar[str | None] = None5755 def to_info_dict(self) -> t.Dict[str, t.Any]:58 def to_info_dict(self) -> dict[str, t.Any]:59 """Gather information that could be useful for a tool generating60 user-facing documentation.6162 Use :meth:`click.Context.to_info_dict` to traverse the entire
15 unmodified lines
7879 def __call__(80 self,81 value: t.Any,79 param: t.Optional["Parameter"] = None,80 ctx: t.Optional["Context"] = None,82 param: Parameter | None = None,83 ctx: Context | None = None,84 ) -> t.Any:85 if value is not None:86 return self.convert(value, param, ctx)8785 def get_metavar(self, param: "Parameter") -> t.Optional[str]:88 def get_metavar(self, param: Parameter) -> str | None:89 """Returns the metavar default for this param if it provides one."""9088 def get_missing_message(self, param: "Parameter") -> t.Optional[str]:91 def get_missing_message(self, param: Parameter) -> str | None:92 """Optionally might return extra information about a missing93 parameter.9495 .. versionadded:: 2.096 """9798 def convert(96 self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]99 self, value: t.Any, param: Parameter | None, ctx: Context | None100 ) -> t.Any:101 """Convert the value to the correct type. This is not called if102 the value is ``None`` (the missing value).103
14 unmodified lines
118 be ``None``.119 """120 return value121119 def split_envvar_value(self, rv: str) -> t.Sequence[str]:122 def split_envvar_value(self, rv: str) -> cabc.Sequence[str]:123 """Given a value from an environment variable this splits it up124 into small chunks depending on the defined envvar list splitter.125126 If the splitter is set to `None`, which means that whitespace splits,
4 unmodified lines
131132 def fail(133 self,134 message: str,132 param: t.Optional["Parameter"] = None,133 ctx: t.Optional["Context"] = None,134 ) -> "t.NoReturn":135 param: Parameter | None = None,136 ctx: Context | None = None,137 ) -> t.NoReturn:138 """Helper method to fail with an invalid value message."""139 raise BadParameter(message, ctx=ctx, param=param)140141 def shell_complete(139 self, ctx: "Context", param: "Parameter", incomplete: str140 ) -> t.List["CompletionItem"]:142 self, ctx: Context, param: Parameter, incomplete: str143 ) -> list[CompletionItem]:144 """Return a list of145 :class:`~click.shell_completion.CompletionItem` objects for the146 incomplete value. Most types do not provide completions, but147 some do, and this allows custom types to provide custom
20 unmodified lines
168 def __init__(self, func: t.Callable[[t.Any], t.Any]) -> None:169 self.name: str = func.__name__170 self.func = func171169 def to_info_dict(self) -> t.Dict[str, t.Any]:172 def to_info_dict(self) -> dict[str, t.Any]:173 info_dict = super().to_info_dict()174 info_dict["func"] = self.func175 return info_dict176177 def convert(175 self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]178 self, value: t.Any, param: Parameter | None, ctx: Context | None179 ) -> t.Any:180 try:181 return self.func(value)182 except ValueError:
8 unmodified lines
191class UnprocessedParamType(ParamType):192 name = "text"193194 def convert(192 self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]195 self, value: t.Any, param: Parameter | None, ctx: Context | None196 ) -> t.Any:197 return value198199 def __repr__(self) -> str:
3 unmodified lines
203class StringParamType(ParamType):204 name = "text"205206 def convert(204 self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]207 self, value: t.Any, param: Parameter | None, ctx: Context | None208 ) -> t.Any:209 if isinstance(value, bytes):210 enc = _get_argv_encoding()211 try:
32 unmodified lines
244 """245246 name = "choice"247245 def __init__(self, choices: t.Sequence[str], case_sensitive: bool = True) -> None:248 def __init__(249 self, choices: cabc.Sequence[str], case_sensitive: bool = True250 ) -> None:251 self.choices = choices252 self.case_sensitive = case_sensitive253249 def to_info_dict(self) -> t.Dict[str, t.Any]:254 def to_info_dict(self) -> dict[str, t.Any]:255 info_dict = super().to_info_dict()256 info_dict["choices"] = self.choices257 info_dict["case_sensitive"] = self.case_sensitive258 return info_dict259255 def get_metavar(self, param: "Parameter") -> str:260 def get_metavar(self, param: Parameter) -> str:261 choices_str = "|".join(self.choices)262263 # Use curly braces to indicate a required argument.264 if param.required and param.param_type_name == "argument":
1 unmodified line
266267 # Use square braces to indicate an option or optional argument.268 return f"[{choices_str}]"269265 def get_missing_message(self, param: "Parameter") -> str:270 def get_missing_message(self, param: Parameter) -> str:271 return _("Choose from:\n\t{choices}").format(choices=",\n\t".join(self.choices))272273 def convert(269 self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]274 self, value: t.Any, param: Parameter | None, ctx: Context | None275 ) -> t.Any:276 # Match through normalization and case sensitivity277 # first do token_normalize_func, then lowercase278 # preserve original `value` to produce an accurate message in
32 unmodified lines
311 def __repr__(self) -> str:312 return f"Choice({list(self.choices)})"313314 def shell_complete(310 self, ctx: "Context", param: "Parameter", incomplete: str311 ) -> t.List["CompletionItem"]:315 self, ctx: Context, param: Parameter, incomplete: str316 ) -> list[CompletionItem]:317 """Complete choices that start with the incomplete value.318319 :param ctx: Invocation context for this command.320 :param param: The parameter that is requesting completion.
36 unmodified lines
357 """358359 name = "datetime"360356 def __init__(self, formats: t.Optional[t.Sequence[str]] = None):357 self.formats: t.Sequence[str] = formats or [361 def __init__(self, formats: cabc.Sequence[str] | None = None):362 self.formats: cabc.Sequence[str] = formats or [363 "%Y-%m-%d",364 "%Y-%m-%dT%H:%M:%S",365 "%Y-%m-%d %H:%M:%S",366 ]367363 def to_info_dict(self) -> t.Dict[str, t.Any]:368 def to_info_dict(self) -> dict[str, t.Any]:369 info_dict = super().to_info_dict()370 info_dict["formats"] = self.formats371 return info_dict372368 def get_metavar(self, param: "Parameter") -> str:373 def get_metavar(self, param: Parameter) -> str:374 return f"[{'|'.join(self.formats)}]"375371 def _try_to_convert_date(self, value: t.Any, format: str) -> t.Optional[datetime]:376 def _try_to_convert_date(self, value: t.Any, format: str) -> datetime | None:377 try:378 return datetime.strptime(value, format)379 except ValueError:380 return None381382 def convert(378 self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]383 self, value: t.Any, param: Parameter | None, ctx: Context | None384 ) -> t.Any:385 if isinstance(value, datetime):386 return value387
18 unmodified lines
406 return "DateTime"407408409class _NumberParamTypeBase(ParamType):405 _number_class: t.ClassVar[t.Type[t.Any]]410 _number_class: t.ClassVar[type[t.Any]]411412 def convert(408 self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]413 self, value: t.Any, param: Parameter | None, ctx: Context | None414 ) -> t.Any:415 try:416 return self._number_class(value)417 except ValueError:
8 unmodified lines
426427class _NumberRangeBase(_NumberParamTypeBase):428 def __init__(429 self,425 min: t.Optional[float] = None,426 max: t.Optional[float] = None,430 min: float | None = None,431 max: float | None = None,432 min_open: bool = False,433 max_open: bool = False,434 clamp: bool = False,435 ) -> None:
2 unmodified lines
438 self.min_open = min_open439 self.max_open = max_open440 self.clamp = clamp441437 def to_info_dict(self) -> t.Dict[str, t.Any]:442 def to_info_dict(self) -> dict[str, t.Any]:443 info_dict = super().to_info_dict()444 info_dict.update(445 min=self.min,446 max=self.max,
3 unmodified lines
450 )451 return info_dict452453 def convert(449 self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]454 self, value: t.Any, param: Parameter | None, ctx: Context | None455 ) -> t.Any:456 import operator457458 rv = super().convert(value, param, ctx)
21 unmodified lines
480 )481482 return rv483479 def _clamp(self, bound: float, dir: "te.Literal[1, -1]", open: bool) -> float:484 def _clamp(self, bound: float, dir: t.Literal[1, -1], open: bool) -> float:485 """Find the valid value to clamp to bound in the given486 direction.487488 :param bound: The boundary value.
46 unmodified lines
535536 name = "integer range"537538 def _clamp( # type: ignore534 self, bound: int, dir: "te.Literal[1, -1]", open: bool539 self, bound: int, dir: t.Literal[1, -1], open: bool540 ) -> int:541 if not open:542 return bound543
27 unmodified lines
571 name = "float range"572573 def __init__(574 self,570 min: t.Optional[float] = None,571 max: t.Optional[float] = None,575 min: float | None = None,576 max: float | None = None,577 min_open: bool = False,578 max_open: bool = False,579 clamp: bool = False,580 ) -> None:
3 unmodified lines
584585 if (min_open or max_open) and clamp:586 raise TypeError("Clamping is not supported for open bounds.")587583 def _clamp(self, bound: float, dir: "te.Literal[1, -1]", open: bool) -> float:588 def _clamp(self, bound: float, dir: t.Literal[1, -1], open: bool) -> float:589 if not open:590 return bound591592 # Could use Python 3.9's math.nextafter here, but clamping an
5 unmodified lines
598class BoolParamType(ParamType):599 name = "boolean"600601 def convert(597 self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]602 self, value: t.Any, param: Parameter | None, ctx: Context | None603 ) -> t.Any:604 if value in {False, True}:605 return bool(value)606
16 unmodified lines
623class UUIDParameterType(ParamType):624 name = "uuid"625626 def convert(622 self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]627 self, value: t.Any, param: Parameter | None, ctx: Context | None628 ) -> t.Any:629 import uuid630631 if isinstance(value, uuid.UUID):
44 unmodified lines
676677 def __init__(678 self,679 mode: str = "r",675 encoding: t.Optional[str] = None,676 errors: t.Optional[str] = "strict",677 lazy: t.Optional[bool] = None,680 encoding: str | None = None,681 errors: str | None = "strict",682 lazy: bool | None = None,683 atomic: bool = False,684 ) -> None:685 self.mode = mode686 self.encoding = encoding687 self.errors = errors688 self.lazy = lazy689 self.atomic = atomic690686 def to_info_dict(self) -> t.Dict[str, t.Any]:691 def to_info_dict(self) -> dict[str, t.Any]:692 info_dict = super().to_info_dict()693 info_dict.update(mode=self.mode, encoding=self.encoding)694 return info_dict695691 def resolve_lazy_flag(self, value: "t.Union[str, os.PathLike[str]]") -> bool:696 def resolve_lazy_flag(self, value: str | os.PathLike[str]) -> bool:697 if self.lazy is not None:698 return self.lazy699 if os.fspath(value) == "-":700 return False
2 unmodified lines
703 return False704705 def convert(706 self,702 value: t.Union[str, "os.PathLike[str]", t.IO[t.Any]],703 param: t.Optional["Parameter"],704 ctx: t.Optional["Context"],707 value: str | os.PathLike[str] | t.IO[t.Any],708 param: Parameter | None,709 ctx: Context | None,710 ) -> t.IO[t.Any]:711 if _is_file_like(value):712 return value713709 value = t.cast("t.Union[str, os.PathLike[str]]", value)714 value = t.cast("str | os.PathLike[str]", value)715716 try:717 lazy = self.resolve_lazy_flag(value)718
4 unmodified lines
723724 if ctx is not None:725 ctx.call_on_close(lf.close_intelligently)726722 return t.cast(t.IO[t.Any], lf)727 return t.cast("t.IO[t.Any]", lf)728729 f, should_close = open_stream(730 value, self.mode, self.encoding, self.errors, atomic=self.atomic731 )
13 unmodified lines
745 except OSError as e: # noqa: B014746 self.fail(f"'{format_filename(value)}': {e.strerror}", param, ctx)747748 def shell_complete(744 self, ctx: "Context", param: "Parameter", incomplete: str745 ) -> t.List["CompletionItem"]:749 self, ctx: Context, param: Parameter, incomplete: str750 ) -> list[CompletionItem]:751 """Return a special completion marker that tells the completion752 system to use the shell to provide file path completions.753754 :param ctx: Invocation context for this command.
6 unmodified lines
761762 return [CompletionItem(incomplete, type="file")]763764760def _is_file_like(value: t.Any) -> "te.TypeGuard[t.IO[t.Any]]":765def _is_file_like(value: t.Any) -> te.TypeGuard[t.IO[t.Any]]:766 return hasattr(value, "read") or hasattr(value, "write")767768769class Path(ParamType):
39 unmodified lines
809 writable: bool = False,810 readable: bool = True,811 resolve_path: bool = False,812 allow_dash: bool = False,808 path_type: t.Optional[t.Type[t.Any]] = None,813 path_type: type[t.Any] | None = None,814 executable: bool = False,815 ):816 self.exists = exists817 self.file_okay = file_okay
11 unmodified lines
829 self.name = _("directory")830 else:831 self.name = _("path")832828 def to_info_dict(self) -> t.Dict[str, t.Any]:833 def to_info_dict(self) -> dict[str, t.Any]:834 info_dict = super().to_info_dict()835 info_dict.update(836 exists=self.exists,837 file_okay=self.file_okay,
4 unmodified lines
842 )843 return info_dict844845 def coerce_path_result(841 self, value: "t.Union[str, os.PathLike[str]]"842 ) -> "t.Union[str, bytes, os.PathLike[str]]":846 self, value: str | os.PathLike[str]847 ) -> str | bytes | os.PathLike[str]:848 if self.type is not None and not isinstance(value, self.type):849 if self.type is str:850 return os.fsdecode(value)851 elif self.type is bytes:
4 unmodified lines
856 return value857858 def convert(859 self,855 value: "t.Union[str, os.PathLike[str]]",856 param: t.Optional["Parameter"],857 ctx: t.Optional["Context"],858 ) -> "t.Union[str, bytes, os.PathLike[str]]":860 value: str | os.PathLike[str],861 param: Parameter | None,862 ctx: Context | None,863 ) -> str | bytes | os.PathLike[str]:864 rv = value865866 is_dash = self.file_okay and self.allow_dash and rv in (b"-", "-")867
60 unmodified lines
928929 return self.coerce_path_result(rv)930931 def shell_complete(927 self, ctx: "Context", param: "Parameter", incomplete: str928 ) -> t.List["CompletionItem"]:932 self, ctx: Context, param: Parameter, incomplete: str933 ) -> list[CompletionItem]:934 """Return a special completion marker that tells the completion935 system to use the shell to provide path completions for only936 directories or any paths.937
22 unmodified lines
960961 :param types: a list of types that should be used for the tuple items.962 """963959 def __init__(self, types: t.Sequence[t.Union[t.Type[t.Any], ParamType]]) -> None:960 self.types: t.Sequence[ParamType] = [convert_type(ty) for ty in types]964 def __init__(self, types: cabc.Sequence[type[t.Any] | ParamType]) -> None:965 self.types: cabc.Sequence[ParamType] = [convert_type(ty) for ty in types]966962 def to_info_dict(self) -> t.Dict[str, t.Any]:967 def to_info_dict(self) -> dict[str, t.Any]:968 info_dict = super().to_info_dict()969 info_dict["types"] = [t.to_info_dict() for t in self.types]970 return info_dict971
5 unmodified lines
977 def arity(self) -> int: # type: ignore978 return len(self.types)979980 def convert(976 self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]981 self, value: t.Any, param: Parameter | None, ctx: Context | None982 ) -> t.Any:983 len_type = len(self.types)984 len_value = len(value)985
10 unmodified lines
996997 return tuple(ty(x, param, ctx) for ty, x in zip(self.types, value))998999995def convert_type(ty: t.Optional[t.Any], default: t.Optional[t.Any] = None) -> ParamType:1000def convert_type(ty: t.Any | None, default: t.Any | None = None) -> ParamType:1001 """Find the most appropriate :class:`ParamType` for the given Python1002 type. If the type isn't provided, it can be inferred from a default1003 value.1004 """
86 unmodified lines
modified:src/click/utils.py+35 added-32 removed
1from __future__ import annotations23import collections.abc as cabc4import os5import re6import sys7import typing as t
24 unmodified lines
32def _posixify(name: str) -> str:33 return "-".join(name.split()).lower()343533def safecall(func: "t.Callable[P, R]") -> "t.Callable[P, t.Optional[R]]":36def safecall(func: t.Callable[P, R]) -> t.Callable[P, R | None]:37 """Wraps a function so that it swallows exceptions."""3836 def wrapper(*args: "P.args", **kwargs: "P.kwargs") -> t.Optional[R]:39 def wrapper(*args: P.args, **kwargs: P.kwargs) -> R | None:40 try:41 return func(*args, **kwargs)42 except Exception:43 pass
70 unmodified lines
114 """115116 def __init__(117 self,115 filename: t.Union[str, "os.PathLike[str]"],118 filename: str | os.PathLike[str],119 mode: str = "r",117 encoding: t.Optional[str] = None,118 errors: t.Optional[str] = "strict",120 encoding: str | None = None,121 errors: str | None = "strict",122 atomic: bool = False,123 ):124 self.name: str = os.fspath(filename)125 self.mode = mode126 self.encoding = encoding127 self.errors = errors128 self.atomic = atomic126 self._f: t.Optional[t.IO[t.Any]]129 self._f: t.IO[t.Any] | None130 self.should_close: bool131132 if self.name == "-":133 self._f, self.should_close = open_stream(filename, mode, encoding, errors)
43 unmodified lines
177 """178 if self.should_close:179 self.close()180178 def __enter__(self) -> "LazyFile":181 def __enter__(self) -> LazyFile:182 return self183184 def __exit__(185 self,183 exc_type: t.Optional[t.Type[BaseException]],184 exc_value: t.Optional[BaseException],185 tb: t.Optional[TracebackType],186 exc_type: type[BaseException] | None,187 exc_value: BaseException | None,188 tb: TracebackType | None,189 ) -> None:190 self.close_intelligently()191189 def __iter__(self) -> t.Iterator[t.AnyStr]:192 def __iter__(self) -> cabc.Iterator[t.AnyStr]:193 self.open()194 return iter(self._f) # type: ignore195196
3 unmodified lines
200201 def __getattr__(self, name: str) -> t.Any:202 return getattr(self._file, name)203201 def __enter__(self) -> "KeepOpenFile":204 def __enter__(self) -> KeepOpenFile:205 return self206207 def __exit__(208 self,206 exc_type: t.Optional[t.Type[BaseException]],207 exc_value: t.Optional[BaseException],208 tb: t.Optional[TracebackType],209 exc_type: type[BaseException] | None,210 exc_value: BaseException | None,211 tb: TracebackType | None,212 ) -> None:213 pass214215 def __repr__(self) -> str:216 return repr(self._file)217215 def __iter__(self) -> t.Iterator[t.AnyStr]:218 def __iter__(self) -> cabc.Iterator[t.AnyStr]:219 return iter(self._file)220221222def echo(220 message: t.Optional[t.Any] = None,221 file: t.Optional[t.IO[t.Any]] = None,223 message: t.Any | None = None,224 file: t.IO[t.Any] | None = None,225 nl: bool = True,226 err: bool = False,224 color: t.Optional[bool] = None,227 color: bool | None = None,228) -> None:229 """Print a message and newline to stdout or a file. This should be230 used instead of :func:`print` because it provides better support231 for different data, files, and environments.
44 unmodified lines
276 return277278 # Convert non bytes/text into the native string type.279 if message is not None and not isinstance(message, (str, bytes, bytearray)):277 out: t.Optional[t.Union[str, bytes]] = str(message)280 out: str | bytes | None = str(message)281 else:282 out = message283284 if nl:
36 unmodified lines
321 file.write(out) # type: ignore322 file.flush()323324322def get_binary_stream(name: "te.Literal['stdin', 'stdout', 'stderr']") -> t.BinaryIO:325def get_binary_stream(name: t.Literal["stdin", "stdout", "stderr"]) -> t.BinaryIO:326 """Returns a system stream for byte processing.327328 :param name: the name of the stream to open. Valid names are ``'stdin'``,329 ``'stdout'`` and ``'stderr'``
4 unmodified lines
334 return opener()335336337def get_text_stream(335 name: "te.Literal['stdin', 'stdout', 'stderr']",336 encoding: t.Optional[str] = None,337 errors: t.Optional[str] = "strict",338 name: t.Literal["stdin", "stdout", "stderr"],339 encoding: str | None = None,340 errors: str | None = "strict",341) -> t.TextIO:342 """Returns a system stream for text processing. This usually returns343 a wrapped stream around a binary stream returned from344 :func:`get_binary_stream` but it also can take shortcuts for already
12 unmodified lines
357358def open_file(359 filename: str,360 mode: str = "r",358 encoding: t.Optional[str] = None,359 errors: t.Optional[str] = "strict",361 encoding: str | None = None,362 errors: str | None = "strict",363 lazy: bool = False,364 atomic: bool = False,365) -> t.IO[t.Any]:366 """Open a file, with extra behavior to handle ``'-'`` to indicate
25 unmodified lines
392 .. versionadded:: 3.0393 """394 if lazy:395 return t.cast(393 t.IO[t.Any], LazyFile(filename, mode, encoding, errors, atomic=atomic)396 "t.IO[t.Any]", LazyFile(filename, mode, encoding, errors, atomic=atomic)397 )398399 f, should_close = open_stream(filename, mode, encoding, errors, atomic=atomic)400401 if not should_close:399 f = t.cast(t.IO[t.Any], KeepOpenFile(f))402 f = t.cast("t.IO[t.Any]", KeepOpenFile(f))403404 return f405406407def format_filename(405 filename: "t.Union[str, bytes, os.PathLike[str], os.PathLike[bytes]]",408 filename: str | bytes | os.PathLike[str] | os.PathLike[bytes],409 shorten: bool = False,410) -> str:411 """Format a filename as a string for display. Ensures the filename can be412 displayed by replacing any invalid bytes or surrogate escapes in the name
107 unmodified lines
520 return getattr(self.wrapped, attr)521522523def _detect_program_name(521 path: t.Optional[str] = None, _main: t.Optional[ModuleType] = None524 path: str | None = None, _main: ModuleType | None = None525) -> str:526 """Determine the command used to run the program, for use in help527 text. If a file or entry point was executed, the file name is528 returned. If ``python -m`` was used to execute a module or package,
46 unmodified lines
575 return f"python -m {py_module.lstrip('.')}"576577578def _expand_args(576 args: t.Iterable[str],579 args: cabc.Iterable[str],580 *,581 user: bool = True,582 env: bool = True,583 glob_recursive: bool = True,581) -> t.List[str]:584) -> list[str]:585 """Simulate Unix shell expansion with Python functions.586587 See :func:`glob.glob`, :func:`os.path.expanduser`, and588 :func:`os.path.expandvars`.
39 unmodified lines
modified:tests/test_imports.py+2 added
25 unmodified lines
26click.echo(json.dumps(rv))27"""2829ALLOWED_IMPORTS = {30 "__future__",31 "weakref",32 "os",33 "struct",34 "collections",35 "collections.abc",36 "sys",37 "contextlib",38 "functools",39 "stat",
31 unmodified lines
modified:CHANGES.rst+3 added
22 unmodified lines
23 - ``Parameter.add_to_parser`` (on both ``Argument`` and ``Option``) is24 unneeded. Parsing works directly without building a separate parser.25 - ``split_arg_string`` is moved from ``parser`` to ``shell_completion``.2627- Enable deferred evaluation of annotations with28 ``from __future__ import annotations``. :pr:`2270`293031Version 8.1.732-------------3334Released 2023-08-17
1100 unmodified lines