use modern typing features
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by David Lord · parent ecdeb0c · Browse files · 16 files·+563 added−575 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
16 files+563 added−575 removed
- tests:+1 added−0 removed
- other:+562 added−575 removed
Provenance
- Commit
ec258fe- Tree
fc2e59f- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
ecdeb0c
16 files changed+563 added−575 removed
modified:src/click/_compat.py+46 added-47 removed
1 from __future__ import annotations2 3 import codecs4+import collections.abc as cabc5 import io6 import os7 import re8 import sys9 import typing as t10+from types import TracebackType11 from weakref import WeakKeyDictionary12 13 CYGWIN = sys.platform.startswith("cygwin")14 WIN = sys.platform.startswith("win")13-auto_wrap_for_ansi: t.Optional[t.Callable[[t.TextIO], t.TextIO]] = None15+auto_wrap_for_ansi: t.Callable[[t.TextIO], t.TextIO] | None = None16 _ansi_re = re.compile(r"\033\[[;?0-9]*[a-zA-Z]")17 18 19 def _make_text_stream(20 stream: t.BinaryIO,19- encoding: t.Optional[str],20- 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 lines56 class _NonClosingTextIOWrapper(io.TextIOWrapper):57 def __init__(58 self,59 stream: t.BinaryIO,58- encoding: t.Optional[str],59- 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 lines169 return default170 return True171 172 171-def _find_binary_reader(stream: t.IO[t.Any]) -> t.Optional[t.BinaryIO]:173+def _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 lines187 188 return None189 190 189-def _find_binary_writer(stream: t.IO[t.Any]) -> t.Optional[t.BinaryIO]:191+def _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 lines214 # but this at least will force Click to recover somehow.215 return is_ascii_encoding(getattr(stream, "encoding", None) or "ascii")216 217 216-def _is_compat_stream_attr(stream: t.TextIO, attr: str, value: t.Optional[str]) -> bool:218+def _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 line224 return stream_value == value or (value is None and stream_value is not None)225 226 227 def _is_compatible_text_stream(226- 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 lines236 237 238 def _force_correct_text_stream(239 text_stream: t.IO[t.Any],238- encoding: t.Optional[str],239- errors: t.Optional[str],240+ encoding: str | None,241+ errors: str | None,242 is_binary: t.Callable[[t.IO[t.Any], bool], bool],241- 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 lines282 283 284 def _force_correct_text_reader(285 text_reader: t.IO[t.Any],284- encoding: t.Optional[str],285- 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 lines298 299 300 def _force_correct_text_writer(301 text_writer: t.IO[t.Any],300- encoding: t.Optional[str],301- 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 lines333 raise RuntimeError("Was not able to determine binary stream for sys.stderr.")334 return writer335 336 335-def get_text_stdin(336- encoding: t.Optional[str] = None, errors: t.Optional[str] = None337-) -> t.TextIO:337+def 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)342 343 344-def get_text_stdout(345- encoding: t.Optional[str] = None, errors: t.Optional[str] = None346-) -> t.TextIO:344+def 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)349 350 353-def get_text_stderr(354- encoding: t.Optional[str] = None, errors: t.Optional[str] = None355-) -> t.TextIO:351+def 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)356 357 358 def _wrap_io_open(363- file: t.Union[str, os.PathLike[str], int],359+ file: str | os.PathLike[str] | int,360 mode: str,365- encoding: t.Optional[str],366- 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 line368 return open(file, mode, encoding=encoding, errors=errors)369 370 371 def open_stream(376- filename: t.Union[str, os.PathLike[str]],372+ filename: str | os.PathLike[str],373 mode: str = "r",378- encoding: t.Optional[str] = None,379- errors: t.Optional[str] = "strict",374+ encoding: str | None = None,375+ errors: str | None = "strict",376 atomic: bool = False,381-) -> t.Tuple[t.IO[t.Any], bool]:377+) -> tuple[t.IO[t.Any], bool]:378 binary = "b" in mode379 filename = os.fspath(filename)380 381 # Standard streams first. These are simple because they ignore the31 unmodified lines413 import errno414 import random415 416 try:421- perm: t.Optional[int] = os.stat(filename).st_mode417+ perm: int | None = os.stat(filename).st_mode418 except OSError:419 perm = None420 421 flags = os.O_RDWR | os.O_CREAT | os.O_EXCL50 unmodified lines472 473 def __enter__(self) -> _AtomicFile:474 return self475 480- 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)483 484 def __repr__(self) -> str:485 return repr(self._f)10 unmodified lines496 return stream.__class__.__module__.startswith("ipykernel.")497 498 499 def should_strip_ansi(499- 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.stdin11 unmodified lines516 import locale517 518 return locale.getpreferredencoding()519 519- _ansi_stream_wrappers: t.MutableMapping[t.TextIO, t.TextIO] = WeakKeyDictionary()520+ _ansi_stream_wrappers: cabc.MutableMapping[t.TextIO, t.TextIO] = WeakKeyDictionary()521 522 def auto_wrap_for_ansi( # noqa: F811522- 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 lines561 def _get_argv_encoding() -> str:562 return getattr(sys.stdin, "encoding", None) or sys.getfilesystemencoding()563 564 def _get_windows_console_stream(564- f: t.TextIO, encoding: t.Optional[str], errors: t.Optional[str]565- ) -> t.Optional[t.TextIO]:565+ f: t.TextIO, encoding: str | None, errors: str | None566+ ) -> t.TextIO | None:567 return None568 569 570 def term_len(x: str) -> int:7 unmodified lines578 return False579 580 581 def _make_cached_stream_func(581- src_func: t.Callable[[], t.Optional[t.TextIO]],582+ src_func: t.Callable[[], t.TextIO | None],583 wrapper_func: t.Callable[[], t.TextIO],583-) -> t.Callable[[], t.Optional[t.TextIO]]:584- cache: t.MutableMapping[t.TextIO, t.TextIO] = WeakKeyDictionary()584+) -> t.Callable[[], t.TextIO | None]:585+ cache: cabc.MutableMapping[t.TextIO, t.TextIO] = WeakKeyDictionary()586 586- def func() -> t.Optional[t.TextIO]:587+ def func() -> t.TextIO | None:588 stream = src_func()589 590 if stream is None:591 return None18 unmodified lines610 _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)612 613 613-binary_streams: t.Mapping[str, t.Callable[[], t.BinaryIO]] = {614+binary_streams: cabc.Mapping[str, t.Callable[[], t.BinaryIO]] = {615 "stdin": get_binary_stdin,616 "stdout": get_binary_stdout,617 "stderr": get_binary_stderr,618 }619 619-text_streams: t.Mapping[620- str, t.Callable[[t.Optional[str], t.Optional[str]], t.TextIO]621-] = {620+text_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+32 added-33 removed
3 unmodified lines4 placed in this module and only imported as needed.5 """6 from __future__ import annotations7 8+import collections.abc as cabc9 import contextlib10 import math11 import os12 import sys26 unmodified lines39 40 class ProgressBar(t.Generic[V]):41 def __init__(42 self,42- iterable: t.Optional[t.Iterable[V]],43- 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,49- show_percent: t.Optional[bool] = None,50+ show_percent: bool | None = None,51 show_pos: bool = False,51- item_show_func: t.Optional[t.Callable[[t.Optional[V]], t.Optional[str]]] = None,52- label: t.Optional[str] = None,53- file: t.Optional[t.TextIO] = None,54- 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_char30 unmodified lines90 length = None91 if iterable is None:92 if length is None:93 raise TypeError("iterable or length is required")93- iterable = t.cast(t.Iterable[V], range(length))94- 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 = 097- 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 = False103- self.max_width: t.Optional[int] = None104+ self.max_width: int | None = None105 self.entered: bool = False105- self.current_item: t.Optional[V] = None106+ self.current_item: V | None = None107 self.is_hidden: bool = not isatty(self.file)107- self._last_line: t.Optional[str] = None108+ self._last_line: str | None = None109 110 def __enter__(self) -> ProgressBar[V]:111 self.entered = True112 self.render_progress()113 return self114 115 def __exit__(116 self,116- exc_type: t.Optional[t.Type[BaseException]],117- exc_value: t.Optional[BaseException],118- 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()122 122- 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 lines294 self.avg = self.avg[-6:] + [step]295 296 self.eta_known = self.length is not None297 297- 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 lines325 self.eta_known = False326 self.current_item = None327 self.finished = True328 328- 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 lines359 self.finish()360 self.render_progress()361 362 362-def pager(generator: t.Iterable[str], color: t.Optional[bool] = None) -> None:363+def 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()366 367 # There are no standard streams attached to write to. For example,26 unmodified lines394 finally:395 os.unlink(filename)396 397 397-def _pipepager(generator: t.Iterable[str], cmd: str, color: t.Optional[bool]) -> None:398+def _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 subprocess41 unmodified lines444 else:445 break446 447 447-def _tempfilepager(448- generator: t.Iterable[str], cmd: str, color: t.Optional[bool]449-) -> None:448+def _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 tempfile451 452 fd, filename = tempfile.mkstemp()11 unmodified lines464 os.unlink(filename)465 466 467 def _nullpager(469- 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 lines476 477 class Editor:478 def __init__(479 self,481- editor: t.Optional[str] = None,482- 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 = editor18 unmodified lines504 def edit_file(self, filename: str) -> None:505 import subprocess506 507 editor = self.get_editor()509- environ: t.Optional[t.Dict[str, str]] = None508+ environ: dict[str, str] | None = None509 510 if self.env:511 environ = os.environ.copy()512 environ.update(self.env)9 unmodified lines522 raise ClickException(523 _("{editor}: Editing failed: {e}").format(editor=editor, e=e)524 ) from e525 527- 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 tempfile528 529 if not text:530 data = b""99 unmodified lines630 return 0631 return 1632 633 635-def _translate_ch_to_exc(ch: str) -> t.Optional[BaseException]:634+def _translate_ch_to_exc(ch: str) -> None:635 if ch == "\x03":636 raise KeyboardInterrupt()637 638 if ch == "\x04" and not WIN: # Unix-like, Ctrl+D8 unmodified lines647 if WIN:648 import msvcrt649 650 @contextlib.contextmanager652- def raw_terminal() -> t.Iterator[int]:651+ def raw_terminal() -> cabc.Iterator[int]:652 yield -1653 654 def getchar(echo: bool) -> str:655 # The function `getch` will return a bytes object corresponding to46 unmodified lines702 import tty703 import termios704 705 @contextlib.contextmanager707- def raw_terminal() -> t.Iterator[int]:708- f: t.Optional[t.TextIO]706+ def raw_terminal() -> cabc.Iterator[int]:707+ f: t.TextIO | None708 fd: int709 710 if not isatty(sys.stdin):711 f = open("/dev/tty")29 unmodified linesmodified:src/click/_textwrap.py+4 added-4 removed
1 from __future__ import annotations2 3+import collections.abc as cabc4 import textwrap4-import typing as t5 from contextlib import contextmanager6 7 8 class TextWrapper(textwrap.TextWrapper):9 def _handle_long_word(10 self,11- reversed_chunks: t.List[str],12- 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 lines24 elif not cur_line:25 cur_line.append(reversed_chunks.pop())26 27 @contextmanager28- 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 += indent19 unmodified linesmodified:src/click/_winconsole.py+5 added-4 removed
6 unmodified lines7 # the entire interpreter but just work in our little world of8 # echo and prompt.9 from __future__ import annotations10 11+import collections.abc as cabc12 import io13 import sys14 import time15 import typing as t182 unmodified lines198 except Exception:199 pass200 return self.buffer.write(x)201 201- 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)205 206 def __getattr__(self, name: str) -> t.Any:35 unmodified lines242 )243 return t.cast(t.TextIO, ConsoleStream(text_stream, buffer_stream))244 245 245-_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 lines263 return bool(GetConsoleMode(handle, byref(DWORD())))264 265 266 def _get_windows_console_stream(266- f: t.TextIO, encoding: t.Optional[str], errors: t.Optional[str]267-) -> 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 linesmodified:src/click/core.py+188 added-197 removed
1 from __future__ import annotations2 3+import collections.abc as cabc4 import enum5 import errno6 import inspect7 import os8 import sys9 import typing as t10 from collections import abc11+from contextlib import AbstractContextManager12 from contextlib import contextmanager13 from contextlib import ExitStack14 from functools import update_wrapper15 from gettext import gettext as _25 unmodified lines41 from .utils import make_str42 from .utils import PacifyFlushWrapper43 44 if t.TYPE_CHECKING:43- import typing_extensions as te45 from .shell_completion import CompletionItem46 46-F = t.TypeVar("F", bound=t.Callable[..., t.Any])47+F = t.TypeVar("F", bound="t.Callable[..., t.Any]")48 V = t.TypeVar("V")49 50 51 def _complete_visible_commands(52 ctx: Context, incomplete: str52-) -> t.Iterator[t.Tuple[str, Command]]:53+) -> cabc.Iterator[tuple[str, Command]]:54 """List all the subcommands of a group that start with the55 incomplete value and aren't hidden.56 57 :param ctx: Invocation context for the group.28 unmodified lines86 87 raise RuntimeError(message)88 89 89-def batch(iterable: t.Iterable[V], batch_size: int) -> t.List[t.Tuple[V, ...]]:90+def batch(iterable: cabc.Iterable[V], batch_size: int) -> list[tuple[V, ...]]:91 return list(zip(*repeat(iter(iterable), batch_size)))92 93 94 @contextmanager95 def augment_usage_errors(95- ctx: Context, param: t.Optional[Parameter] = None96-) -> 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 lines110 raise111 112 113 def iter_params_for_processing(113- invocation_order: t.Sequence[Parameter],114- declaration_order: t.Sequence[Parameter],115-) -> 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 """121 121- 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 lines257 258 #: The formatter class to create with :meth:`make_formatter`.259 #:260 #: .. versionadded:: 8.0260- formatter_class: t.Type[HelpFormatter] = HelpFormatter261+ formatter_class: type[HelpFormatter] = HelpFormatter262 263 def __init__(264 self,265 command: Command,265- parent: t.Optional[Context] = None,266- info_name: t.Optional[str] = None,267- obj: t.Optional[t.Any] = None,268- auto_envvar_prefix: t.Optional[str] = None,269- default_map: t.Optional[t.MutableMapping[str, t.Any]] = None,270- terminal_width: t.Optional[int] = None,271- max_content_width: t.Optional[int] = None,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,273- allow_extra_args: t.Optional[bool] = None,274- allow_interspersed_args: t.Optional[bool] = None,275- ignore_unknown_options: t.Optional[bool] = None,276- help_option_names: t.Optional[t.List[str]] = None,277- token_normalize_func: t.Optional[t.Callable[[str], str]] = None,278- color: t.Optional[bool] = None,279- 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 line286 #: 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.289- self.params: t.Dict[str, t.Any] = {}290+ self.params: dict[str, t.Any] = {}291 #: the leftover arguments.291- 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.296- self._protected_args: t.List[str] = []297+ self._protected_args: list[str] = []298 #: the collected prefixes of the command's options.298- 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()300 301 if obj is None and parent is not None:302 obj = parent.obj303 304 #: the user object stored.305 self.obj: t.Any = obj305- self._meta: t.Dict[str, t.Any] = getattr(parent, "meta", {})306+ self._meta: dict[str, t.Any] = getattr(parent, "meta", {})307 308 #: A dictionary (-like object) with defaults for parameters.309 if (310 default_map is None2 unmodified lines313 and parent.default_map is not None314 ):315 default_map = parent.default_map.get(info_name)316 316- self.default_map: t.Optional[t.MutableMapping[str, t.Any]] = default_map317+ self.default_map: cabc.MutableMapping[str, t.Any] | None = default_map318 319 #: 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 passes3 unmodified lines325 #: 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`.328- self.invoked_subcommand: t.Optional[str] = None329+ self.invoked_subcommand: str | None = None330 331 if terminal_width is None and parent is not None:332 terminal_width = parent.terminal_width333 334 #: The width of the terminal (None is autodetection).334- self.terminal_width: t.Optional[int] = terminal_width335+ self.terminal_width: int | None = terminal_width336 337 if max_content_width is None and parent is not None:338 max_content_width = parent.max_content_width339 340 #: The maximum width of formatted content (None implies a sensible341 #: default which is 80 for most things).341- self.max_content_width: t.Optional[int] = max_content_width342+ self.max_content_width: int | None = max_content_width343 344 if allow_extra_args is None:345 allow_extra_args = command.allow_extra_args346 31 unmodified lines378 else:379 help_option_names = ["--help"]380 381 #: The names for the help options.381- self.help_option_names: t.List[str] = help_option_names382+ self.help_option_names: list[str] = help_option_names383 384 if token_normalize_func is None and parent is not None:385 token_normalize_func = parent.token_normalize_func386 387 #: An optional normalization function for tokens. This is388 #: options, choices, commands etc.388- self.token_normalize_func: t.Optional[389- t.Callable[[str], str]390- ] = token_normalize_func389+ self.token_normalize_func: t.Callable[[str], str] | None = token_normalize_func390 391 #: 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 lines410 411 if auto_envvar_prefix is not None:412 auto_envvar_prefix = auto_envvar_prefix.replace("-", "_")413 415- self.auto_envvar_prefix: t.Optional[str] = auto_envvar_prefix414+ self.auto_envvar_prefix: str | None = auto_envvar_prefix415 416 if color is None and parent is not None:417 color = parent.color418 419 #: Controls if styling output is wanted or not.421- self.color: t.Optional[bool] = color420+ self.color: bool | None = color421 422 if show_default is None and parent is not None:423 show_default = parent.show_default424 425 #: Show option default values when formatting help text.427- self.show_default: t.Optional[bool] = show_default426+ self.show_default: bool | None = show_default427 429- self._close_callbacks: t.List[t.Callable[[], t.Any]] = []428+ self._close_callbacks: list[t.Callable[[], t.Any]] = []429 self._depth = 0431- self._parameter_source: t.Dict[str, ParameterSource] = {}430+ self._parameter_source: dict[str, ParameterSource] = {}431 self._exit_stack = ExitStack()432 433 @property435- def protected_args(self) -> t.List[str]:434+ def protected_args(self) -> list[str]:435 import warnings436 437 warnings.warn(438 "'protected_args' is deprecated and will be removed in Click 9.0."2 unmodified lines441 stacklevel=2,442 )443 return self._protected_args444 446- 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 19 unmodified lines469 return self470 471 def __exit__(472 self,474- exc_type: t.Optional[t.Type[BaseException]],475- exc_value: t.Optional[BaseException],476- 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()481 482 @contextmanager484- 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 cleanup29 unmodified lines517 if not cleanup:518 self._depth -= 1519 520 @property522- 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 lines558 return self.formatter_class(559 width=self.terminal_width, max_width=self.max_content_width560 )561 563- 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 67 unmodified lines634 while node.parent is not None:635 node = node.parent636 return node637 639- 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."""641- node: t.Optional[Context] = self640+ node: Context | None = self641 642 while node is not None:643 if isinstance(node.obj, object_type):644 return node.obj1 unmodified line646 node = node.parent647 648 return None649 651- 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 line656 self.obj = rv = object_type()657 return rv658 659 @t.overload661- def lookup_default(662- self, name: str, call: te.Literal[True] = True663- ) -> t.Optional[t.Any]:660+ def lookup_default(self, name: str, call: t.Literal[True] = True) -> t.Any | None:661 ...662 663 @t.overload664 def lookup_default(668- self, name: str, call: te.Literal[False] = ...669- ) -> 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 ...668 672- 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`.671 672 :param name: Name of the parameter.673 :param call: If the default is a callable, call it. Disable to11 unmodified lines685 return value686 687 return None688 692- 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.692 693 :param message: the error message to fail with.694 """695 raise UsageError(message, self)696 700- def abort(self) -> te.NoReturn:697+ def abort(self) -> t.NoReturn:698 """Aborts the script."""699 raise Abort()700 704- 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)704 705 def get_usage(self) -> str:35 unmodified lines741 ...742 743 def invoke(744 __self, # noqa: B902748- __callback: t.Union[Command, t.Callable[..., V]],745+ __callback: Command | t.Callable[..., V],746 *args: t.Any,747 **kwargs: t.Any,751- ) -> 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:751 752 1. the first argument can be a callback and all other arguments and69 unmodified lines822 :param source: A member of :class:`~click.core.ParameterSource`.823 """824 self._parameter_source[name] = source825 829- 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.829 830 This can be useful for determining when a user specified a value58 unmodified lines889 890 #: The context class to create with :meth:`make_context`.891 #:892 #: .. versionadded:: 8.0896- context_class: t.Type[Context] = Context893+ context_class: type[Context] = Context894 895 #: the default for the :attr:`Context.allow_extra_args` flag.896 allow_extra_args = False897 4 unmodified lines902 ignore_unknown_options = False903 904 def __init__(905 self,909- name: t.Optional[str],910- context_settings: t.Optional[t.MutableMapping[str, t.Any]] = None,911- callback: t.Optional[t.Callable[..., t.Any]] = None,912- params: t.Optional[t.List[Parameter]] = None,913- help: t.Optional[str] = None,914- epilog: t.Optional[str] = None,915- short_help: t.Optional[str] = None,916- 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 lines925 if context_settings is None:926 context_settings = {}927 928 #: an optional dictionary with defaults passed to the context.932- self.context_settings: t.MutableMapping[str, t.Any] = context_settings929+ self.context_settings: cabc.MutableMapping[str, t.Any] = context_settings930 931 #: 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.940- 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_help1 unmodified line943 self.no_args_is_help = no_args_is_help944 self.hidden = hidden945 self.deprecated = deprecated946 950- 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 lines966 formatter = ctx.make_formatter()967 self.format_usage(ctx, formatter)968 return formatter.getvalue().rstrip("\n")969 973- 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)973 974 if help_option is not None:8 unmodified lines983 """984 pieces = self.collect_usage_pieces(ctx)985 formatter.write_usage(ctx.command_path, " ".join(pieces))986 990- 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 lines994 rv.extend(param.get_usage_pieces(ctx))995 996 return rv997 1001- 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)1005 1009- 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)1009 1010 if not help_options or not self.add_help_option:101 unmodified lines1112 formatter.write_text(epilog)1113 1114 def make_context(1115 self,1119- info_name: t.Optional[str],1120- args: t.List[str],1121- 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 not24 unmodified lines1147 with ctx.scope(cleanup=False):1148 self.parse_args(ctx, args)1149 return ctx1150 1154- 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 lines1184 1185 if self.callback is not None:1186 return ctx.invoke(self.callback, **ctx.params)1187 1191- 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.1191 1192 Any command could be part of a chained multi-command, so sibling5 unmodified lines1198 .. versionadded:: 8.01199 """1200 from click.shell_completion import CompletionItem1201 1205- results: t.List[CompletionItem] = []1202+ results: list[CompletionItem] = []1203 1204 if incomplete and not incomplete[0].isalnum():1205 for param in self.get_params(ctx):1206 if (27 unmodified lines1234 1235 @t.overload1236 def main(1237 self,1241- args: t.Optional[t.Sequence[str]] = None,1242- prog_name: t.Optional[str] = None,1243- complete_var: t.Optional[str] = None,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,1243 ) -> t.NoReturn:1244 ...1245 1246 @t.overload1247 def main(1248 self,1252- args: t.Optional[t.Sequence[str]] = None,1253- prog_name: t.Optional[str] = None,1254- 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 ...1256 1257 def main(1258 self,1262- args: t.Optional[t.Sequence[str]] = None,1263- prog_name: t.Optional[str] = None,1264- 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 lines1368 sys.exit(1)1369 1370 def _main_shell_completion(1371 self,1375- ctx_args: t.MutableMapping[str, t.Any],1372+ ctx_args: cabc.MutableMapping[str, t.Any],1373 prog_name: str,1377- 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 lines1456 #: as the default :class:`Command` class. This is useful to make all1457 #: subcommands use a custom command class.1458 #:1459 #: .. versionadded:: 8.01463- command_class: t.Optional[t.Type[Command]] = None1460+ command_class: type[Command] | None = None1461 1462 #: 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 lines1468 #: default class. This makes a custom group class continue to make1469 #: custom groups.1470 #:1471 #: .. versionadded:: 8.01475- 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]1474 1475 def __init__(1476 self,1480- name: t.Optional[str] = None,1481- commands: t.Optional[1482- t.Union[t.MutableMapping[str, Command], t.Sequence[Command]]1483- ] = 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,1485- no_args_is_help: t.Optional[bool] = None,1486- subcommand_metavar: t.Optional[str] = None,1482+ no_args_is_help: bool | None = None,1483+ subcommand_metavar: str | None = None,1484 chain: bool = False,1488- 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 lines1492 elif isinstance(commands, abc.Sequence):1493 commands = {c.name: c for c in commands if c.name is not None}1494 1495 #: The registered subcommands by their exported names.1499- self.commands: t.MutableMapping[str, Command] = commands1496+ self.commands: cabc.MutableMapping[str, Command] = commands1497 1498 if no_args_is_help is None:1499 no_args_is_help = not invoke_without_command1500 18 unmodified lines1519 raise RuntimeError(1520 "A group in chain mode cannot have optional arguments."1521 )1522 1526- 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 = {}1526 1527 for name in self.list_commands(ctx):9 unmodified lines1537 1538 info_dict.update(commands=commands, chain=self.chain)1539 return info_dict1540 1544- 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.name13 unmodified lines1559 ...1560 1561 def command(1562 self, *args: t.Any, **kwargs: t.Any1566- ) -> 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 lines1576 Added the :attr:`command_class` attribute.1577 """1578 from .decorators import command1579 1583- func: t.Optional[t.Callable[..., t.Any]] = None1580+ func: t.Callable[..., t.Any] | None = None1581 1582 if args and callable(args[0]):1583 assert (1584 len(args) == 1 and not kwargs25 unmodified lines1610 ...1611 1612 def group(1613 self, *args: t.Any, **kwargs: t.Any1617- ) -> 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 lines1627 Added the :attr:`group_class` attribute.1628 """1629 from .decorators import group1630 1634- func: t.Optional[t.Callable[..., t.Any]] = None1631+ func: t.Callable[..., t.Any] | None = None1632 1633 if args and callable(args[0]):1634 assert (1635 len(args) == 1 and not kwargs61 unmodified lines1697 return rv1698 1699 return decorator1700 1704- 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)1706 1710- 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)1710 1714- 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 lines1744 if rows:1745 with formatter.section(_("Commands")):1746 formatter.write_dl(rows)1747 1751- 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 lines1828 rv.append(sub_ctx.command.invoke(sub_ctx))1829 return _process_result(rv)1830 1831 def resolve_command(1835- self, ctx: Context, args: t.List[str]1836- ) -> 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_name1836 1837 # Get the command16 unmodified lines1854 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:]1857 1861- 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 lines1899 """1900 1901 def __init__(1902 self,1906- name: t.Optional[str] = None,1907- 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.1912- self.sources: t.List[Group] = sources or []1909+ self.sources: list[Group] = sources or []1910 1911 def add_source(self, group: Group) -> None:1912 """Add a group as a source of commands."""1913 self.sources.append(group)1914 1918- 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)1917 1918 if rv is not None:1919 return rv8 unmodified lines1928 return rv1929 1930 return None1931 1935- def list_commands(self, ctx: Context) -> t.List[str]:1936- 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))1934 1935 for source in self.sources:1936 rv.update(source.list_commands(ctx))1937 1938 return sorted(rv)1939 1940 1944-def _check_iter(value: t.Any) -> t.Iterator[t.Any]:1941+def _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 lines2025 param_type_name = "parameter"2026 2027 def __init__(2028 self,2032- param_decls: t.Optional[t.Sequence[str]] = None,2033- 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,2035- default: t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]] = None,2036- callback: t.Optional[t.Callable[[Context, Parameter, t.Any], t.Any]] = None,2037- 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,2039- metavar: t.Optional[str] = None,2036+ metavar: str | None = None,2037 expose_value: bool = True,2038 is_eager: bool = False,2042- envvar: t.Optional[t.Union[str, t.Sequence[str]]] = None,2043- shell_complete: t.Optional[2044- t.Callable[2045- [Context, Parameter, str],2046- t.Union[t.List[CompletionItem], t.List[str]],2047- ]2048- ] = 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:2050- self.name: t.Optional[str]2051- self.opts: t.List[str]2052- 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 lines2109 raise ValueError(2110 f"'default' {subject} must match nargs={nargs}."2111 )2112 2118- 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.2116 2117 Use :meth:`click.Context.to_info_dict` to traverse the entire17 unmodified lines2135 def __repr__(self) -> str:2136 return f"<{self.__class__.__name__} {self.name}>"2137 2138 def _parse_decls(2144- self, decls: t.Sequence[str], expose_value: bool2145- ) -> 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()2142 2143 @property2144 def human_readable_name(self) -> str:16 unmodified lines2161 2162 return metavar2163 2164 @t.overload2170- def get_default(2171- self, ctx: Context, call: te.Literal[True] = True2172- ) -> t.Optional[t.Any]:2165+ def get_default(self, ctx: Context, call: t.Literal[True] = True) -> t.Any | None:2166 ...2167 2168 @t.overload2169 def get_default(2170 self, ctx: Context, call: bool = ...2178- ) -> t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]]:2171+ ) -> t.Any | t.Callable[[], t.Any] | None:2172 ...2173 2174 def get_default(2175 self, ctx: Context, call: bool = True2183- ) -> 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.2179 2180 :param ctx: Current context.26 unmodified lines2207 def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None:2208 raise NotImplementedError()2209 2210 def consume_value(2218- self, ctx: Context, opts: t.Mapping[str, t.Any]2219- ) -> 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.COMMANDLINE2215 2216 if value is None:16 unmodified lines2233 """2234 if value is None:2235 return () if self.multiple or self.nargs == -1 else None2236 2244- 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 lines2251 return self.type(value, param=self, ctx=ctx)2252 2253 elif self.nargs == -1:2254 2262- 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))2257 2258 else: # nargs > 12259 2267- 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))2262 2263 if len(value) != self.nargs:2264 raise BadParameter(32 unmodified lines2297 value = self.callback(ctx, self, value)2298 2299 return value2300 2308- 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 None2304 2305 if isinstance(self.envvar, str):9 unmodified lines2315 return rv2316 2317 return None2318 2326- def value_from_envvar(self, ctx: Context) -> t.Optional[t.Any]:2327- 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)2321 2322 if rv is not None and self.nargs != 1:2323 rv = self.type.split_envvar_value(rv)2324 2325 return rv2326 2327 def handle_parse_result(2335- self, ctx: Context, opts: t.Mapping[str, t.Any], args: t.List[str]2336- ) -> 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 lines2343 ctx.params[self.name] = value # type: ignore2344 2345 return value, args2346 2354- 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 pass2349 2357- def get_usage_pieces(self, ctx: Context) -> t.List[str]:2350+ def get_usage_pieces(self, ctx: Context) -> list[str]:2351 return []2352 2353 def get_error_hint(self, ctx: Context) -> str:2354 """Get a stringified version of the param for use in error messages to1 unmodified line2356 """2357 hint_list = self.opts or [self.human_readable_name]2358 return " / ".join(f"'{x}'" for x in hint_list)2359 2367- 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 lines2375 from click.shell_completion import CompletionItem2376 2377 results = [CompletionItem(c) for c in results]2378 2386- return t.cast(t.List["CompletionItem"], results)2379+ return t.cast("list[CompletionItem]", results)2380 2381 return self.type.shell_complete(ctx, self, incomplete)2382 2383 61 unmodified lines2445 param_type_name = "option"2446 2447 def __init__(2448 self,2456- param_decls: t.Optional[t.Sequence[str]] = None,2457- show_default: t.Union[bool, str, None] = None,2458- prompt: t.Union[bool, str] = False,2459- 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,2462- is_flag: t.Optional[bool] = None,2463- 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,2467- type: t.Optional[t.Union[types.ParamType, t.Any]] = None,2468- 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 lines2473 if prompt is True:2474 if self.name is None:2475 raise TypeError("'name' is required with 'prompt=True'.")2476 2484- 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 = prompt22 unmodified lines2504 # 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 None2507 2515- self.default: t.Union[t.Any, t.Callable[[], t.Any]]2508+ self.default: t.Any | t.Callable[[], t.Any]2509 2510 if is_flag and default_is_missing and not self.required:2511 if multiple:2512 self.default = ()48 unmodified lines2561 2562 if self.is_flag:2563 raise TypeError("'count' is not valid with 'is_flag'.")2564 2572- 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 lines2574 )2575 return info_dict2576 2577 def _parse_decls(2585- self, decls: t.Sequence[str], expose_value: bool2586- ) -> 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 lines2665 action=action,2666 nargs=self.nargs,2667 )2668 2676- 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 None2672 2673 any_prefix_is_slash = False2674 2682- def _write_opts(opts: t.Sequence[str]) -> str:2675+ def _write_opts(opts: cabc.Sequence[str]) -> str:2676 nonlocal any_prefix_is_slash2677 2678 rv, any_slashes = join_options(opts)2679 94 unmodified lines2774 2775 return ("; " if any_prefix_is_slash else " / ").join(rv), help2776 2777 @t.overload2785- def get_default(2786- self, ctx: Context, call: te.Literal[True] = True2787- ) -> t.Optional[t.Any]:2778+ def get_default(self, ctx: Context, call: t.Literal[True] = True) -> t.Any | None:2779 ...2780 2781 @t.overload2782 def get_default(2783 self, ctx: Context, call: bool = ...2793- ) -> t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]]:2784+ ) -> t.Any | t.Callable[[], t.Any] | None:2785 ...2786 2787 def get_default(2788 self, ctx: Context, call: bool = True2798- ) -> 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 lines2825 confirmation_prompt=self.confirmation_prompt,2826 value_proc=lambda x: self.process_value(ctx, x),2827 )2828 2838- 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)2831 2832 if rv is not None:2833 return rv10 unmodified lines2844 return rv2845 2846 return None2847 2857- def value_from_envvar(self, ctx: Context) -> t.Optional[t.Any]:2858- 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)2850 2851 if rv is None:2852 return None2853 7 unmodified lines2861 2862 return rv2863 2864 def consume_value(2874- self, ctx: Context, opts: t.Mapping[str, Parameter]2875- ) -> 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)2868 2869 # The parser will emit a sentinel value if the option can be2870 # given as a flag without a value. This is different from None39 unmodified lines2910 param_type_name = "argument"2911 2912 def __init__(2913 self,2923- param_decls: t.Sequence[str],2924- 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 lines2948 var += "..."2949 return var2950 2951 def _parse_decls(2961- self, decls: t.Sequence[str], expose_value: bool2962- ) -> 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 lines2964 f" {len(decls)}."2965 )2966 return name, [arg], []2967 2977- 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()]2970 2971 def get_error_hint(self, ctx: Context) -> str:2972 return f"'{self.make_metavar()}'"27 unmodified linesmodified:src/click/decorators.py+30 added-30 removed
20 unmodified lines21 22 R = t.TypeVar("R")23 T = t.TypeVar("T")24 _AnyCallable = t.Callable[..., t.Any]25-FC = t.TypeVar("FC", bound=t.Union[_AnyCallable, Command])25+FC = t.TypeVar("FC", bound="_AnyCallable | Command")26 27 28 def pass_context(f: t.Callable[te.Concatenate[Context, P], R]) -> t.Callable[P, R]:29 """Marks a callback as wanting to receive the current context5 unmodified lines35 36 return update_wrapper(new_func, f)37 38 39-def pass_obj(f: t.Callable[te.Concatenate[t.Any, P], R]) -> t.Callable[P, R]:39+def 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 """4 unmodified lines48 return update_wrapper(new_func, f)49 50 51 def make_pass_decorator(52- object_type: t.Type[T], ensure: bool = False52+ 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 type19 unmodified lines76 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()79 80- 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 lines97 return decorator # type: ignore[return-value]98 99 100 def pass_meta_key(101- key: str, *, doc_description: t.Optional[str] = None102-) -> 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 lines111 112 .. versionadded:: 8.0113 """114 115- def decorator(f: t.Callable[te.Concatenate[t.Any, P], R]) -> t.Callable[P, 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)22 unmodified lines142 # variant: with positional name and with positional or keyword cls argument:143 # @command(namearg, CommandCls, ...) or @command(namearg, cls=CommandCls, ...)144 @t.overload145 def command(146- name: t.Optional[str],147- 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 lines154 @t.overload155 def command(156 name: None = None,157 *,158- cls: t.Type[CmdType],158+ cls: type[CmdType],159 **attrs: t.Any,160 ) -> t.Callable[[_AnyCallable], CmdType]:161 ...162 163 164 # variant: with optional string name, no cls argument provided.165 @t.overload166 def command(167- name: t.Optional[str] = ..., cls: None = None, **attrs: t.Any167+ name: str | None = ..., cls: None = None, **attrs: t.Any168 ) -> t.Callable[[_AnyCallable], Command]:169 ...170 171 172 def command(173- name: t.Union[t.Optional[str], _AnyCallable] = None,174- cls: t.Optional[t.Type[CmdType]] = None,173+ name: str | _AnyCallable | None = None,174+ cls: type[CmdType] | None = None,175 **attrs: t.Any,176-) -> 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 lines202 The ``params`` argument can be used. Decorated params are203 appended to the end of the list.204 """205 206- func: t.Optional[t.Callable[[_AnyCallable], t.Any]] = None206+ func: t.Callable[[_AnyCallable], t.Any] | None = None207 208 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."213 214 if cls is None:215- cls = t.cast(t.Type[CmdType], Command)215+ cls = t.cast("type[CmdType]", Command)216 217 def decorator(f: _AnyCallable) -> CmdType:218 if isinstance(f, Command):219 raise TypeError("Attempted to convert a callback into a command twice.")43 unmodified lines263 # variant: with positional name and with positional or keyword cls argument:264 # @group(namearg, GroupCls, ...) or @group(namearg, cls=GroupCls, ...)265 @t.overload266 def group(267- name: t.Optional[str],268- 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 lines275 @t.overload276 def group(277 name: None = None,278 *,279- cls: t.Type[GrpType],279+ cls: type[GrpType],280 **attrs: t.Any,281 ) -> t.Callable[[_AnyCallable], GrpType]:282 ...283 284 285 # variant: with optional string name, no cls argument provided.286 @t.overload287 def group(288- name: t.Optional[str] = ..., cls: None = None, **attrs: t.Any288+ name: str | None = ..., cls: None = None, **attrs: t.Any289 ) -> t.Callable[[_AnyCallable], Group]:290 ...291 292 293 def group(294- name: t.Union[str, _AnyCallable, None] = None,295- cls: t.Optional[t.Type[GrpType]] = None,294+ name: str | _AnyCallable | None = None,295+ cls: type[GrpType] | None = None,296 **attrs: t.Any,297-) -> 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`.301 302 .. versionchanged:: 8.1303 This decorator can be applied without parentheses.304 """305 if cls is None:306- cls = t.cast(t.Type[GrpType], Group)306+ cls = t.cast("type[GrpType]", Group)307 308 if callable(name):309 return command(cls=cls, **attrs)(name)310 10 unmodified lines321 f.__click_params__.append(param) # type: ignore322 323 324 def argument(325- *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 lines349 return decorator350 351 352 def option(353- *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 lines418 return option(*param_decls, **kwargs)419 420 421 def version_option(422- version: t.Optional[str] = None,422+ version: str | None = None,423 *param_decls: str,424- package_name: t.Optional[str] = None,425- prog_name: t.Optional[str] = None,426- 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 linesmodified:src/click/exceptions.py+20 added-21 removed
1 from __future__ import annotations2 3+import collections.abc as cabc4 import typing as t5 from gettext import gettext as _6 from gettext import ngettext7 6 unmodified lines14 from .core import Context15 from .core import Parameter16 17 17-def _join_param_hints(18- param_hint: t.Optional[t.Union[t.Sequence[str], str]]19-) -> t.Optional[str]:18+def _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)21 22 return param_hint14 unmodified lines37 38 def __str__(self) -> str:39 return self.message40 42- 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()44 45 echo(_("Error: {message}").format(message=self.format_message()), file=file)9 unmodified lines55 """56 57 exit_code = 258 60- 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 = ctx63- self.cmd: t.Optional[Command] = self.ctx.command if self.ctx else None62+ self.cmd: Command | None = self.ctx.command if self.ctx else None63 65- 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 lines104 105 def __init__(106 self,107 message: str,109- ctx: t.Optional[Context] = None,110- param: t.Optional[Parameter] = None,111- 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_hint24 unmodified lines139 """140 141 def __init__(142 self,144- message: t.Optional[str] = None,145- ctx: t.Optional[Context] = None,146- param: t.Optional[Parameter] = None,147- param_hint: t.Optional[str] = None,148- 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_type151 152 def format_message(self) -> str:153 if self.param_hint is not None:155- 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 = None45 unmodified lines204 205 def __init__(206 self,207 option_name: str,209- message: t.Optional[str] = None,210- possibilities: t.Optional[t.Sequence[str]] = None,211- 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 lines239 :param option_name: the name of the option being used incorrectly.240 """241 242 def __init__(244- 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 lines257 258 class FileError(ClickException):259 """Raised if a file cannot be opened."""260 262- 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")264 265 super().__init__(hint)24 unmodified linesmodified:src/click/formatting.py+16 added-18 removed
1 from __future__ import annotations2 3-import typing as t3+import collections.abc as cabc4 from contextlib import contextmanager5 from gettext import gettext as _6 7 from ._compat import term_len8 from .parser import _split_opt9 10 # Can force a width. This is used by the test system11-FORCED_WIDTH: t.Optional[int] = None11+FORCED_WIDTH: int | None = None12 13 14-def measure_table(rows: t.Iterable[t.Tuple[str, str]]) -> t.Tuple[int, ...]:15- widths: t.Dict[int, int] = {}14+def measure_table(rows: cabc.Iterable[tuple[str, str]]) -> tuple[int, ...]:15+ widths: dict[int, int] = {}16 17 for row in rows:18 for idx, col in enumerate(row):19 widths[idx] = max(widths.get(idx, 0), term_len(col))1 unmodified line21 return tuple(y for x, y in sorted(widths.items()))22 23 24 def iter_rows(25- rows: t.Iterable[t.Tuple[str, str]], col_count: int26-) -> 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))29 30 33 unmodified lines64 )65 if not preserve_paragraphs:66 return wrapper.fill(text)67 68- p: t.List[t.Tuple[int, bool, str]] = []69- buf: t.List[str] = []68+ p: list[tuple[int, bool, str]] = []69+ buf: list[str] = []70 indent = None71 72 def _flush_par() -> None:73 if not buf:41 unmodified lines115 116 def __init__(117 self,118 indent_increment: int = 2,119- width: t.Optional[int] = None,120- max_width: t.Optional[int] = None,119+ width: int | None = None,120+ max_width: int | None = None,121 ) -> None:122 import shutil123 124 self.indent_increment = indent_increment4 unmodified lines129 if width is None:130 width = max(min(shutil.get_terminal_size().columns, max_width) - 2, 50)131 self.width = width132 self.current_indent = 0133- self.buffer: t.List[str] = []133+ self.buffer: list[str] = []134 135 def write(self, string: str) -> None:136 """Writes a unicode string into the internal buffer."""137 self.buffer.append(string)5 unmodified lines143 def dedent(self) -> None:144 """Decreases the indentation."""145 self.current_indent -= self.indent_increment146 147- def write_usage(148- self, prog: str, args: str = "", prefix: t.Optional[str] = None149- ) -> None:147+ def write_usage(self, prog: str, args: str = "", prefix: str | None = None) -> None:148 """Writes a usage line into the buffer.149 150 :param prog: the program name.151 :param args: whitespace separated list of arguments.56 unmodified lines208 self.write("\n")209 210 def write_dl(211 self,214- 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 options34 unmodified lines251 else:252 self.write("\n")253 254 @contextmanager257- 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.258 259 :param name: the section name that is written as heading.6 unmodified lines266 finally:267 self.dedent()268 269 @contextmanager272- 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 yield4 unmodified lines279 """Returns the buffer contents."""280 return "".join(self.buffer)281 282 285-def join_options(options: t.Sequence[str]) -> t.Tuple[str, bool]:283+def 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 linesmodified:src/click/globals.py+4 added-5 removed
2 unmodified lines3 import typing as t4 from threading import local5 6 if t.TYPE_CHECKING:7- import typing_extensions as te7 from .core import Context8 9 _local = local()10 11 12 @t.overload14-def get_current_context(silent: te.Literal[False] = False) -> Context:13+def get_current_context(silent: t.Literal[False] = False) -> Context:14 ...15 16 17 @t.overload19-def get_current_context(silent: bool = ...) -> t.Optional[Context]:18+def get_current_context(silent: bool = ...) -> Context | None:19 ...20 21 23-def get_current_context(silent: bool = False) -> t.Optional[Context]:22+def 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 be25 unmodified lines52 """Removes the top level from the stack."""53 _local.stack.pop()54 55 57-def resolve_color_default(color: t.Optional[bool] = None) -> t.Optional[bool]:56+def 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 linesmodified:src/click/parser.py+31 added-33 removed
21 unmodified lines22 # Copyright 2001-2006 Gregory P. Ward23 # Copyright 2002-2006 Python Software Foundation24 from __future__ import annotations25 26+import collections.abc as cabc27 import typing as t28 from collections import deque29 from gettext import gettext as _30 from gettext import ngettext3 unmodified lines34 from .exceptions import NoSuchOption35 from .exceptions import UsageError36 37 if t.TYPE_CHECKING:37- 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 CoreParameter6 unmodified lines48 _flag_needs_value = object()49 50 51 def _unpack_args(52- args: t.Sequence[str], nargs_spec: t.Sequence[int]53-) -> 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 lines61 Missing items are filled with `None`.62 """63 args = deque(args)64 nargs_spec = deque(nargs_spec)65- rv: t.List[t.Union[str, t.Tuple[t.Optional[str], ...], None]] = []66- spos: t.Optional[int] = None65+ rv: list[str | tuple[str | None, ...] | None] = []66+ spos: int | None = None67 68- 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 lines107 108 return tuple(rv), list(args)109 110 111-def _split_opt(opt: str) -> t.Tuple[str, str]:111+def _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:]118 119 120-def _normalize_opt(opt: str, ctx: t.Optional[Context]) -> str:120+def _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)}"2 unmodified lines127 class _Option:128 def __init__(129 self,130 obj: CoreOption,131- opts: t.Sequence[str],132- dest: t.Optional[str],133- action: t.Optional[str] = None,131+ opts: cabc.Sequence[str],132+ dest: str | None,133+ action: str | None = None,134 nargs: int = 1,135- const: t.Optional[t.Any] = None,135+ const: t.Any | None = None,136 ):137 self._short_opts = []138 self._long_opts = []139- self.prefixes: t.Set[str] = set()139+ self.prefixes: set[str] = set()140 141 for opt in opts:142 prefix, value = _split_opt(opt)143 if not prefix:34 unmodified lines178 state.order.append(self.obj)179 180 181 class _Argument:182- 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 = obj186 187 def process(188 self,189- value: t.Union[t.Optional[str], t.Sequence[t.Optional[str]]],189+ value: str | cabc.Sequence[str | None] | None,190 state: _ParsingState,191 ) -> None:192 if self.nargs > 1:193 assert value is not None16 unmodified lines210 state.order.append(self.obj)211 212 213 class _ParsingState:214- def __init__(self, rargs: t.List[str]) -> None:215- self.opts: t.Dict[str, t.Any] = {}216- 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 = rargs218- self.order: t.List[CoreParameter] = []218+ self.order: list[CoreParameter] = []219 220 221 class _OptionParser:222 """The option parser is an internal class that is ultimately used to11 unmodified lines234 .. deprecated:: 8.2235 Will be removed in Click 9.0.236 """237 238- 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 lines253 if ctx is not None:254 self.allow_interspersed_args = ctx.allow_interspersed_args255 self.ignore_unknown_options = ctx.ignore_unknown_options256 257- self._short_opt: t.Dict[str, _Option] = {}258- 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 = {"-", "--"}260- self._args: t.List[_Argument] = []260+ self._args: list[_Argument] = []261 262 def add_option(263 self,264 obj: CoreOption,265- opts: t.Sequence[str],266- dest: t.Optional[str],267- action: t.Optional[str] = None,265+ opts: cabc.Sequence[str],266+ dest: str | None,267+ action: str | None = None,268 nargs: int = 1,269- 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 lines283 self._short_opt[opt] = option284 for opt in option._long_opts:285 self._long_opt[opt] = option286 287- def add_argument(288- self, obj: CoreArgument, dest: t.Optional[str], nargs: int = 1289- ) -> 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.289 290 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))294 295 def parse_args(298- self, args: t.List[str]299- ) -> 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 they55 unmodified lines357 # *empty* -- still a subset of [arg0, ..., arg(i-1)], but358 # not a very interesting subset!359 360 def _match_long_opt(363- 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 linesmodified:src/click/shell_completion.py+21 added-22 removed
1 from __future__ import annotations2 3+import collections.abc as cabc4 import os5 import re6 import typing as t7 from gettext import gettext as _9 unmodified lines17 18 19 def shell_complete(20 cli: Command,20- 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 lines78 def __init__(79 self,80 value: t.Any,81 type: str = "plain",81- 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 = type86- self.help: t.Optional[str] = help87+ self.help: str | None = help88 self._info = kwargs89 90 def __getattr__(self, name: str) -> t.Any:91 return self._info.get(name)125 unmodified lines217 218 def __init__(219 self,220 cli: Command,220- 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 = cli8 unmodified lines234 """235 safe_name = re.sub(r"\W*", "", self.prog_name.replace("-", "_"), flags=re.ASCII)236 return f"_{safe_name}_completion"237 237- 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`.240 241 By default this provides ``complete_func``, ``complete_var``,242 and ``prog_name``.11 unmodified lines254 :meth:`source_vars`.255 """256 return self.source_template % self.source_vars()257 257- 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 NotImplementedError264 264- def get_completions(265- self, args: t.List[str], incomplete: str266- ) -> 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 lines330 def source(self) -> str:331 self._check_version()332 return super().source()333 335- 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 lines352 353 name = "zsh"354 source_template = _SOURCE_ZSH355 357- 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 lines374 375 name = "fish"376 source_template = _SOURCE_FISH377 379- 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 lines393 394 return f"{item.type},{item.value}"395 396 398-ShellCompleteType = t.TypeVar("ShellCompleteType", bound=t.Type[ShellComplete])397+ShellCompleteType = t.TypeVar("ShellCompleteType", bound="type[ShellComplete]")398 399 401-_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 }405 406 407 def add_completion_class(409- 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 lines423 424 return cls425 426 428-def get_completion_class(shell: str) -> t.Optional[t.Type[ShellComplete]]:427+def 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 line433 """434 return _available_shells.get(shell)435 436 438-def split_arg_string(string: str) -> t.List[str]:437+def 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 lines504 c = value[0]505 return c in ctx._opt_prefixes506 507 509-def _is_incomplete_option(ctx: Context, args: t.List[str], param: Parameter) -> bool:508+def _is_incomplete_option(ctx: Context, args: list[str], param: Parameter) -> bool:509 """Determine if the given parameter is an option that needs a value.510 511 :param args: List of complete args before the incomplete value.512 :param param: Option object being checked.17 unmodified lines530 531 532 def _resolve_context(533 cli: Command,535- ctx_args: t.MutableMapping[str, t.Any],534+ ctx_args: cabc.MutableMapping[str, t.Any],535 prog_name: str,537- 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 lines586 return ctx587 588 589 def _resolve_incomplete(591- ctx: Context, args: t.List[str], incomplete: str592-) -> 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.594 595 :param ctx: Invocation context for the command represented by38 unmodified linesmodified:src/click/termui.py+42 added-42 removed
1 from __future__ import annotations2 3+import collections.abc as cabc4 import inspect5 import io6 import itertools7 import sys8 import typing as t9+from contextlib import AbstractContextManager10 from gettext import gettext as _11 12 from ._compat import isatty13 from ._compat import strip_ansi46 unmodified lines60 def _build_prompt(61 text: str,62 suffix: str,63 show_default: bool = False,62- default: t.Optional[t.Any] = None,64+ default: t.Any | None = None,65 show_choices: bool = True,64- 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 lines81 82 83 def prompt(84 text: str,83- default: t.Optional[t.Any] = None,85+ default: t.Any | None = None,86 hide_input: bool = False,85- confirmation_prompt: t.Union[bool, str] = False,86- type: t.Optional[t.Union[ParamType, t.Any]] = None,87- 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 lines192 193 194 def confirm(195 text: str,194- 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 lines252 return rv253 254 255 def echo_via_pager(254- text_or_generator: t.Union[t.Iterable[str], t.Callable[[], t.Iterable[str]], str],255- 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 lines269 """270 color = resolve_color_default(color)271 272 if inspect.isgeneratorfunction(text_or_generator):271- 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:275- i = iter(t.cast(t.Iterable[str], text_or_generator))277+ i = iter(t.cast("cabc.Iterable[str]", text_or_generator))278 279 # 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 lines284 return pager(itertools.chain(text_generator, "\n"), color)285 286 287 def progressbar(286- iterable: t.Optional[t.Iterable[V]] = None,287- length: t.Optional[int] = None,288- 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,290- show_percent: t.Optional[bool] = None,292+ show_percent: bool | None = None,293 show_pos: bool = False,292- 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,298- file: t.Optional[t.TextIO] = None,299- color: t.Optional[bool] = None,300+ file: t.TextIO | None = None,301+ color: bool | None = None,302 update_min_steps: int = 1,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 will143 unmodified lines449 # ANSI escape \033[2J clears the screen, \033[1;1H moves the cursor450 echo("\033[2J\033[1;1H", nl=False)451 452 451-def _interpret_color(452- color: t.Union[int, t.Tuple[int, int, int], str], offset: int = 0453-) -> str:453+def _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}"456 457 if isinstance(color, (tuple, list)):4 unmodified lines462 463 464 def style(465 text: t.Any,466- fg: t.Optional[t.Union[int, t.Tuple[int, int, int], str]] = None,467- bg: t.Optional[t.Union[int, t.Tuple[int, int, int], str]] = None,468- bold: t.Optional[bool] = None,469- dim: t.Optional[bool] = None,470- underline: t.Optional[bool] = None,471- overline: t.Optional[bool] = None,472- italic: t.Optional[bool] = None,473- blink: t.Optional[bool] = None,474- reverse: t.Optional[bool] = None,475- 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 end122 unmodified lines602 return strip_ansi(text)603 604 605 def secho(606- message: t.Optional[t.Any] = None,607- 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,610- 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 lines636 return echo(message, file=file, nl=nl, err=err, color=color)637 638 639 def edit(640- text: t.Optional[t.AnyStr] = None,641- editor: t.Optional[str] = None,642- 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",645- filename: t.Optional[str] = None,646-) -> 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 be61 unmodified lines712 713 714 # If this is provided, getchar() calls into this instead. This is used715 # for unittesting purposes.716-_getchar: t.Optional[t.Callable[[bool], str]] = None716+_getchar: t.Callable[[bool], str] | None = None717 718 719 def getchar(echo: bool = False) -> str:720 """Fetches a single character from the terminal and returns it. This24 unmodified lines745 746 return _getchar(echo)747 748 749-def raw_terminal() -> t.ContextManager[int]:749+def raw_terminal() -> AbstractContextManager[int]:750 from ._termui_impl import raw_terminal as f751 752 return f()753 754 755-def pause(info: t.Optional[str] = None, err: bool = False) -> None:755+def 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 linesmodified:src/click/testing.py+27 added-27 removed
1 from __future__ import annotations2 3+import collections.abc as cabc4 import contextlib5 import io6 import os7 import shlex35 unmodified lines43 44 def readline(self, n: int = -1) -> bytes:45 return self._echo(self._input.readline(n))46 46- def readlines(self) -> t.List[bytes]:47+ def readlines(self) -> list[bytes]:48 return [self._echo(x) for x in self._input.readlines()]49 49- def __iter__(self) -> t.Iterator[bytes]:50+ def __iter__(self) -> cabc.Iterator[bytes]:51 return iter(self._echo(x) for x in self._input)52 53 def __repr__(self) -> str:54 return repr(self._input)55 56 57 @contextlib.contextmanager57-def _pause_echo(stream: t.Optional[EchoingStdin]) -> t.Iterator[None]:58+def _pause_echo(stream: EchoingStdin | None) -> cabc.Iterator[None]:59 if stream is None:60 yield61 else:62 stream._paused = True18 unmodified lines81 return self._mode82 83 84 def make_input_stream(84- 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"):88- rv = _find_binary_reader(t.cast(t.IO[t.Any], input))89+ rv = _find_binary_reader(t.cast("t.IO[t.Any]", input))90 91 if rv is not None:92 return rv93 13 unmodified lines107 def __init__(108 self,109 runner: CliRunner,110 stdout_bytes: bytes,110- stderr_bytes: t.Optional[bytes],111+ stderr_bytes: bytes | None,112 return_value: t.Any,113 exit_code: int,113- exception: t.Optional[BaseException],114- exc_info: t.Optional[115- t.Tuple[t.Type[BaseException], BaseException, TracebackType]116- ] = 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 lines179 180 def __init__(181 self,182 charset: str = "utf-8",183- 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 = charset188- 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_stderr191 192 def get_default_prog_name(self, cli: Command) -> str:3 unmodified lines196 """197 return cli.name or "root"198 199 def make_env(200- self, overrides: t.Optional[t.Mapping[str, t.Optional[str]]] = None201- ) -> 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 line207 208 @contextlib.contextmanager209 def isolation(210 self,211- input: t.Optional[t.Union[str, bytes, t.IO[t.Any]]] = None,212- 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,214- ) -> 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 the57 unmodified lines276 errors="backslashreplace",277 )278 279 @_pause_echo(echo_input) # type: ignore280- 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 val286 287 @_pause_echo(echo_input) # type: ignore288- 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 lines302 303 default_color = color304 305 def should_strip_ansi(306- 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 color39 unmodified lines350 351 def invoke(352 self,353 cli: Command,354- args: t.Optional[t.Union[str, t.Sequence[str]]] = None,355- input: t.Optional[t.Union[str, bytes, t.IO[t.Any]]] = None,356- env: t.Optional[t.Mapping[str, t.Optional[str]]] = None,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 lines394 """395 exc_info = None396 with self.isolation(input=input, env=env, color=color) as outstreams:397 return_value = None398- exception: t.Optional[BaseException] = None398+ exception: BaseException | None = None399 exit_code = 0400 401 if isinstance(args, str):402 args = shlex.split(args)6 unmodified lines409 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()413- e_code = t.cast(t.Optional[t.Union[int, t.Any]], e.code)413+ e_code = t.cast("int | t.Any | None", e.code)414 415 if e_code is None:416 e_code = 0417 32 unmodified lines450 )451 452 @contextlib.contextmanager453 def isolated_filesystem(454- self, temp_dir: t.Optional[t.Union[str, os.PathLike[str]]] = None455- ) -> 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 linesmodified:src/click/types.py+65 added-62 removed
1 from __future__ import annotations2 3+import collections.abc as cabc4 import os5 import stat6 import sys7 import typing as t44 unmodified lines52 #: 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).55- envvar_list_splitter: t.ClassVar[t.Optional[str]] = None56+ envvar_list_splitter: t.ClassVar[str | None] = None57 57- 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.61 62 Use :meth:`click.Context.to_info_dict` to traverse the entire15 unmodified lines78 79 def __call__(80 self,81 value: t.Any,81- param: t.Optional[Parameter] = None,82- 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)87 87- 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."""90 90- 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.94 95 .. versionadded:: 2.096 """97 98 def convert(98- 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 lines118 be ``None``.119 """120 return value121 121- 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.125 126 If the splitter is set to `None`, which means that whitespace splits,4 unmodified lines131 132 def fail(133 self,134 message: str,134- param: t.Optional[Parameter] = None,135- ctx: t.Optional[Context] = None,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)140 141 def shell_complete(142 self, ctx: Context, param: Parameter, incomplete: str142- ) -> t.List[CompletionItem]:143+ ) -> 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 custom20 unmodified lines168 def __init__(self, func: t.Callable[[t.Any], t.Any]) -> None:169 self.name: str = func.__name__170 self.func = func171 171- 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_dict176 177 def convert(177- 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 lines191 class UnprocessedParamType(ParamType):192 name = "text"193 194 def convert(194- 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 value198 199 def __repr__(self) -> str:3 unmodified lines203 class StringParamType(ParamType):204 name = "text"205 206 def convert(206- 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 lines244 """245 246 name = "choice"247 247- 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_sensitive253 251- 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_dict11 unmodified lines270 def get_missing_message(self, param: Parameter) -> str:271 return _("Choose from:\n\t{choices}").format(choices=",\n\t".join(self.choices))272 273 def convert(271- 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 in33 unmodified lines312 return f"Choice({list(self.choices)})"313 314 def shell_complete(315 self, ctx: Context, param: Parameter, incomplete: str313- ) -> t.List[CompletionItem]:316+ ) -> list[CompletionItem]:317 """Complete choices that start with the incomplete value.318 319 :param ctx: Invocation context for this command.320 :param param: The parameter that is requesting completion.36 unmodified lines357 """358 359 name = "datetime"360 358- def __init__(self, formats: t.Optional[t.Sequence[str]] = None):359- 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 ]367 365- 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_dict372 373 def get_metavar(self, param: Parameter) -> str:374 return f"[{'|'.join(self.formats)}]"375 373- 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 None381 382 def convert(380- 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 lines406 return "DateTime"407 408 409 class _NumberParamTypeBase(ParamType):407- _number_class: t.ClassVar[t.Type[t.Any]]410+ _number_class: t.ClassVar[type[t.Any]]411 412 def convert(410- 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 lines426 427 class _NumberRangeBase(_NumberParamTypeBase):428 def __init__(429 self,427- min: t.Optional[float] = None,428- 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 lines438 self.min_open = min_open439 self.max_open = max_open440 self.clamp = clamp441 439- 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 lines450 )451 return info_dict452 453 def convert(451- 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 operator457 458 rv = super().convert(value, param, ctx)21 unmodified lines480 )481 482 return rv483 481- 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.487 488 :param bound: The boundary value.46 unmodified lines535 536 name = "integer range"537 538 def _clamp( # type: ignore536- 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 lines571 name = "float range"572 573 def __init__(574 self,572- min: t.Optional[float] = None,573- 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 lines584 585 if (min_open or max_open) and clamp:586 raise TypeError("Clamping is not supported for open bounds.")587 585- 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 bound591 592 # Could use Python 3.9's math.nextafter here, but clamping an5 unmodified lines598 class BoolParamType(ParamType):599 name = "boolean"600 601 def convert(599- 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 lines623 class UUIDParameterType(ParamType):624 name = "uuid"625 626 def convert(624- 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 uuid630 631 if isinstance(value, uuid.UUID):44 unmodified lines676 677 def __init__(678 self,679 mode: str = "r",677- encoding: t.Optional[str] = None,678- errors: t.Optional[str] = "strict",679- 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 = atomic690 688- 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_dict695 693- 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 False2 unmodified lines703 return False704 705 def convert(706 self,704- value: t.Union[str, os.PathLike[str], t.IO[t.Any]],705- param: t.Optional[Parameter],706- 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 value713 711- value = t.cast("t.Union[str, os.PathLike[str]]", value)714+ value = t.cast("str | os.PathLike[str]", value)715 716 try:717 lazy = self.resolve_lazy_flag(value)718 4 unmodified lines723 724 if ctx is not None:725 ctx.call_on_close(lf.close_intelligently)726 724- return t.cast(t.IO[t.Any], lf)727+ return t.cast("t.IO[t.Any]", lf)728 729 f, should_close = open_stream(730 value, self.mode, self.encoding, self.errors, atomic=self.atomic731 )14 unmodified lines746 self.fail(f"'{format_filename(value)}': {e.strerror}", param, ctx)747 748 def shell_complete(749 self, ctx: Context, param: Parameter, incomplete: str747- ) -> t.List[CompletionItem]:750+ ) -> list[CompletionItem]:751 """Return a special completion marker that tells the completion752 system to use the shell to provide file path completions.753 754 :param ctx: Invocation context for this command.54 unmodified lines809 writable: bool = False,810 readable: bool = True,811 resolve_path: bool = False,812 allow_dash: bool = False,810- 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_okay11 unmodified lines829 self.name = _("directory")830 else:831 self.name = _("path")832 830- 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 lines842 )843 return info_dict844 845 def coerce_path_result(843- self, value: t.Union[str, os.PathLike[str]]844- ) -> 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 lines856 return value857 858 def convert(859 self,857- value: t.Union[str, os.PathLike[str]],858- param: t.Optional[Parameter],859- ctx: t.Optional[Context],860- ) -> 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 = value865 866 is_dash = self.file_okay and self.allow_dash and rv in (b"-", "-")867 61 unmodified lines929 return self.coerce_path_result(rv)930 931 def shell_complete(932 self, ctx: Context, param: Parameter, incomplete: str930- ) -> t.List[CompletionItem]:933+ ) -> 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 lines960 961 :param types: a list of types that should be used for the tuple items.962 """963 961- def __init__(self, types: t.Sequence[t.Union[t.Type[t.Any], ParamType]]) -> None:962- 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]966 964- 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 lines977 def arity(self) -> int: # type: ignore978 return len(self.types)979 980 def convert(978- 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 lines996 997 return tuple(ty(x, param, ctx) for ty, x in zip(self.types, value))998 999 997-def convert_type(ty: t.Optional[t.Any], default: t.Optional[t.Any] = None) -> ParamType:1000+def 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 linesmodified:src/click/utils.py+31 added-30 removed
1 from __future__ import annotations2 3+import collections.abc as cabc4 import os5 import re6 import sys7 import typing as t24 unmodified lines32 def _posixify(name: str) -> str:33 return "-".join(name.split()).lower()34 35 35-def safecall(func: t.Callable[P, R]) -> t.Callable[P, t.Optional[R]]:36+def safecall(func: t.Callable[P, R]) -> t.Callable[P, R | None]:37 """Wraps a function so that it swallows exceptions."""38 38- 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 pass70 unmodified lines114 """115 116 def __init__(117 self,117- filename: t.Union[str, os.PathLike[str]],118+ filename: str | os.PathLike[str],119 mode: str = "r",119- encoding: t.Optional[str] = None,120- 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 = atomic128- self._f: t.Optional[t.IO[t.Any]]129+ self._f: t.IO[t.Any] | None130 self.should_close: bool131 132 if self.name == "-":133 self._f, self.should_close = open_stream(filename, mode, encoding, errors)48 unmodified lines182 return self183 184 def __exit__(185 self,185- exc_type: t.Optional[t.Type[BaseException]],186- exc_value: t.Optional[BaseException],187- 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()191 191- def __iter__(self) -> t.Iterator[t.AnyStr]:192+ def __iter__(self) -> cabc.Iterator[t.AnyStr]:193 self.open()194 return iter(self._f) # type: ignore195 196 8 unmodified lines205 return self206 207 def __exit__(208 self,208- exc_type: t.Optional[t.Type[BaseException]],209- exc_value: t.Optional[BaseException],210- tb: t.Optional[TracebackType],209+ exc_type: type[BaseException] | None,210+ exc_value: BaseException | None,211+ tb: TracebackType | None,212 ) -> None:213 pass214 215 def __repr__(self) -> str:216 return repr(self._file)217 217- def __iter__(self) -> t.Iterator[t.AnyStr]:218+ def __iter__(self) -> cabc.Iterator[t.AnyStr]:219 return iter(self._file)220 221 222 def echo(222- message: t.Optional[t.Any] = None,223- 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,226- 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 lines276 return277 278 # Convert non bytes/text into the native string type.279 if message is not None and not isinstance(message, (str, bytes, bytearray)):279- out: t.Optional[t.Union[str, bytes]] = str(message)280+ out: str | bytes | None = str(message)281 else:282 out = message283 284 if nl:36 unmodified lines321 file.write(out) # type: ignore322 file.flush()323 324 324-def get_binary_stream(name: te.Literal["stdin", "stdout", "stderr"]) -> t.BinaryIO:325+def get_binary_stream(name: t.Literal["stdin", "stdout", "stderr"]) -> t.BinaryIO:326 """Returns a system stream for byte processing.327 328 :param name: the name of the stream to open. Valid names are ``'stdin'``,329 ``'stdout'`` and ``'stderr'``4 unmodified lines334 return opener()335 336 337 def get_text_stream(337- name: te.Literal["stdin", "stdout", "stderr"],338- encoding: t.Optional[str] = None,339- 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 already12 unmodified lines357 358 def open_file(359 filename: str,360 mode: str = "r",360- encoding: t.Optional[str] = None,361- 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 indicate25 unmodified lines392 .. versionadded:: 3.0393 """394 if lazy:395 return t.cast(395- t.IO[t.Any], LazyFile(filename, mode, encoding, errors, atomic=atomic)396+ "t.IO[t.Any]", LazyFile(filename, mode, encoding, errors, atomic=atomic)397 )398 399 f, should_close = open_stream(filename, mode, encoding, errors, atomic=atomic)400 401 if not should_close:401- f = t.cast(t.IO[t.Any], KeepOpenFile(f))402+ f = t.cast("t.IO[t.Any]", KeepOpenFile(f))403 404 return f405 406 407 def format_filename(407- 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 name107 unmodified lines520 return getattr(self.wrapped, attr)521 522 523 def _detect_program_name(523- 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 lines575 return f"python -m {py_module.lstrip('.')}"576 577 578 def _expand_args(578- args: t.Iterable[str],579+ args: cabc.Iterable[str],580 *,581 user: bool = True,582 env: bool = True,583 glob_recursive: bool = True,583-) -> t.List[str]:584+) -> list[str]:585 """Simulate Unix shell expansion with Python functions.586 587 See :func:`glob.glob`, :func:`os.path.expanduser`, and588 :func:`os.path.expandvars`.39 unmodified linesmodified:tests/test_imports.py+1 added
30 unmodified lines31 "weakref",32 "os",33 "struct",34 "collections",35+ "collections.abc",36 "sys",37 "contextlib",38 "functools",39 "stat",31 unmodified lines