add typing annotations
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 77ce48f · Browse files · 22 files·+1732 added−1062 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
22 files+1732 added−1062 removed
- tests:+18 added−22 removed
- other:+1714 added−1040 removed
Provenance
- Commit
0103c95- Tree
20c3c4e- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
77ce48f
22 files changed+1732 added−1062 removed
modified:examples/termui/termui.py+1 added-1 removed
143 unmodified lines144 @cli.command()145 def menu():146 """Shows a simple menu."""147 menu = "main"148- while 1:148+ while True:149 if menu == "main":150 click.echo("Main menu:")151 click.echo(" d: debug menu")152 click.echo(" q: quit")17 unmodified linesmodified:src/click/_compat.py+138 added-87 removed
15 unmodified lines16 auto_wrap_for_ansi: t.Optional[t.Callable[[t.TextIO], t.TextIO]] = None17 _ansi_re = re.compile(r"\033\[[;?0-9]*[a-zA-Z]")18 19 20-def get_filesystem_encoding():20+def get_filesystem_encoding() -> str:21 return sys.getfilesystemencoding() or sys.getdefaultencoding()22 23 24 def _make_text_stream(25- stream, encoding, errors, force_readable=False, force_writable=False26-):25+ stream: t.BinaryIO,26+ encoding: t.Optional[str],27+ errors: t.Optional[str],28+ force_readable: bool = False,29+ force_writable: bool = False,30+) -> t.TextIO:31 if encoding is None:32 encoding = get_best_encoding(stream)33 if errors is None:34 errors = "replace"6 unmodified lines41 force_writable=force_writable,42 )43 44 41-def is_ascii_encoding(encoding):45+def is_ascii_encoding(encoding: str) -> bool:46 """Checks if a given encoding is ascii."""47 try:48 return codecs.lookup(encoding).name == "ascii"49 except LookupError:50 return False51 52 49-def get_best_encoding(stream):53+def get_best_encoding(stream: t.IO) -> str:54 """Returns the default stream encoding if not found."""55 rv = getattr(stream, "encoding", None) or sys.getdefaultencoding()56 if is_ascii_encoding(rv):57 return "utf-8"2 unmodified lines60 61 class _NonClosingTextIOWrapper(io.TextIOWrapper):62 def __init__(63 self,60- stream,61- encoding,62- errors,63- force_readable=False,64- force_writable=False,65- **extra,66- ):67- self._stream = stream = _FixupStream(stream, force_readable, force_writable)64+ stream: t.BinaryIO,65+ encoding: t.Optional[str],66+ errors: t.Optional[str],67+ force_readable: bool = False,68+ force_writable: bool = False,69+ **extra: t.Any,70+ ) -> None:71+ self._stream = stream = t.cast(72+ t.BinaryIO, _FixupStream(stream, force_readable, force_writable)73+ )74 super().__init__(stream, encoding, errors, **extra)75 70- def __del__(self):76+ def __del__(self) -> None:77 try:78 self.detach()79 except Exception:80 pass81 76- def isatty(self):82+ def isatty(self) -> bool:83 # https://bitbucket.org/pypy/pypy/issue/180384 return self._stream.isatty()85 86 6 unmodified lines93 put badly patched objects on sys (one such offender are certain version94 of jupyter notebook).95 """96 91- def __init__(self, stream, force_readable=False, force_writable=False):97+ def __init__(98+ self,99+ stream: t.BinaryIO,100+ force_readable: bool = False,101+ force_writable: bool = False,102+ ):103 self._stream = stream104 self._force_readable = force_readable105 self._force_writable = force_writable106 96- def __getattr__(self, name):107+ def __getattr__(self, name: str) -> t.Any:108 return getattr(self._stream, name)109 99- def read1(self, size):110+ def read1(self, size: int) -> bytes:111 f = getattr(self._stream, "read1", None)112+113 if f is not None:102- return f(size)114+ return t.cast(bytes, f(size))115 116 return self._stream.read(size)117 106- def readable(self):118+ def readable(self) -> bool:119 if self._force_readable:120 return True121 x = getattr(self._stream, "readable", None)122 if x is not None:111- return x()123+ return t.cast(bool, x())124 try:125 self._stream.read(0)126 except Exception:127 return False128 return True129 118- def writable(self):130+ def writable(self) -> bool:131 if self._force_writable:132 return True133 x = getattr(self._stream, "writable", None)134 if x is not None:123- return x()135+ return t.cast(bool, x())136 try:125- self._stream.write("")137+ self._stream.write("") # type: ignore138 except Exception:139 try:140 self._stream.write(b"")141 except Exception:142 return False143 return True144 133- def seekable(self):145+ def seekable(self) -> bool:146 x = getattr(self._stream, "seekable", None)147 if x is not None:136- return x()148+ return t.cast(bool, x())149 try:150 self._stream.seek(self._stream.tell())151 except Exception:152 return False153 return True154 155 144-def is_bytes(x):145- return isinstance(x, (bytes, memoryview, bytearray))146-147-148-def _is_binary_reader(stream, default=False):156+def _is_binary_reader(stream: t.IO, default: bool = False) -> bool:157 try:158 return isinstance(stream.read(0), bytes)159 except Exception:160 return default161 # This happens in some cases where the stream was already162 # closed. In this case, we assume the default.163 164 157-def _is_binary_writer(stream, default=False):165+def _is_binary_writer(stream: t.IO, default: bool = False) -> bool:166 try:167 stream.write(b"")168 except Exception:169 try:4 unmodified lines174 return default175 return True176 177 170-def _find_binary_reader(stream):178+def _find_binary_reader(stream: t.IO) -> t.Optional[t.BinaryIO]:179 # We need to figure out if the given stream is already binary.180 # This can happen because the official docs recommend detaching181 # the streams to get binary streams. Some code might do this, so182 # we need to deal with this case explicitly.183 if _is_binary_reader(stream, False):176- return stream184+ return t.cast(t.BinaryIO, stream)185 186 buf = getattr(stream, "buffer", None)187 188 # Same situation here; this time we assume that the buffer is189 # actually binary in case it's closed.190 if buf is not None and _is_binary_reader(buf, True):183- return buf191+ return t.cast(t.BinaryIO, buf)192 193+ return None194 186-def _find_binary_writer(stream):195+196+def _find_binary_writer(stream: t.IO) -> t.Optional[t.BinaryIO]:197 # We need to figure out if the given stream is already binary.198 # This can happen because the official docs recommend detaching199 # the streams to get binary streams. Some code might do this, so200 # we need to deal with this case explicitly.201 if _is_binary_writer(stream, False):192- return stream202+ return t.cast(t.BinaryIO, stream)203 204 buf = getattr(stream, "buffer", None)205 206 # Same situation here; this time we assume that the buffer is207 # actually binary in case it's closed.208 if buf is not None and _is_binary_writer(buf, True):199- return buf209+ return t.cast(t.BinaryIO, buf)210 211+ return None212 213+202-def _stream_is_misconfigured(stream):214+def _stream_is_misconfigured(stream: t.TextIO) -> bool:215 """A stream is misconfigured if its encoding is ASCII."""216 # If the stream does not have an encoding set, we assume it's set217 # to ASCII. This appears to happen in certain unittest218 # environments. It's not quite clear what the correct behavior is219 # but this at least will force Click to recover somehow.220 return is_ascii_encoding(getattr(stream, "encoding", None) or "ascii")221 222 211-def _is_compat_stream_attr(stream, attr, value):223+def _is_compat_stream_attr(stream: t.TextIO, attr: str, value: t.Optional[str]) -> bool:224 """A stream attribute is compatible if it is equal to the225 desired value or the desired value is unset and the attribute226 has a value.227 """228 stream_value = getattr(stream, attr, None)229 return stream_value == value or (value is None and stream_value is not None)230 231 220-def _is_compatible_text_stream(stream, encoding, errors):232+def _is_compatible_text_stream(233+ stream: t.TextIO, encoding: t.Optional[str], errors: t.Optional[str]234+) -> bool:235 """Check if a stream's encoding and errors attributes are236 compatible with the desired values.237 """238 return _is_compat_stream_attr(1 unmodified line240 ) and _is_compat_stream_attr(stream, "errors", errors)241 242 243 def _force_correct_text_stream(230- text_stream,231- encoding,232- errors,233- is_binary,234- find_binary,235- force_readable=False,236- force_writable=False,237-):244+ text_stream: t.IO,245+ encoding: t.Optional[str],246+ errors: t.Optional[str],247+ is_binary: t.Callable[[t.IO, bool], bool],248+ find_binary: t.Callable[[t.IO], t.Optional[t.BinaryIO]],249+ force_readable: bool = False,250+ force_writable: bool = False,251+) -> t.TextIO:252 if is_binary(text_stream, False):239- binary_reader = text_stream253+ binary_reader = t.cast(t.BinaryIO, text_stream)254 else:255+ text_stream = t.cast(t.TextIO, text_stream)256 # If the stream looks compatible, and won't default to a257 # misconfigured ascii encoding, return it as-is.258 if _is_compatible_text_stream(text_stream, encoding, errors) and not (259 encoding is None and _stream_is_misconfigured(text_stream)260 ):261 return text_stream262 263 # Otherwise, get the underlying binary reader.249- binary_reader = find_binary(text_stream)264+ possible_binary_reader = find_binary(text_stream)265 266 # If that's not possible, silently use the original reader267 # and get mojibake instead of exceptions.253- if binary_reader is None:268+ if possible_binary_reader is None:269 return text_stream270 271+ binary_reader = possible_binary_reader272+273 # Default errors to replace instead of strict in order to get274 # something that works.275 if errors is None:276 errors = "replace"8 unmodified lines285 force_writable=force_writable,286 )287 288 272-def _force_correct_text_reader(text_reader, encoding, errors, force_readable=False):289+def _force_correct_text_reader(290+ text_reader: t.IO,291+ encoding: t.Optional[str],292+ errors: t.Optional[str],293+ force_readable: bool = False,294+) -> t.TextIO:295 return _force_correct_text_stream(296 text_reader,297 encoding,298 errors,2 unmodified lines301 force_readable=force_readable,302 )303 304 283-def _force_correct_text_writer(text_writer, encoding, errors, force_writable=False):305+def _force_correct_text_writer(306+ text_writer: t.IO,307+ encoding: t.Optional[str],308+ errors: t.Optional[str],309+ force_writable: bool = False,310+) -> t.TextIO:311 return _force_correct_text_stream(312 text_writer,313 encoding,314 errors,2 unmodified lines317 force_writable=force_writable,318 )319 320 294-def get_binary_stdin():321+def get_binary_stdin() -> t.BinaryIO:322 reader = _find_binary_reader(sys.stdin)323 if reader is None:324 raise RuntimeError("Was not able to determine binary stream for sys.stdin.")325 return reader326 327 301-def get_binary_stdout():328+def get_binary_stdout() -> t.BinaryIO:329 writer = _find_binary_writer(sys.stdout)330 if writer is None:331 raise RuntimeError("Was not able to determine binary stream for sys.stdout.")332 return writer333 334 308-def get_binary_stderr():335+def get_binary_stderr() -> t.BinaryIO:336 writer = _find_binary_writer(sys.stderr)337 if writer is None:338 raise RuntimeError("Was not able to determine binary stream for sys.stderr.")339 return writer340 341 315-def get_text_stdin(encoding=None, errors=None):342+def get_text_stdin(343+ encoding: t.Optional[str] = None, errors: t.Optional[str] = None344+) -> t.TextIO:345 rv = _get_windows_console_stream(sys.stdin, encoding, errors)346 if rv is not None:347 return rv348 return _force_correct_text_reader(sys.stdin, encoding, errors, force_readable=True)349 350 322-def get_text_stdout(encoding=None, errors=None):351+def get_text_stdout(352+ encoding: t.Optional[str] = None, errors: t.Optional[str] = None353+) -> t.TextIO:354 rv = _get_windows_console_stream(sys.stdout, encoding, errors)355 if rv is not None:356 return rv357 return _force_correct_text_writer(sys.stdout, encoding, errors, force_writable=True)358 359 329-def get_text_stderr(encoding=None, errors=None):360+def get_text_stderr(361+ encoding: t.Optional[str] = None, errors: t.Optional[str] = None362+) -> t.TextIO:363 rv = _get_windows_console_stream(sys.stderr, encoding, errors)364 if rv is not None:365 return rv366 return _force_correct_text_writer(sys.stderr, encoding, errors, force_writable=True)367 368 336-def get_strerror(e, default=None):369+def get_strerror(e: OSError, default: t.Optional[str] = None) -> str:370 if hasattr(e, "strerror"):371 msg = e.strerror372 else:373 if default is not None:374 msg = default375 else:376 msg = str(e)344- if isinstance(msg, bytes):345- msg = msg.decode("utf-8", "replace")377 return msg378 379 349-def _wrap_io_open(file, mode, encoding, errors):380+def _wrap_io_open(381+ file: t.Union[str, os.PathLike, int],382+ mode: str,383+ encoding: t.Optional[str],384+ errors: t.Optional[str],385+) -> t.IO:386 """Handles not passing ``encoding`` and ``errors`` in binary mode."""387 if "b" in mode:388 return open(file, mode)389 390 return open(file, mode, encoding=encoding, errors=errors)391 392 357-def open_stream(filename, mode="r", encoding=None, errors="strict", atomic=False):393+def open_stream(394+ filename: str,395+ mode: str = "r",396+ encoding: t.Optional[str] = None,397+ errors: t.Optional[str] = "strict",398+ atomic: bool = False,399+) -> t.Tuple[t.IO, bool]:400 binary = "b" in mode401 402 # Standard streams first. These are simple because they don't need403 # special handling for the atomic flag. It's entirely ignored.30 unmodified lines434 import errno435 import random436 437 try:396- perm = os.stat(filename).st_mode438+ perm: t.Optional[int] = os.stat(filename).st_mode439 except OSError:440 perm = None441 442 flags = os.O_RDWR | os.O_CREAT | os.O_EXCL22 unmodified lines465 if perm is not None:466 os.chmod(tmp_filename, perm) # in case perm includes bits in umask467 468 f = _wrap_io_open(fd, mode, encoding, errors)427- return _AtomicFile(f, tmp_filename, os.path.realpath(filename)), True469+ af = _AtomicFile(f, tmp_filename, os.path.realpath(filename))470+ return t.cast(t.IO, af), True471 472 473 class _AtomicFile:431- def __init__(self, f, tmp_filename, real_filename):474+ def __init__(self, f: t.IO, tmp_filename: str, real_filename: str) -> None:475 self._f = f476 self._tmp_filename = tmp_filename477 self._real_filename = real_filename478 self.closed = False479 480 @property438- def name(self):481+ def name(self) -> str:482 return self._real_filename483 441- def close(self, delete=False):484+ def close(self, delete: bool = False) -> None:485 if self.closed:486 return487 self._f.close()488 os.replace(self._tmp_filename, self._real_filename)489 self.closed = True490 448- def __getattr__(self, name):491+ def __getattr__(self, name: str) -> t.Any:492 return getattr(self._f, name)493 451- def __enter__(self):494+ def __enter__(self) -> "_AtomicFile":495 return self496 454- def __exit__(self, exc_type, exc_value, tb):497+ def __exit__(self, exc_type, exc_value, tb): # type: ignore498 self.close(delete=exc_type is not None)499 457- def __repr__(self):500+ def __repr__(self) -> str:501 return repr(self._f)502 503 461-def strip_ansi(value):504+def strip_ansi(value: str) -> str:505 return _ansi_re.sub("", value)506 507 465-def _is_jupyter_kernel_output(stream):508+def _is_jupyter_kernel_output(stream: t.IO) -> bool:509 while isinstance(stream, (_FixupStream, _NonClosingTextIOWrapper)):510 stream = stream._stream511 512 return stream.__class__.__module__.startswith("ipykernel.")513 514 472-def should_strip_ansi(stream=None, color=None):515+def should_strip_ansi(516+ stream: t.Optional[t.IO] = None, color: t.Optional[bool] = None517+) -> bool:518 if color is None:519 if stream is None:520 stream = sys.stdin521 return not isatty(stream) and not _is_jupyter_kernel_output(stream)5 unmodified lines527 # NOTE: double check is needed so mypy does not analyze this on Linux528 if sys.platform.startswith("win") and WIN:529 from ._winconsole import _get_windows_console_stream530 486- def _get_argv_encoding():531+ def _get_argv_encoding() -> str:532 import locale533 534 return locale.getpreferredencoding()535 38 unmodified lines574 575 576 else:577 533- def _get_argv_encoding():578+ def _get_argv_encoding() -> str:579 return getattr(sys.stdin, "encoding", None) or get_filesystem_encoding()580 536- def _get_windows_console_stream(f, encoding, errors):581+ def _get_windows_console_stream(582+ f: t.TextIO, encoding: t.Optional[str], errors: t.Optional[str]583+ ) -> t.Optional[t.TextIO]:584 return None585 586 540-def term_len(x):587+def term_len(x: str) -> int:588 return len(strip_ansi(x))589 590 544-def isatty(stream):591+def isatty(stream: t.IO) -> bool:592 try:593 return stream.isatty()594 except Exception:595 return False596 597 551-def _make_cached_stream_func(src_func, wrapper_func):552- cache = WeakKeyDictionary()598+def _make_cached_stream_func(599+ src_func: t.Callable[[], t.TextIO], wrapper_func: t.Callable[[], t.TextIO]600+) -> t.Callable[[], t.TextIO]:601+ cache: t.MutableMapping[t.TextIO, t.TextIO] = WeakKeyDictionary()602 554- def func():603+ def func() -> t.TextIO:604 stream = src_func()605 try:606 rv = cache.get(stream)607 except Exception:15 unmodified lines623 _default_text_stdout = _make_cached_stream_func(lambda: sys.stdout, get_text_stdout)624 _default_text_stderr = _make_cached_stream_func(lambda: sys.stderr, get_text_stderr)625 626 578-binary_streams = {627+binary_streams: t.Mapping[str, t.Callable[[], t.BinaryIO]] = {628 "stdin": get_binary_stdin,629 "stdout": get_binary_stdout,630 "stderr": get_binary_stderr,631 }632 584-text_streams = {633+text_streams: t.Mapping[634+ str, t.Callable[[t.Optional[str], t.Optional[str]], t.TextIO]635+] = {636 "stdin": get_text_stdin,637 "stdout": get_text_stdout,638 "stderr": get_text_stderr,639 }modified:src/click/_termui_impl.py+126 added-110 removed
6 unmodified lines7 import math8 import os9 import sys10 import time11+import typing as t12 from gettext import gettext as _13 14 from ._compat import _default_text_stdout15 from ._compat import CYGWIN5 unmodified lines21 from ._compat import WIN22 from .exceptions import ClickException23 from .utils import echo24 25+V = t.TypeVar("V")26+27 if os.name == "nt":28 BEFORE_BAR = "\r"29 AFTER_BAR = "\n"30 else:31 BEFORE_BAR = "\r\033[?25l"32 AFTER_BAR = "\033[?25h\n"33 34 32-def _length_hint(obj):33- """Returns the length hint of an object."""34- try:35- return len(obj)36- except (AttributeError, TypeError):37- try:38- get_hint = type(obj).__length_hint__39- except AttributeError:40- return None41- try:42- hint = get_hint(obj)43- except TypeError:44- return None45- if hint is NotImplemented or not isinstance(hint, int) or hint < 0:46- return None47- return hint48-49-35 class ProgressBar:36 def __init__(37 self,53- iterable,54- length=None,55- fill_char="#",56- empty_char=" ",57- bar_template="%(bar)s",58- info_sep=" ",59- show_eta=True,60- show_percent=None,61- show_pos=False,62- item_show_func=None,63- label=None,64- file=None,65- color=None,66- update_min_steps=1,67- width=30,38+ iterable: t.Optional[t.Iterable[V]],39+ length: t.Optional[int] = None,40+ fill_char: str = "#",41+ empty_char: str = " ",42+ bar_template: str = "%(bar)s",43+ info_sep: str = " ",44+ show_eta: bool = True,45+ show_percent: t.Optional[bool] = None,46+ show_pos: bool = False,47+ item_show_func: t.Optional[t.Callable[[t.Optional[V]], t.Optional[str]]] = None,48+ label: t.Optional[str] = None,49+ file: t.Optional[t.TextIO] = None,50+ color: t.Optional[bool] = None,51+ update_min_steps: int = 1,52+ width: int = 30,53 ):54 self.fill_char = fill_char55 self.empty_char = empty_char56 self.bar_template = bar_template12 unmodified lines69 self.width = width70 self.autowidth = width == 071 72 if length is None:88- length = _length_hint(iterable)73+ from operator import length_hint74+75+ length = length_hint(iterable, -1)76+77+ if length == -1:78+ length = None79 if iterable is None:80 if length is None:81 raise TypeError("iterable or length is required")92- iterable = range(length)82+ iterable = t.cast(t.Iterable[V], range(length))83 self.iter = iter(iterable)84 self.length = length95- self.length_known = length is not None85 self.pos = 097- self.avg = []86+ self.avg: t.List[float] = []87 self.start = self.last_eta = time.time()88 self.eta_known = False89 self.finished = False101- self.max_width = None90+ self.max_width: t.Optional[int] = None91 self.entered = False103- self.current_item = None92+ self.current_item: t.Optional[V] = None93 self.is_hidden = not isatty(self.file)105- self._last_line = None94+ self._last_line: t.Optional[str] = None95 107- def __enter__(self):96+ def __enter__(self) -> "ProgressBar":97 self.entered = True98 self.render_progress()99 return self100 112- def __exit__(self, exc_type, exc_value, tb):101+ def __exit__(self, exc_type, exc_value, tb): # type: ignore102 self.render_finish()103 115- def __iter__(self):104+ def __iter__(self) -> t.Iterable[V]:105 if not self.entered:106 raise RuntimeError("You need to use progress bars in a with block.")107 self.render_progress()108 return self.generator()109 121- def __next__(self):110+ def __next__(self) -> V:111 # Iteration is defined in terms of a generator function,112 # returned by iter(self); use that to define next(). This works113 # because `self.iter` is an iterable consumed by that generator,114 # so it is re-entry safe. Calling `next(self.generator())`115 # twice works and does "what you want".127- return next(iter(self))116+ return next(iter(self)) # type: ignore117 129- def render_finish(self):118+ def render_finish(self) -> None:119 if self.is_hidden:120 return121 self.file.write(AFTER_BAR)122 self.file.flush()123 124 @property136- def pct(self):125+ def pct(self) -> float:126 if self.finished:127 return 1.0139- return min(self.pos / (float(self.length) or 1), 1.0)128+ return min(self.pos / (float(self.length or 1) or 1), 1.0)129 130 @property142- def time_per_iteration(self):131+ def time_per_iteration(self) -> float:132 if not self.avg:133 return 0.0134 return sum(self.avg) / float(len(self.avg))135 136 @property148- def eta(self):149- if self.length_known and not self.finished:137+ def eta(self) -> float:138+ if self.length is not None and not self.finished:139 return self.time_per_iteration * (self.length - self.pos)140 return 0.0141 153- def format_eta(self):142+ def format_eta(self) -> str:143 if self.eta_known:144 t = int(self.eta)145 seconds = t % 60146 t //= 606 unmodified lines153 else:154 return f"{hours:02}:{minutes:02}:{seconds:02}"155 return ""156 168- def format_pos(self):157+ def format_pos(self) -> str:158 pos = str(self.pos)170- if self.length_known:159+ if self.length is not None:160 pos += f"/{self.length}"161 return pos162 174- def format_pct(self):163+ def format_pct(self) -> str:164 return f"{int(self.pct * 100): 4}%"[1:]165 177- def format_bar(self):178- if self.length_known:166+ def format_bar(self) -> str:167+ if self.length is not None:168 bar_length = int(self.pct * self.width)169 bar = self.fill_char * bar_length170 bar += self.empty_char * (self.width - bar_length)171 elif self.finished:172 bar = self.fill_char * self.width173 else:185- bar = list(self.empty_char * (self.width or 1))174+ chars = list(self.empty_char * (self.width or 1))175 if self.time_per_iteration != 0:187- bar[176+ chars[177 int(178 (math.cos(self.pos * self.time_per_iteration) / 2.0 + 0.5)179 * self.width180 )181 ] = self.fill_char193- bar = "".join(bar)182+ bar = "".join(chars)183 return bar184 196- def format_progress_line(self):185+ def format_progress_line(self) -> str:186 show_percent = self.show_percent187 188 info_bits = []200- if self.length_known and show_percent is None:189+ if self.length is not None and show_percent is None:190 show_percent = not self.show_pos191 192 if self.show_pos:193 info_bits.append(self.format_pos())14 unmodified lines208 "info": self.info_sep.join(info_bits),209 }210 ).rstrip()211 223- def render_progress(self):212+ def render_progress(self) -> None:213 import shutil214 215 if self.is_hidden:216 # Only output the label as it changes if the output is not a12 unmodified lines229 clutter_length = term_len(self.format_progress_line())230 new_width = max(0, shutil.get_terminal_size().columns - clutter_length)231 if new_width < old_width:232 buf.append(BEFORE_BAR)244- buf.append(" " * self.max_width)233+ buf.append(" " * self.max_width) # type: ignore234 self.max_width = new_width235 self.width = new_width236 237 clear_width = self.width15 unmodified lines253 self._last_line = line254 echo(line, file=self.file, color=self.color, nl=False)255 self.file.flush()256 268- def make_step(self, n_steps):257+ def make_step(self, n_steps: int) -> None:258 self.pos += n_steps270- if self.length_known and self.pos >= self.length:259+ if self.length is not None and self.pos >= self.length:260 self.finished = True261 262 if (time.time() - self.last_eta) < 1.0:263 return9 unmodified lines273 step = time.time() - self.start274 275 self.avg = self.avg[-6:] + [step]276 288- self.eta_known = self.length_known277+ self.eta_known = self.length is not None278 290- def update(self, n_steps, current_item=None):279+ def update(self, n_steps: int, current_item: t.Optional[V] = None) -> None:280 """Update the progress bar by advancing a specified number of281 steps, and optionally set the ``current_item`` for this new282 position.283 17 unmodified lines301 self.make_step(self._completed_intervals)302 self.render_progress()303 self._completed_intervals = 0304 316- def finish(self):317- self.eta_known = 0305+ def finish(self) -> None:306+ self.eta_known = False307 self.current_item = None308 self.finished = True309 321- def generator(self):310+ def generator(self) -> t.Iterator[V]:311 """Return a generator which yields the items added to the bar312 during construction, and updates the progress bar *after* the313 yielded block returns.314 """25 unmodified lines340 self.finish()341 self.render_progress()342 343 355-def pager(generator, color=None):344+def pager(generator: t.Iterable[str], color: t.Optional[bool] = None) -> None:345 """Decide what method to use for paging through text."""346 stdout = _default_text_stdout()347 if not isatty(sys.stdin) or not isatty(stdout):348 return _nullpager(stdout, generator, color)20 unmodified lines369 finally:370 os.unlink(filename)371 372 384-def _pipepager(generator, cmd, color):373+def _pipepager(generator: t.Iterable[str], cmd: str, color: t.Optional[bool]) -> None:374 """Page through text by feeding it to another program. Invoking a375 pager through this might support colors.376 """377 import subprocess11 unmodified lines389 elif "r" in less_flags or "R" in less_flags:390 color = True391 392 c = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, env=env)393+ stdin = t.cast(t.BinaryIO, c.stdin)404- encoding = get_best_encoding(c.stdin)394+ encoding = get_best_encoding(stdin)395 try:396 for text in generator:397 if not color:398 text = strip_ansi(text)399 410- c.stdin.write(text.encode(encoding, "replace"))400+ stdin.write(text.encode(encoding, "replace"))401 except (OSError, KeyboardInterrupt):402 pass403 else:414- c.stdin.close()404+ stdin.close()405 406 # Less doesn't respect ^C, but catches it for its own UI purposes (aborting407 # search or other commands inside less).408 #10 unmodified lines419 else:420 break421 422 433-def _tempfilepager(generator, cmd, color):423+def _tempfilepager(424+ generator: t.Iterable[str], cmd: str, color: t.Optional[bool]425+) -> None:426 """Page through text by invoking a program on a temporary file."""427 import tempfile428 437- filename = tempfile.mkstemp()429+ _, filename = tempfile.mkstemp()430 # TODO: This never terminates if the passed generator never terminates.431 text = "".join(generator)432 if not color:433 text = strip_ansi(text)5 unmodified lines439 finally:440 os.unlink(filename)441 442 451-def _nullpager(stream, generator, color):443+def _nullpager(444+ stream: t.TextIO, generator: t.Iterable[str], color: t.Optional[bool]445+) -> None:446 """Simply print unformatted text. This is the ultimate fallback."""447 for text in generator:448 if not color:449 text = strip_ansi(text)450 stream.write(text)451 452 453 class Editor:460- def __init__(self, editor=None, env=None, require_save=True, extension=".txt"):454+ def __init__(455+ self,456+ editor: t.Optional[str] = None,457+ env: t.Optional[t.Mapping[str, str]] = None,458+ require_save: bool = True,459+ extension: str = ".txt",460+ ) -> None:461 self.editor = editor462 self.env = env463 self.require_save = require_save464 self.extension = extension465 466- def get_editor(self):466+ def get_editor(self) -> str:467 if self.editor is not None:468 return self.editor469 for key in "VISUAL", "EDITOR":470 rv = os.environ.get(key)5 unmodified lines476 if os.system(f"which {editor} >/dev/null 2>&1") == 0:477 return editor478 return "vi"479 480- def edit_file(self, filename):480+ def edit_file(self, filename: str) -> None:481 import subprocess482 483 editor = self.get_editor()484+ environ: t.Optional[t.Dict[str, str]] = None485+486 if self.env:487 environ = os.environ.copy()488 environ.update(self.env)487- else:488- environ = None489+490 try:491 c = subprocess.Popen(f'{editor} "{filename}"', env=environ, shell=True)492 exit_code = c.wait()493 if exit_code != 0:4 unmodified lines498 raise ClickException(499 _("{editor}: Editing failed: {e}").format(editor=editor, e=e)500 )501 501- def edit(self, text):502+ def edit(self, text: t.Optional[t.AnyStr]) -> t.Optional[t.AnyStr]:503 import tempfile504 505 if not text:505- text = ""506-507- is_bytes = isinstance(text, (bytes, bytearray))508-509- if not is_bytes:506+ data = b""507+ elif isinstance(text, (bytes, bytearray)):508+ data = text509+ else:510 if text and not text.endswith("\n"):511 text += "\n"512 513 if WIN:514- text = text.replace("\n", "\r\n").encode("utf-8-sig")514+ data = text.replace("\n", "\r\n").encode("utf-8-sig")515 else:516- text = text.encode("utf-8")516+ data = text.encode("utf-8")517 518 fd, name = tempfile.mkstemp(prefix="editor-", suffix=self.extension)519+ f: t.BinaryIO520 521 try:522 with os.fdopen(fd, "wb") as f:522- f.write(text)523+ f.write(data)524 525 # If the filesystem resolution is 1 second, like Mac OS526 # 10.12 Extended, or 2 seconds, like FAT32, and the editor527 # closes very fast, require_save can fail. Set the modified10 unmodified lines538 539 with open(name, "rb") as f:540 rv = f.read()541 541- if is_bytes:542+ if isinstance(text, (bytes, bytearray)):543 return rv544 544- return rv.decode("utf-8-sig").replace("\r\n", "\n")545+ return rv.decode("utf-8-sig").replace("\r\n", "\n") # type: ignore546 finally:547 os.unlink(name)548 549 549-def open_url(url, wait=False, locate=False):550+def open_url(url: str, wait: bool = False, locate: bool = False) -> int:551 import subprocess552 553 def _unquote_file(url: str) -> str:554 from urllib.parse import unquote20 unmodified lines575 url = _unquote_file(url.replace('"', ""))576 args = f'explorer /select,"{url}"'577 else:578 url = url.replace('"', "")578- wait = "/WAIT" if wait else ""579- args = f'start {wait} "" "{url}"'579+ wait_str = "/WAIT" if wait else ""580+ args = f'start {wait_str} "" "{url}"'581 return os.system(args)582 elif CYGWIN:583 if locate:584 url = os.path.dirname(_unquote_file(url).replace('"', ""))585 args = f'cygstart "{url}"'586 else:587 url = url.replace('"', "")587- wait = "-w" if wait else ""588- args = f'cygstart {wait} "{url}"'588+ wait_str = "-w" if wait else ""589+ args = f'cygstart {wait_str} "{url}"'590 return os.system(args)591 592 try:593 if locate:12 unmodified lines606 return 0607 return 1608 609 609-def _translate_ch_to_exc(ch):610+def _translate_ch_to_exc(ch: str) -> t.Optional[BaseException]:611 if ch == "\x03":612 raise KeyboardInterrupt()613+614 if ch == "\x04" and not WIN: # Unix-like, Ctrl+D615 raise EOFError()616+617 if ch == "\x1a" and WIN: # Windows, Ctrl+Z618 raise EOFError()619 620+ return None621 622+623 if WIN:624 import msvcrt625 626 @contextlib.contextmanager622- def raw_terminal():623- yield627+ def raw_terminal() -> t.Iterator[int]:628+ yield -1629 625- def getchar(echo):630+ def getchar(echo: bool) -> str:631 # The function `getch` will return a bytes object corresponding to632 # the pressed character. Since Windows 10 build 1803, it will also633 # return \x00 when called a second time after pressing a regular key.634 #21 unmodified lines656 # limited to the current 8-bit codepage.657 #658 # Anyway, Click doesn't claim to do this Right(tm), and using `getwch`659 # is doing the right thing in more situations than with `getch`.660+ func: t.Callable[[], str]661+662 if echo:656- func = msvcrt.getwche663+ func = msvcrt.getwche # type: ignore664 else:658- func = msvcrt.getwch665+ func = msvcrt.getwch # type: ignore666 667 rv = func()668+669 if rv in ("\x00", "\xe0"):670 # \x00 and \xe0 are control characters that indicate special key,671 # see above.672 rv += func()673+674 _translate_ch_to_exc(rv)675 return rv676 677 1 unmodified line679 import tty680 import termios681 682 @contextlib.contextmanager674- def raw_terminal():683+ def raw_terminal() -> t.Iterator[int]:684+ f: t.Optional[t.TextIO]685+ fd: int686+687 if not isatty(sys.stdin):688 f = open("/dev/tty")689 fd = f.fileno()690 else:691 fd = sys.stdin.fileno()692 f = None693+694 try:695 old_settings = termios.tcgetattr(fd)696+697 try:698 tty.setraw(fd)699 yield fd700 finally:701 termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)702 sys.stdout.flush()703+704 if f is not None:705 f.close()706 except termios.error:707 pass708 694- def getchar(echo):709+ def getchar(echo: bool) -> str:710 with raw_terminal() as fd:696- ch = os.read(fd, 32)697- ch = ch.decode(get_best_encoding(sys.stdin), "replace")711+ ch = os.read(fd, 32).decode(get_best_encoding(sys.stdin), "replace")712+713 if echo and isatty(sys.stdout):714 sys.stdout.write(ch)715+716 _translate_ch_to_exc(ch)717 return chmodified:src/click/_textwrap.py+15 added-3 removed
1 import textwrap2+import typing as t3 from contextlib import contextmanager4 5 6 class TextWrapper(textwrap.TextWrapper):6- def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width):7+ def _handle_long_word(8+ self,9+ reversed_chunks: t.List[str],10+ cur_line: t.List[str],11+ cur_len: int,12+ width: int,13+ ) -> None:14 space_left = max(width - cur_len, 1)15 16 if self.break_long_words:17 last = reversed_chunks[-1]4 unmodified lines22 elif not cur_line:23 cur_line.append(reversed_chunks.pop())24 25 @contextmanager19- def extra_indent(self, indent):26+ def extra_indent(self, indent: str) -> t.Iterator[None]:27 old_initial_indent = self.initial_indent28 old_subsequent_indent = self.subsequent_indent29 self.initial_indent += indent30 self.subsequent_indent += indent31+32 try:33 yield34 finally:35 self.initial_indent = old_initial_indent36 self.subsequent_indent = old_subsequent_indent37 30- def indent_only(self, text):38+ def indent_only(self, text: str) -> str:39 rv = []40+41 for idx, line in enumerate(text.splitlines()):42 indent = self.initial_indent43+44 if idx > 0:45 indent = self.subsequent_indent46+47 rv.append(f"{indent}{line}")48+49 return "\n".join(rv)modified:src/click/_unicodefun.py+20 added-13 removed
1 unmodified line2 import os3 from gettext import gettext as _4 5 6-def _verify_python_env():6+def _verify_python_env() -> None:7 """Ensures that the environment is good for Unicode."""8 try:9- import locale9+ from locale import getpreferredencoding10 11- fs_enc = codecs.lookup(locale.getpreferredencoding()).name11+ fs_enc = codecs.lookup(getpreferredencoding()).name12 except Exception:13 fs_enc = "ascii"14+15 if fs_enc != "ascii":16 return17 18 extra = [9 unmodified lines28 import subprocess29 30 try:31 rv = subprocess.Popen(31- ["locale", "-a"], stdout=subprocess.PIPE, stderr=subprocess.PIPE32+ ["locale", "-a"],33+ stdout=subprocess.PIPE,34+ stderr=subprocess.PIPE,35+ encoding="ascii",36+ errors="replace",37 ).communicate()[0]38 except OSError:34- rv = b""39+ rv = ""40+41 good_locales = set()42 has_c_utf8 = False43 38- # Make sure we're operating on text here.39- if isinstance(rv, bytes):40- rv = rv.decode("ascii", "replace")41-44 for line in rv.splitlines():45 locale = line.strip()46+47 if locale.lower().endswith((".utf-8", ".utf8")):48 good_locales.add(locale)49+50 if locale.lower() in ("c.utf8", "c.utf-8"):51 has_c_utf8 = True52 53 if not good_locales:24 unmodified lines78 ).format(locales=", ".join(sorted(good_locales)))79 )80 81 bad_locale = None82+78- for locale in os.environ.get("LC_ALL"), os.environ.get("LANG"):79- if locale and locale.lower().endswith((".utf-8", ".utf8")):80- bad_locale = locale81- if locale is not None:83+ for env_locale in os.environ.get("LC_ALL"), os.environ.get("LANG"):84+ if env_locale and env_locale.lower().endswith((".utf-8", ".utf8")):85+ bad_locale = env_locale86+87+ if env_locale is not None:88 break89+90 if bad_locale is not None:91 extra.append(92 _(93 "Click discovered that you exported a UTF-8 locale"7 unmodified linesmodified:src/click/_winconsole.py+21 added-18 removed
7 unmodified lines8 # echo and prompt.9 import io10 import sys11 import time12+import typing as t13 from ctypes import byref14 from ctypes import c_char15 from ctypes import c_char_p16 from ctypes import c_int161 unmodified lines178 return bytes_written179 180 181 class ConsoleStream:181- def __init__(self, text_stream, byte_stream):182+ def __init__(self, text_stream: t.TextIO, byte_stream: t.BinaryIO) -> None:183 self._text_stream = text_stream184 self.buffer = byte_stream185 186 @property186- def name(self):187+ def name(self) -> str:188 return self.buffer.name189 189- def write(self, x):190+ def write(self, x: t.AnyStr) -> int:191 if isinstance(x, str):192 return self._text_stream.write(x)193 try:194 self.flush()195 except Exception:196 pass197 return self.buffer.write(x)198 198- def writelines(self, lines):199+ def writelines(self, lines: t.Iterable[t.AnyStr]) -> None:200 for line in lines:201 self.write(line)202 202- def __getattr__(self, name):203+ def __getattr__(self, name: str) -> t.Any:204 return getattr(self._text_stream, name)205 205- def isatty(self):206+ def isatty(self) -> bool:207 return self.buffer.isatty()208 209 def __repr__(self):210 return f"<ConsoleStream name={self.name!r} encoding={self.encoding!r}>"23 unmodified lines234 self.__wrapped.write(text[written : written + to_write])235 written += to_write236 237 237-def _get_text_stdin(buffer_stream):238+def _get_text_stdin(buffer_stream: t.BinaryIO) -> t.TextIO:239 text_stream = _NonClosingTextIOWrapper(240 io.BufferedReader(_WindowsConsoleReader(STDIN_HANDLE)),241 "utf-16-le",242 "strict",243 line_buffering=True,244 )244- return ConsoleStream(text_stream, buffer_stream)245+ return t.cast(t.TextIO, ConsoleStream(text_stream, buffer_stream))246 247 247-def _get_text_stdout(buffer_stream):248+def _get_text_stdout(buffer_stream: t.BinaryIO) -> t.TextIO:249 text_stream = _NonClosingTextIOWrapper(250 io.BufferedWriter(_WindowsConsoleWriter(STDOUT_HANDLE)),251 "utf-16-le",252 "strict",253 line_buffering=True,254 )254- return ConsoleStream(text_stream, buffer_stream)255+ return t.cast(t.TextIO, ConsoleStream(text_stream, buffer_stream))256 257 257-def _get_text_stderr(buffer_stream):258+def _get_text_stderr(buffer_stream: t.BinaryIO) -> t.TextIO:259 text_stream = _NonClosingTextIOWrapper(260 io.BufferedWriter(_WindowsConsoleWriter(STDERR_HANDLE)),261 "utf-16-le",262 "strict",263 line_buffering=True,264 )264- return ConsoleStream(text_stream, buffer_stream)265+ return t.cast(t.TextIO, ConsoleStream(text_stream, buffer_stream))266 267 267-_stream_factories = {268+_stream_factories: t.Mapping[int, t.Callable[[t.BinaryIO], t.TextIO]] = {269 0: _get_text_stdin,270 1: _get_text_stdout,271 2: _get_text_stderr,272 }273 274 274-def _is_console(f):275+def _is_console(f: t.TextIO) -> bool:276 if not hasattr(f, "fileno"):277 return False278 279 try:4 unmodified lines284 handle = msvcrt.get_osfhandle(fileno)285 return bool(GetConsoleMode(handle, byref(DWORD())))286 287 287-def _get_windows_console_stream(f, encoding, errors):288+def _get_windows_console_stream(289+ f: t.TextIO, encoding: t.Optional[str], errors: t.Optional[str]290+) -> t.Optional[t.TextIO]:291 if (292 get_buffer is not None293 and encoding in {"utf-16-le", None}294 and errors in {"strict", None}295 and _is_console(f)296 ):297 func = _stream_factories.get(f.fileno())298 if func is not None:296- f = getattr(f, "buffer", None)299+ b = getattr(f, "buffer", None)300 298- if f is None:301+ if b is None:302 return None303 301- return func(f)304+ return func(b)modified:src/click/core.py+568 added-340 removed
1 import enum2 import errno3 import os4 import sys5+import typing6 import typing as t7+from collections import abc8 from contextlib import contextmanager9 from contextlib import ExitStack10 from functools import partial11 from functools import update_wrapper21 unmodified lines33 from .types import _NumberRangeBase34 from .types import BOOL35 from .types import convert_type36 from .types import IntRange37+from .types import ParamType38 from .utils import _detect_program_name39 from .utils import _expand_args40 from .utils import echo41 from .utils import make_default_short_help42 from .utils import make_str43 from .utils import PacifyFlushWrapper44 45+if t.TYPE_CHECKING:46+ import typing_extensions as te47+ from .shell_completion import CompletionItem48 49+F = t.TypeVar("F", bound=t.Callable[..., t.Any])50+V = t.TypeVar("V")51+52+43-def _fast_exit(code):53+def _fast_exit(code: int) -> t.NoReturn:54 """Low-level exit that skips Python's cleanup but speeds up exit by55 about 10ms for things like shell completion.56 57 :param code: Exit code.2 unmodified lines60 sys.stderr.flush()61 os._exit(code)62 63 54-def _complete_visible_commands(ctx, incomplete):64+def _complete_visible_commands(65+ ctx: "Context", incomplete: str66+) -> t.Iterator[t.Tuple[str, "Command"]]:67 """List all the subcommands of a group that start with the68 incomplete value and aren't hidden.69 70 :param ctx: Invocation context for the group.71 :param incomplete: Value being completed. May be empty.72 """73+ multi = t.cast(MultiCommand, ctx.command)74+61- for name in ctx.command.list_commands(ctx):75+ for name in multi.list_commands(ctx):76 if name.startswith(incomplete):63- command = ctx.command.get_command(ctx, name)77+ command = multi.get_command(ctx, name)78 65- if not command.hidden:79+ if command is not None and not command.hidden:80 yield name, command81 82 69-def _check_multicommand(base_command, cmd_name, cmd, register=False):83+def _check_multicommand(84+ base_command: "MultiCommand", cmd_name: str, cmd: "Command", register: bool = False85+) -> None:86 if not base_command.chain or not isinstance(cmd, MultiCommand):87 return88 if register:89 hint = (13 unmodified lines103 f" {base_command.name!r})."104 )105 106 91-def batch(iterable, batch_size):107+def batch(iterable: t.Iterable[V], batch_size: int) -> t.List[t.Tuple[V, ...]]:108 return list(zip(*repeat(iter(iterable), batch_size)))109 110 111 @contextmanager96-def augment_usage_errors(ctx, param=None):112+def augment_usage_errors(113+ ctx: "Context", param: t.Optional["Parameter"] = None114+) -> t.Iterator[None]:115 """Context manager that attaches extra information to exceptions."""116 try:117 yield118 except BadParameter as e:7 unmodified lines126 e.ctx = ctx127 raise128 129 112-def iter_params_for_processing(invocation_order, declaration_order):130+def iter_params_for_processing(131+ invocation_order: t.Sequence["Parameter"],132+ declaration_order: t.Sequence["Parameter"],133+) -> t.List["Parameter"]:134 """Given a sequence of parameters in the order as should be considered135 for processing and an iterable of parameters that exist, this returns136 a list in the correct order as they should be processed.137 """138 118- def sort_key(item):139+ def sort_key(item: "Parameter") -> t.Tuple[bool, float]:140 try:120- idx = invocation_order.index(item)141+ idx: float = invocation_order.index(item)142 except ValueError:143 idx = float("inf")123- return (not item.is_eager, idx)144 145+ return not item.is_eager, idx146+147 return sorted(declaration_order, key=sort_key)148 149 150 class ParameterSource(enum.Enum):114 unmodified lines265 266 #: The formatter class to create with :meth:`make_formatter`.267 #:268 #: .. versionadded:: 8.0247- formatter_class = HelpFormatter269+ formatter_class: t.Type["HelpFormatter"] = HelpFormatter270 271 def __init__(272 self,251- command,252- parent=None,253- info_name=None,254- obj=None,255- auto_envvar_prefix=None,256- default_map=None,257- terminal_width=None,258- max_content_width=None,259- resilient_parsing=False,260- allow_extra_args=None,261- allow_interspersed_args=None,262- ignore_unknown_options=None,263- help_option_names=None,264- token_normalize_func=None,265- color=None,266- show_default=None,267- ):273+ command: "Command",274+ parent: t.Optional["Context"] = None,275+ info_name: t.Optional[str] = None,276+ obj: t.Optional[t.Any] = None,277+ auto_envvar_prefix: t.Optional[str] = None,278+ default_map: t.Optional[t.Dict[str, t.Any]] = None,279+ terminal_width: t.Optional[int] = None,280+ max_content_width: t.Optional[int] = None,281+ resilient_parsing: bool = False,282+ allow_extra_args: t.Optional[bool] = None,283+ allow_interspersed_args: t.Optional[bool] = None,284+ ignore_unknown_options: t.Optional[bool] = None,285+ help_option_names: t.Optional[t.List[str]] = None,286+ token_normalize_func: t.Optional[t.Callable[[str], str]] = None,287+ color: t.Optional[bool] = None,288+ show_default: t.Optional[bool] = None,289+ ) -> None:290 #: the parent context or `None` if none exists.291 self.parent = parent292 #: the :class:`Command` for this context.293 self.command = command294 #: the descriptive information name295 self.info_name = info_name296 #: Map of parameter names to their parsed values. Parameters297 #: with ``expose_value=False`` are not stored.276- self.params = {}298+ self.params: t.Dict[str, t.Any] = {}299 #: the leftover arguments.278- self.args = []300+ self.args: t.List[str] = []301 #: protected arguments. These are arguments that are prepended302 #: to `args` when certain parsing scenarios are encountered but303 #: must be never propagated to another arguments. This is used304 #: to implement nested parsing.283- self.protected_args = []305+ self.protected_args: t.List[str] = []306+307 if obj is None and parent is not None:308 obj = parent.obj309+310 #: the user object stored.287- self.obj = obj288- self._meta = getattr(parent, "meta", {})311+ self.obj: t.Optional[t.Any] = obj312+ self._meta: t.Dict[str, t.Any] = getattr(parent, "meta", {})313 314 #: A dictionary (-like object) with defaults for parameters.315 if (316 default_map is None317+ and info_name is not None318 and parent is not None319 and parent.default_map is not None320 ):321 default_map = parent.default_map.get(info_name)297- self.default_map = default_map322 323+ self.default_map: t.Optional[t.Dict[str, t.Any]] = default_map324+325 #: This flag indicates if a subcommand is going to be executed. A326 #: group callback can use this information to figure out if it's327 #: being executed directly or because the execution flow passes328 #: onwards to a subcommand. By default it's None, but it can be2 unmodified lines331 #: If chaining is enabled this will be set to ``'*'`` in case332 #: any commands are executed. It is however not possible to333 #: figure out which ones. If you require this knowledge you334 #: should use a :func:`result_callback`.309- self.invoked_subcommand = None335+ self.invoked_subcommand: t.Optional[str] = None336 337 if terminal_width is None and parent is not None:338 terminal_width = parent.terminal_width339+340 #: The width of the terminal (None is autodetection).314- self.terminal_width = terminal_width341+ self.terminal_width: t.Optional[int] = terminal_width342 343 if max_content_width is None and parent is not None:344 max_content_width = parent.max_content_width345+346 #: The maximum width of formatted content (None implies a sensible347 #: default which is 80 for most things).320- self.max_content_width = max_content_width348+ self.max_content_width: t.Optional[int] = max_content_width349 350 if allow_extra_args is None:351 allow_extra_args = command.allow_extra_args352+353 #: Indicates if the context allows extra args or if it should354 #: fail on parsing.355 #:356 #: .. versionadded:: 3.0357 self.allow_extra_args = allow_extra_args358 359 if allow_interspersed_args is None:360 allow_interspersed_args = command.allow_interspersed_args361+362 #: Indicates if the context allows mixing of arguments and363 #: options or not.364 #:365 #: .. versionadded:: 3.0336- self.allow_interspersed_args = allow_interspersed_args366+ self.allow_interspersed_args: bool = allow_interspersed_args367 368 if ignore_unknown_options is None:369 ignore_unknown_options = command.ignore_unknown_options370+371 #: Instructs click to ignore options that a command does not372 #: understand and will store it on the context for later373 #: processing. This is primarily useful for situations where you374 #: want to call into external programs. Generally this pattern is375 #: strongly discouraged because it's not possibly to losslessly376 #: forward all arguments.377 #:378 #: .. versionadded:: 4.0348- self.ignore_unknown_options = ignore_unknown_options379+ self.ignore_unknown_options: bool = ignore_unknown_options380 381 if help_option_names is None:382 if parent is not None:383 help_option_names = parent.help_option_names384 else:385 help_option_names = ["--help"]386 387 #: The names for the help options.357- self.help_option_names = help_option_names388+ self.help_option_names: t.List[str] = help_option_names389 390 if token_normalize_func is None and parent is not None:391 token_normalize_func = parent.token_normalize_func392 393 #: An optional normalization function for tokens. This is394 #: options, choices, commands etc.364- self.token_normalize_func = token_normalize_func395+ self.token_normalize_func: t.Optional[396+ t.Callable[[str], str]397+ ] = token_normalize_func398 399 #: Indicates if resilient parsing is enabled. In that case Click400 #: will do its best to not cause any failures and default values401 #: will be ignored. Useful for completion.369- self.resilient_parsing = resilient_parsing402+ self.resilient_parsing: bool = resilient_parsing403 404 # If there is no envvar prefix yet, but the parent has one and405 # the command on this level has a name, we can expand the envvar406 # prefix automatically.7 unmodified lines414 f"{parent.auto_envvar_prefix}_{self.info_name.upper()}"415 )416 else:417 auto_envvar_prefix = auto_envvar_prefix.upper()418+419 if auto_envvar_prefix is not None:420 auto_envvar_prefix = auto_envvar_prefix.replace("-", "_")387- self.auto_envvar_prefix = auto_envvar_prefix421 422+ self.auto_envvar_prefix: t.Optional[str] = auto_envvar_prefix423+424 if color is None and parent is not None:425 color = parent.color426 427 #: Controls if styling output is wanted or not.393- self.color = color428+ self.color: t.Optional[bool] = color429 430 if show_default is None and parent is not None:431 show_default = parent.show_default432 433 #: Show option default values when formatting help text.399- self.show_default = show_default434+ self.show_default: t.Optional[bool] = show_default435 401- self._close_callbacks = []436+ self._close_callbacks: t.List[t.Callable[[], t.Any]] = []437 self._depth = 0403- self._parameter_source = {}438+ self._parameter_source: t.Dict[str, ParameterSource] = {}439 self._exit_stack = ExitStack()440 406- def to_info_dict(self):441+ def to_info_dict(self) -> t.Dict[str, t.Any]:442 """Gather information that could be useful for a tool generating443 user-facing documentation. This traverses the entire CLI444 structure.445 12 unmodified lines458 "ignore_unknown_options": self.ignore_unknown_options,459 "auto_envvar_prefix": self.auto_envvar_prefix,460 }461 427- def __enter__(self):462+ def __enter__(self) -> "Context":463 self._depth += 1464 push_context(self)465 return self466 432- def __exit__(self, exc_type, exc_value, tb):467+ def __exit__(self, exc_type, exc_value, tb): # type: ignore468 self._depth -= 1469 if self._depth == 0:470 self.close()471 pop_context()472 473 @contextmanager439- def scope(self, cleanup=True):474+ def scope(self, cleanup: bool = True) -> t.Iterator["Context"]:475 """This helper method can be used with the context object to promote476 it to the current thread local (see :func:`get_current_context`).477 The default behavior of this is to invoke the cleanup functions which478 can be disabled by setting `cleanup` to `False`. The cleanup29 unmodified lines508 if not cleanup:509 self._depth -= 1510 511 @property477- def meta(self):512+ def meta(self) -> t.Dict[str, t.Any]:513 """This is a dictionary which is shared with all the contexts514 that are nested. It exists so that click utilities can store some515 state here if they need to. It is however the responsibility of516 that code to manage this dictionary well.18 unmodified lines535 .. versionadded:: 5.0536 """537 return self._meta538 504- def make_formatter(self):539+ def make_formatter(self) -> HelpFormatter:540 """Creates the :class:`~click.HelpFormatter` for the help and541 usage output.542 543 To quickly customize the formatter class used without overriding5 unmodified lines549 return self.formatter_class(550 width=self.terminal_width, max_width=self.max_content_width551 )552 518- def with_resource(self, context_manager):553+ def with_resource(self, context_manager: t.ContextManager[V]) -> V:554 """Register a resource as if it were used in a ``with``555 statement. The resource will be cleaned up when the context is556 popped.557 20 unmodified lines578 .. versionadded:: 8.0579 """580 return self._exit_stack.enter_context(context_manager)581 547- def call_on_close(self, f):582+ def call_on_close(self, f: t.Callable[..., t.Any]) -> t.Callable[..., t.Any]:583 """Register a function to be called when the context tears down.584 585 This can be used to close resources opened during the script586 execution. Resources that support Python's context manager3 unmodified lines590 :param f: The function to execute on teardown.591 """592 return self._exit_stack.callback(f)593 559- def close(self):594+ def close(self) -> None:595 """Invoke all close callbacks registered with596 :meth:`call_on_close`, and exit all context managers entered597 with :meth:`with_resource`.598 """1 unmodified line600 # In case the context is reused, create a new exit stack.601 self._exit_stack = ExitStack()602 603 @property569- def command_path(self):604+ def command_path(self) -> str:605 """The computed command path. This is used for the ``usage``606 information on the help page. It's automatically created by607 combining the info names of the chain of contexts to the root.608 """1 unmodified line610 if self.info_name is not None:611 rv = self.info_name612 if self.parent is not None:613 parent_command_path = [self.parent.command_path]614+615+ if isinstance(self.parent.command, Command):579- for param in self.parent.command.get_params(self):580- parent_command_path.extend(param.get_usage_pieces(self))616+ for param in self.parent.command.get_params(self):617+ parent_command_path.extend(param.get_usage_pieces(self))618+619 rv = f"{' '.join(parent_command_path)} {rv}"620 return rv.lstrip()621 584- def find_root(self):622+ def find_root(self) -> "Context":623 """Finds the outermost context."""624 node = self625 while node.parent is not None:626 node = node.parent627 return node628 591- def find_object(self, object_type):629+ def find_object(self, object_type: t.Type[V]) -> t.Optional[V]:630 """Finds the closest object of a given type."""593- node = self631+ node: t.Optional["Context"] = self632+633 while node is not None:634 if isinstance(node.obj, object_type):635 return node.obj636+637 node = node.parent638 639+ return None640+599- def ensure_object(self, object_type):641+ def ensure_object(self, object_type: t.Type[V]) -> V:642 """Like :meth:`find_object` but sets the innermost object to a643 new instance of `object_type` if it does not exist.644 """645 rv = self.find_object(object_type)646 if rv is None:647 self.obj = rv = object_type()648 return rv649 608- def lookup_default(self, name, call=True):650+ @typing.overload651+ def lookup_default(652+ self, name: str, call: "te.Literal[True]" = True653+ ) -> t.Optional[t.Any]:654+ ...655+656+ @typing.overload657+ def lookup_default(658+ self, name: str, call: "te.Literal[False]" = ...659+ ) -> t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]]:660+ ...661+662+ def lookup_default(self, name: str, call: bool = True) -> t.Optional[t.Any]:663 """Get the default for a parameter from :attr:`default_map`.664 665 :param name: Name of the parameter.666 :param call: If the default is a callable, call it. Disable to9 unmodified lines676 return value()677 678 return value679 680+ return None681+626- def fail(self, message):682+ def fail(self, message: str) -> t.NoReturn:683 """Aborts the execution of the program with a specific error684 message.685 686 :param message: the error message to fail with.687 """688 raise UsageError(message, self)689 634- def abort(self):690+ def abort(self) -> t.NoReturn:691 """Aborts the script."""692 raise Abort()693 638- def exit(self, code=0):694+ def exit(self, code: int = 0) -> t.NoReturn:695 """Exits the application with a given exit code."""696 raise Exit(code)697 642- def get_usage(self):698+ def get_usage(self) -> str:699 """Helper method to get formatted usage string for the current700 context and command.701 """702 return self.command.get_usage(self)703 648- def get_help(self):704+ def get_help(self) -> str:705 """Helper method to get formatted help page for the current706 context and command.707 """708 return self.command.get_help(self)709 654- def _make_sub_context(self, command):710+ def _make_sub_context(self, command: "Command") -> "Context":711 """Create a new context of the same type as this context, but712 for a new command.713 714 :meta private:715 """716 return type(self)(command, info_name=command.name, parent=self)717 662- def invoke(*args, **kwargs): # noqa: B902718+ def invoke(719+ __self, # noqa: B902720+ __callback: t.Union["Command", t.Callable[..., t.Any]],721+ *args: t.Any,722+ **kwargs: t.Any,723+ ) -> t.Any:724 """Invokes a command callback in exactly the way it expects. There725 are two ways to invoke this method:726 727 1. the first argument can be a callback and all other arguments and11 unmodified lines739 .. versionchanged:: 8.0740 All ``kwargs`` are tracked in :attr:`params` so they will be741 passed if :meth:`forward` is called at multiple levels.742 """682- self, callback = args[:2]683- ctx = self743+ if isinstance(__callback, Command):744+ other_cmd = __callback745 685- # It's also possible to invoke another command which might or686- # might not have a callback. In that case we also fill687- # in defaults and make a new context for this command.688- if isinstance(callback, Command):689- other_cmd = callback690- callback = other_cmd.callback691-692- if callback is None:746+ if other_cmd.callback is None:747 raise TypeError(748 "The given command does not have a callback that can be invoked."749 )750+ else:751+ __callback = other_cmd.callback752 697- ctx = self._make_sub_context(other_cmd)753+ ctx = __self._make_sub_context(other_cmd)754 755 for param in other_cmd.params:756 if param.name not in kwargs and param.expose_value:701- kwargs[param.name] = param.get_default(ctx)757+ kwargs[param.name] = param.get_default(ctx) # type: ignore758 759 # Track all kwargs as params, so that forward() will pass760 # them on in subsequent calls.761 ctx.params.update(kwargs)762+ else:763+ ctx = __self764 707- args = args[2:]708- with augment_usage_errors(self):765+ with augment_usage_errors(__self):766 with ctx:710- return callback(*args, **kwargs)767+ return __callback(*args, **kwargs)768 712- def forward(*args, **kwargs): # noqa: B902769+ def forward(770+ __self, __cmd: "Command", *args: t.Any, **kwargs: t.Any # noqa: B902771+ ) -> t.Any:772 """Similar to :meth:`invoke` but fills in default keyword773 arguments from the current context if the other command expects774 it. This cannot invoke callbacks directly, only other commands.775 776 .. versionchanged:: 8.0777 All ``kwargs`` are tracked in :attr:`params` so they will be778 passed if ``forward`` is called at multiple levels.779 """721- self, cmd = args[:2]722-780 # Can only forward to other commands, not direct callbacks.724- if not isinstance(cmd, Command):781+ if not isinstance(__cmd, Command):782 raise TypeError("Callback is not a command.")783 727- for param in self.params:784+ for param in __self.params:785 if param not in kwargs:729- kwargs[param] = self.params[param]786+ kwargs[param] = __self.params[param]787 731- return self.invoke(cmd, **kwargs)788+ return __self.invoke(__cmd, *args, **kwargs)789 733- def set_parameter_source(self, name, source):790+ def set_parameter_source(self, name: str, source: ParameterSource) -> None:791 """Set the source of a parameter. This indicates the location792 from which the value of the parameter was obtained.793 794 :param name: The name of the parameter.795 :param source: A member of :class:`~click.core.ParameterSource`.796 """797 self._parameter_source[name] = source798 742- def get_parameter_source(self, name):799+ def get_parameter_source(self, name: str) -> t.Optional[ParameterSource]:800 """Get the source of a parameter. This indicates the location801 from which the value of the parameter was obtained.802 803 This can be useful for determining when a user specified a value35 unmodified lines839 840 #: The context class to create with :meth:`make_context`.841 #:842 #: .. versionadded:: 8.0786- context_class = Context843+ context_class: t.Type[Context] = Context844 #: the default for the :attr:`Context.allow_extra_args` flag.845 allow_extra_args = False846 #: the default for the :attr:`Context.allow_interspersed_args` flag.847 allow_interspersed_args = True848 #: the default for the :attr:`Context.ignore_unknown_options` flag.849 ignore_unknown_options = False850 794- def __init__(self, name, context_settings=None):851+ def __init__(852+ self,853+ name: t.Optional[str],854+ context_settings: t.Optional[t.Dict[str, t.Any]] = None,855+ ) -> None:856 #: the name the command thinks it has. Upon registering a command857 #: on a :class:`Group` the group will default the command name858 #: with this information. You should instead use the859 #: :class:`Context`\'s :attr:`~Context.info_name` attribute.860 self.name = name861+862 if context_settings is None:863 context_settings = {}864+865 #: an optional dictionary with defaults passed to the context.803- self.context_settings = context_settings866+ self.context_settings: t.Dict[str, t.Any] = context_settings867 805- def to_info_dict(self, ctx):868+ def to_info_dict(self, ctx: Context) -> t.Dict[str, t.Any]:869 """Gather information that could be useful for a tool generating870 user-facing documentation. This traverses the entire structure871 below this command.872 5 unmodified lines878 .. versionadded:: 8.0879 """880 return {"name": self.name}881 819- def __repr__(self):882+ def __repr__(self) -> str:883 return f"<{self.__class__.__name__} {self.name}>"884 822- def get_usage(self, ctx):885+ def get_usage(self, ctx: Context) -> str:886 raise NotImplementedError("Base commands cannot get usage")887 825- def get_help(self, ctx):888+ def get_help(self, ctx: Context) -> str:889 raise NotImplementedError("Base commands cannot get help")890 828- def make_context(self, info_name, args, parent=None, **extra):891+ def make_context(892+ self,893+ info_name: t.Optional[str],894+ args: t.List[str],895+ parent: t.Optional[Context] = None,896+ **extra: t.Any,897+ ) -> Context:898 """This function when given an info name and arguments will kick899 off the parsing and create a new :class:`Context`. It does not900 invoke the actual command callback though.901 902 To quickly customize the context class used without overriding903 this method, set the :attr:`context_class` attribute.904 836- :param info_name: the info name for this invokation. Generally this905+ :param info_name: the info name for this invocation. Generally this906 is the most descriptive name for the script or907 command. For the toplevel script it's usually908 the name of the script, for commands below it it's840- the name of the script.909+ the name of the command.910 :param args: the arguments to parse as list of strings.911 :param parent: the parent context if available.912 :param extra: extra keyword arguments forwarded to the context913 constructor.4 unmodified lines918 for key, value in self.context_settings.items():919 if key not in extra:920 extra[key] = value921 853- ctx = self.context_class(self, info_name=info_name, parent=parent, **extra)922+ ctx = self.context_class(923+ self, info_name=info_name, parent=parent, **extra # type: ignore924+ )925 926 with ctx.scope(cleanup=False):927 self.parse_args(ctx, args)928 return ctx929 859- def parse_args(self, ctx, args):930+ def parse_args(self, ctx: Context, args: t.List[str]) -> t.List[str]:931 """Given a context and a list of arguments this creates the parser932 and parses the arguments, then modifies the context as necessary.933 This is automatically invoked by :meth:`make_context`.934 """935 raise NotImplementedError("Base commands do not know how to parse arguments.")936 866- def invoke(self, ctx):937+ def invoke(self, ctx: Context) -> t.Any:938 """Given a context, this invokes the command. The default939 implementation is raising a not implemented error.940 """941 raise NotImplementedError("Base commands are not invokable by default")942 872- def shell_complete(self, ctx, incomplete):943+ def shell_complete(self, ctx: Context, incomplete: str) -> t.List["CompletionItem"]:944 """Return a list of completions for the incomplete value. Looks945 at the names of chained multi-commands.946 947 Any command could be part of a chained multi-command, so sibling6 unmodified lines954 .. versionadded:: 8.0955 """956 from click.shell_completion import CompletionItem957 887- results = []958+ results: t.List["CompletionItem"] = []959 960 while ctx.parent is not None:961 ctx = ctx.parent962 5 unmodified lines968 )969 970 return results971 972+ @typing.overload973 def main(974 self,903- args=None,904- prog_name=None,905- complete_var=None,906- standalone_mode=True,907- **extra,908- ):975+ args: t.Optional[t.Sequence[str]] = None,976+ prog_name: t.Optional[str] = None,977+ complete_var: t.Optional[str] = None,978+ standalone_mode: "te.Literal[True]" = True,979+ **extra: t.Any,980+ ) -> t.NoReturn:981+ ...982+983+ @typing.overload984+ def main(985+ self,986+ args: t.Optional[t.Sequence[str]] = None,987+ prog_name: t.Optional[str] = None,988+ complete_var: t.Optional[str] = None,989+ standalone_mode: bool = ...,990+ **extra: t.Any,991+ ) -> t.Any:992+ ...993+994+ def main(995+ self,996+ args: t.Optional[t.Sequence[str]] = None,997+ prog_name: t.Optional[str] = None,998+ complete_var: t.Optional[str] = None,999+ standalone_mode: bool = True,1000+ **extra: t.Any,1001+ ) -> t.Any:1002 """This is the way to invoke a script with all the bells and1003 whistles as a command line application. This will always terminate1004 the application after a call. If this is not wanted, ``SystemExit``1005 needs to be caught.70 unmodified lines1076 e.show()1077 sys.exit(e.exit_code)1078 except OSError as e:1079 if e.errno == errno.EPIPE:987- sys.stdout = PacifyFlushWrapper(sys.stdout)988- sys.stderr = PacifyFlushWrapper(sys.stderr)1080+ sys.stdout = t.cast(t.TextIO, PacifyFlushWrapper(sys.stdout))1081+ sys.stderr = t.cast(t.TextIO, PacifyFlushWrapper(sys.stderr))1082 sys.exit(1)1083 else:1084 raise1085 except Exit as e:14 unmodified lines1100 raise1101 echo(_("Aborted!"), file=sys.stderr)1102 sys.exit(1)1103 1011- def _main_shell_completion(self, ctx_args, prog_name, complete_var=None):1104+ def _main_shell_completion(1105+ self,1106+ ctx_args: t.Dict[str, t.Any],1107+ prog_name: str,1108+ complete_var: t.Optional[str] = None,1109+ ) -> None:1110 """Check if the shell is asking for tab completion, process1111 that, then exit early. Called from :meth:`main` before the1112 program is invoked.1113 14 unmodified lines1128 1129 rv = shell_complete(self, ctx_args, prog_name, complete_var, instruction)1130 _fast_exit(rv)1131 1034- def __call__(self, *args, **kwargs):1132+ def __call__(self, *args: t.Any, **kwargs: t.Any) -> t.Any:1133 """Alias for :meth:`main`."""1134 return self.main(*args, **kwargs)1135 1136 33 unmodified lines1170 """1171 1172 def __init__(1173 self,1076- name,1077- context_settings=None,1078- callback=None,1079- params=None,1080- help=None,1081- epilog=None,1082- short_help=None,1083- options_metavar="[OPTIONS]",1084- add_help_option=True,1085- no_args_is_help=False,1086- hidden=False,1087- deprecated=False,1088- ):1174+ name: t.Optional[str],1175+ context_settings: t.Optional[t.Dict[str, t.Any]] = None,1176+ callback: t.Optional[t.Callable[..., t.Any]] = None,1177+ params: t.Optional[t.List["Parameter"]] = None,1178+ help: t.Optional[str] = None,1179+ epilog: t.Optional[str] = None,1180+ short_help: t.Optional[str] = None,1181+ options_metavar: t.Optional[str] = "[OPTIONS]",1182+ add_help_option: bool = True,1183+ no_args_is_help: bool = False,1184+ hidden: bool = False,1185+ deprecated: bool = False,1186+ ) -> None:1187 super().__init__(name, context_settings)1188 #: the callback to execute when the command fires. This might be1189 #: `None` in which case nothing happens.1190 self.callback = callback1191 #: the list of parameters for this command in the order they1192 #: should show up in the help page and execute. Eager parameters1193 #: will automatically be handled before non eager ones.1096- self.params = params or []1194+ self.params: t.List["Parameter"] = params or []1195+1196 # if a form feed (page break) is found in the help text, truncate help1197 # text to the content preceding the first form feed1198 if help and "\f" in help:1199 help = help.split("\f", 1)[0]1200+1201 self.help = help1202 self.epilog = epilog1203 self.options_metavar = options_metavar1204 self.short_help = short_help1 unmodified line1206 self.no_args_is_help = no_args_is_help1207 self.hidden = hidden1208 self.deprecated = deprecated1209 1110- def to_info_dict(self, ctx):1210+ def to_info_dict(self, ctx: Context) -> t.Dict[str, t.Any]:1211 info_dict = super().to_info_dict(ctx)1212 info_dict.update(1213 params=[param.to_info_dict() for param in self.get_params(ctx)],1214 help=self.help,3 unmodified lines1218 deprecated=self.deprecated,1219 )1220 return info_dict1221 1122- def __repr__(self):1123- return f"<{self.__class__.__name__} {self.name}>"1124-1125- def get_usage(self, ctx):1222+ def get_usage(self, ctx: Context) -> str:1223 """Formats the usage line into a string and returns it.1224 1225 Calls :meth:`format_usage` internally.1226 """1227 formatter = ctx.make_formatter()1228 self.format_usage(ctx, formatter)1229 return formatter.getvalue().rstrip("\n")1230 1134- def get_params(self, ctx):1231+ def get_params(self, ctx: Context) -> t.List["Parameter"]:1232 rv = self.params1233 help_option = self.get_help_option(ctx)1234+1235 if help_option is not None:1138- rv = rv + [help_option]1236+ rv = [*rv, help_option]1237+1238 return rv1239 1141- def format_usage(self, ctx, formatter):1240+ def format_usage(self, ctx: Context, formatter: HelpFormatter) -> None:1241 """Writes the usage line into the formatter.1242 1243 This is a low-level method called by :meth:`get_usage`.1244 """1245 pieces = self.collect_usage_pieces(ctx)1246 formatter.write_usage(ctx.command_path, " ".join(pieces))1247 1149- def collect_usage_pieces(self, ctx):1248+ def collect_usage_pieces(self, ctx: Context) -> t.List[str]:1249 """Returns all the pieces that go into the usage line and returns1250 it as a list of strings.1251 """1252 rv = [self.options_metavar] if self.options_metavar else []1253+1254 for param in self.get_params(ctx):1255 rv.extend(param.get_usage_pieces(ctx))1256+1257 return rv1258 1158- def get_help_option_names(self, ctx):1259+ def get_help_option_names(self, ctx: Context) -> t.List[str]:1260 """Returns the names for the help option."""1261 all_names = set(ctx.help_option_names)1262 for param in self.params:1263 all_names.difference_update(param.opts)1264 all_names.difference_update(param.secondary_opts)1164- return all_names1265+ return list(all_names)1266 1166- def get_help_option(self, ctx):1267+ def get_help_option(self, ctx: Context) -> t.Optional["Option"]:1268 """Returns the help option object."""1269 help_options = self.get_help_option_names(ctx)1270+1271 if not help_options or not self.add_help_option:1170- return1272+ return None1273 1172- def show_help(ctx, param, value):1274+ def show_help(ctx: Context, param: "Parameter", value: str) -> None:1275 if value and not ctx.resilient_parsing:1276 echo(ctx.get_help(), color=ctx.color)1277 ctx.exit()1278 5 unmodified lines1284 callback=show_help,1285 help=_("Show this message and exit."),1286 )1287 1186- def make_parser(self, ctx):1288+ def make_parser(self, ctx: Context) -> OptionParser:1289 """Creates the underlying option parser for this command."""1290 parser = OptionParser(ctx)1291 for param in self.get_params(ctx):1292 param.add_to_parser(parser, ctx)1293 return parser1294 1193- def get_help(self, ctx):1295+ def get_help(self, ctx: Context) -> str:1296 """Formats the help into a string and returns it.1297 1298 Calls :meth:`format_help` internally.1299 """1300 formatter = ctx.make_formatter()1301 self.format_help(ctx, formatter)1302 return formatter.getvalue().rstrip("\n")1303 1202- def get_short_help_str(self, limit=45):1304+ def get_short_help_str(self, limit: int = 45) -> str:1305 """Gets short help for the command or makes it by shortening the1306 long help string.1307 """1308 text = self.short_help or ""5 unmodified lines1314 text = _("(Deprecated) {text}").format(text=text)1315 1316 return text.strip()1317 1216- def format_help(self, ctx, formatter):1318+ def format_help(self, ctx: Context, formatter: HelpFormatter) -> None:1319 """Writes the help into the formatter if it exists.1320 1321 This is a low-level method called by :meth:`get_help`.1322 8 unmodified lines1331 self.format_help_text(ctx, formatter)1332 self.format_options(ctx, formatter)1333 self.format_epilog(ctx, formatter)1334 1233- def format_help_text(self, ctx, formatter):1335+ def format_help_text(self, ctx: Context, formatter: HelpFormatter) -> None:1336 """Writes the help text to the formatter if it exists."""1337 text = self.help or ""1338 1339 if self.deprecated:4 unmodified lines1344 1345 with formatter.indentation():1346 formatter.write_text(text)1347 1246- def format_options(self, ctx, formatter):1348+ def format_options(self, ctx: Context, formatter: HelpFormatter) -> None:1349 """Writes all the options into the formatter if they exist."""1350 opts = []1351 for param in self.get_params(ctx):1352 rv = param.get_help_record(ctx)3 unmodified lines1356 if opts:1357 with formatter.section(_("Options")):1358 formatter.write_dl(opts)1359 1258- def format_epilog(self, ctx, formatter):1360+ def format_epilog(self, ctx: Context, formatter: HelpFormatter) -> None:1361 """Writes the epilog into the formatter if it exists."""1362 if self.epilog:1363 formatter.write_paragraph()1364 with formatter.indentation():1365 formatter.write_text(self.epilog)1366 1265- def parse_args(self, ctx, args):1367+ def parse_args(self, ctx: Context, args: t.List[str]) -> t.List[str]:1368 if not args and self.no_args_is_help and not ctx.resilient_parsing:1369 echo(ctx.get_help(), color=ctx.color)1370 ctx.exit()1371 14 unmodified lines1386 1387 ctx.args = args1388 return args1389 1288- def invoke(self, ctx):1390+ def invoke(self, ctx: Context) -> t.Any:1391 """Given a context, this invokes the attached callback (if it exists)1392 in the right way.1393 """1394 if self.deprecated:1293- echo(1294- style(1295- _("DeprecationWarning: The command {name!r} is deprecated.").format(1296- name=self.name1297- ),1298- fg="red",1299- ),1300- err=True,1301- )1395+ message = _(1396+ "DeprecationWarning: The command {name!r} is deprecated."1397+ ).format(name=self.name)1398+ echo(style(message, fg="red"), err=True)1399 1400 if self.callback is not None:1401 return ctx.invoke(self.callback, **ctx.params)1402 1306- def shell_complete(self, ctx, incomplete):1403+ def shell_complete(self, ctx: Context, incomplete: str) -> t.List["CompletionItem"]:1404 """Return a list of completions for the incomplete value. Looks1405 at the names of options and chained multi-commands.1406 1407 :param ctx: Invocation context for this command.2 unmodified lines1410 .. versionadded:: 8.01411 """1412 from click.shell_completion import CompletionItem1413 1317- results = []1414+ results: t.List["CompletionItem"] = []1415 1416 if incomplete and not incomplete[0].isalnum():1417 for param in self.get_params(ctx):1418 if (1419 not isinstance(param, Option)1420 or param.hidden1421 or (1422 not param.multiple1326- and ctx.get_parameter_source(param.name)1423+ and ctx.get_parameter_source(param.name) # type: ignore1424 is ParameterSource.COMMANDLINE1425 )1426 ):1427 continue1428 1429 results.extend(1430 CompletionItem(name, help=param.help)1334- for name in param.opts + param.secondary_opts1431+ for name in [*param.opts, *param.secondary_opts]1432 if name.startswith(incomplete)1433 )1434 1435 results.extend(super().shell_complete(ctx, incomplete))29 unmodified lines1465 allow_interspersed_args = False1466 1467 def __init__(1468 self,1372- name=None,1373- invoke_without_command=False,1374- no_args_is_help=None,1375- subcommand_metavar=None,1376- chain=False,1377- result_callback=None,1378- **attrs,1379- ):1469+ name: t.Optional[str] = None,1470+ invoke_without_command: bool = False,1471+ no_args_is_help: t.Optional[bool] = None,1472+ subcommand_metavar: t.Optional[str] = None,1473+ chain: bool = False,1474+ result_callback: t.Optional[t.Callable[..., t.Any]] = None,1475+ **attrs: t.Any,1476+ ) -> None:1477 super().__init__(name, **attrs)1478+1479 if no_args_is_help is None:1480 no_args_is_help = not invoke_without_command1481+1482 self.no_args_is_help = no_args_is_help1483 self.invoke_without_command = invoke_without_command1484+1485 if subcommand_metavar is None:1486 if chain:1487 subcommand_metavar = "COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]..."1488 else:1489 subcommand_metavar = "COMMAND [ARGS]..."1490+1491 self.subcommand_metavar = subcommand_metavar1492 self.chain = chain1493 # The result callback that is stored. This can be set or1494 # overridden with the :func:`result_callback` decorator.6 unmodified lines1501 "Multi commands in chain mode cannot have"1502 " optional arguments."1503 )1504 1404- def to_info_dict(self, ctx):1505+ def to_info_dict(self, ctx: Context) -> t.Dict[str, t.Any]:1506 info_dict = super().to_info_dict(ctx)1507 commands = {}1508 1509 for name in self.list_commands(ctx):1510 command = self.get_command(ctx, name)1511+1512+ if command is None:1513+ continue1514+1515 sub_ctx = ctx._make_sub_context(command)1516 1517 with sub_ctx.scope(cleanup=False):1518 commands[name] = command.to_info_dict(sub_ctx)1519 1520 info_dict.update(commands=commands, chain=self.chain)1521 return info_dict1522 1418- def collect_usage_pieces(self, ctx):1523+ def collect_usage_pieces(self, ctx: Context) -> t.List[str]:1524 rv = super().collect_usage_pieces(ctx)1525 rv.append(self.subcommand_metavar)1526 return rv1527 1423- def format_options(self, ctx, formatter):1528+ def format_options(self, ctx: Context, formatter: HelpFormatter) -> None:1529 super().format_options(ctx, formatter)1530 self.format_commands(ctx, formatter)1531 1427- def result_callback(self, replace=False):1532+ def result_callback(self, replace: bool = False) -> t.Callable[[F], F]:1533 """Adds a result callback to the command. By default if a1534 result callback is already registered this will chain them but1535 this can be disabled with the `replace` parameter. The result1536 callback is invoked with the return value of the subcommand20 unmodified lines1557 1558 .. versionadded:: 3.01559 """1560 1456- def decorator(f):1561+ def decorator(f: F) -> F:1562 old_callback = self._result_callback1563 1564 if old_callback is None or replace:1565 self._result_callback = f1566 return f1567 1463- def function(__value, *args, **kwargs):1464- return f(old_callback(__value, *args, **kwargs), *args, **kwargs)1568+ def function(__value, *args, **kwargs): # type: ignore1569+ inner = old_callback(__value, *args, **kwargs) # type: ignore1570+ return f(inner, *args, **kwargs)1571 1466- self._result_callback = rv = update_wrapper(function, f)1572+ self._result_callback = rv = update_wrapper(t.cast(F, function), f)1573 return rv1574 1575 return decorator1576 1471- def resultcallback(self, replace=False):1577+ def resultcallback(self, replace: bool = False) -> t.Callable[[F], F]:1578 import warnings1579 1580 warnings.warn(1581 "'resultcallback' has been renamed to 'result_callback'."2 unmodified lines1584 stacklevel=2,1585 )1586 return self.result_callback(replace=replace)1587 1482- def format_commands(self, ctx, formatter):1588+ def format_commands(self, ctx: Context, formatter: HelpFormatter) -> None:1589 """Extra format methods for multi methods that adds all the commands1590 after the options.1591 """1592 commands = []19 unmodified lines1612 if rows:1613 with formatter.section(_("Commands")):1614 formatter.write_dl(rows)1615 1510- def parse_args(self, ctx, args):1616+ def parse_args(self, ctx: Context, args: t.List[str]) -> t.List[str]:1617 if not args and self.no_args_is_help and not ctx.resilient_parsing:1618 echo(ctx.get_help(), color=ctx.color)1619 ctx.exit()1620 6 unmodified lines1627 ctx.protected_args, ctx.args = rest[:1], rest[1:]1628 1629 return ctx.args1630 1525- def invoke(self, ctx):1526- def _process_result(value):1631+ def invoke(self, ctx: Context) -> t.Any:1632+ def _process_result(value: t.Any) -> t.Any:1633 if self._result_callback is not None:1634 value = ctx.invoke(self._result_callback, value, **ctx.params)1635 return value1636 7 unmodified lines1644 return _process_result([] if self.chain else None)1645 ctx.fail(_("Missing command."))1646 1647 # Fetch args back out1542- args = ctx.protected_args + ctx.args1648+ args = [*ctx.protected_args, *ctx.args]1649 ctx.args = []1650 ctx.protected_args = []1651 1652 # If we're not in chain mode, we only allow the invocation of a3 unmodified lines1656 # Make sure the context is entered so we do not clean up1657 # resources until the result processor has worked.1658 with ctx:1659 cmd_name, cmd, args = self.resolve_command(ctx, args)1660+ assert cmd is not None1661 ctx.invoked_subcommand = cmd_name1662 super().invoke(ctx)1663 sub_ctx = cmd.make_context(cmd_name, args, parent=ctx)1664 with sub_ctx:13 unmodified lines1678 # is the list of all invoked subcommand's results.1679 contexts = []1680 while args:1681 cmd_name, cmd, args = self.resolve_command(ctx, args)1682+ assert cmd is not None1683 sub_ctx = cmd.make_context(1684 cmd_name,1685 args,1686 parent=ctx,8 unmodified lines1695 with sub_ctx:1696 rv.append(sub_ctx.command.invoke(sub_ctx))1697 return _process_result(rv)1698 1591- def resolve_command(self, ctx, args):1699+ def resolve_command(1700+ self, ctx: Context, args: t.List[str]1701+ ) -> t.Tuple[t.Optional[str], t.Optional[Command], t.List[str]]:1702 cmd_name = make_str(args[0])1703 original_cmd_name = cmd_name1704 1705 # Get the command16 unmodified lines1722 self.parse_args(ctx, ctx.args)1723 ctx.fail(_("No such command {name!r}.").format(name=original_cmd_name))1724 return cmd.name if cmd else None, cmd, args[1:]1725 1616- def get_command(self, ctx, cmd_name):1726+ def get_command(self, ctx: Context, cmd_name: str) -> t.Optional[Command]:1727 """Given a context and a command name, this returns a1728 :class:`Command` object if it exists or returns `None`.1729 """1620- raise NotImplementedError()1730+ raise NotImplementedError1731 1622- def list_commands(self, ctx):1732+ def list_commands(self, ctx: Context) -> t.List[str]:1733 """Returns a list of subcommand names in the order they should1734 appear.1735 """1736 return []1737 1628- def shell_complete(self, ctx, incomplete):1738+ def shell_complete(self, ctx: Context, incomplete: str) -> t.List["CompletionItem"]:1739 """Return a list of completions for the incomplete value. Looks1740 at the names of options, subcommands, and chained1741 multi-commands.1742 32 unmodified lines1775 #: as the default :class:`Command` class. This is useful to make all1776 #: subcommands use a custom command class.1777 #:1778 #: .. versionadded:: 8.01669- command_class: t.Optional[t.Type[BaseCommand]] = None1779+ command_class: t.Optional[t.Type[Command]] = None1780 1781 #: If set, this is used by the group's :meth:`group` decorator1782 #: as the default :class:`Group` class. This is useful to make all1783 #: subgroups use a custom group class.6 unmodified lines1790 #: .. versionadded:: 8.01791 group_class: t.Optional[t.Union[t.Type["Group"], t.Type[type]]] = None1792 # Literal[type] isn't valid, so use Type[type]1793 1684- def __init__(self, name=None, commands=None, **attrs):1794+ def __init__(1795+ self,1796+ name: t.Optional[str] = None,1797+ commands: t.Optional[t.Union[t.Dict[str, Command], t.Sequence[Command]]] = None,1798+ **attrs: t.Any,1799+ ) -> None:1800 super().__init__(name, **attrs)1801 1802 if commands is None:1803 commands = {}1689- elif isinstance(commands, (list, tuple)):1690- commands = {c.name: c for c in commands}1804+ elif isinstance(commands, abc.Sequence):1805+ commands = {c.name: c for c in commands if c.name is not None}1806 1807 #: The registered subcommands by their exported names.1693- self.commands = commands1808+ self.commands: t.Dict[str, Command] = commands1809 1695- def add_command(self, cmd, name=None):1810+ def add_command(self, cmd: Command, name: t.Optional[str] = None) -> None:1811 """Registers another :class:`Command` with this group. If the name1812 is not provided, the name of the command is used.1813 """1814 name = name or cmd.name1 unmodified line1816 raise TypeError("Command has no name.")1817 _check_multicommand(self, name, cmd, register=True)1818 self.commands[name] = cmd1819 1705- def command(self, *args, **kwargs):1820+ def command(1821+ self, *args: t.Any, **kwargs: t.Any1822+ ) -> t.Callable[[t.Callable[..., t.Any]], Command]:1823 """A shortcut decorator for declaring and attaching a command to1824 the group. This takes the same arguments as :func:`command` and1825 immediately registers the created command with this group by1826 calling :meth:`add_command`.8 unmodified lines1835 1836 if self.command_class is not None and "cls" not in kwargs:1837 kwargs["cls"] = self.command_class1838 1722- def decorator(f):1839+ def decorator(f: t.Callable[..., t.Any]) -> Command:1840 cmd = command(*args, **kwargs)(f)1841 self.add_command(cmd)1842 return cmd1843 1844 return decorator1845 1729- def group(self, *args, **kwargs):1846+ def group(1847+ self, *args: t.Any, **kwargs: t.Any1848+ ) -> t.Callable[[t.Callable[..., t.Any]], "Group"]:1849 """A shortcut decorator for declaring and attaching a group to1850 the group. This takes the same arguments as :func:`group` and1851 immediately registers the created group with this group by1852 calling :meth:`add_command`.11 unmodified lines1864 kwargs["cls"] = type(self)1865 else:1866 kwargs["cls"] = self.group_class1867 1749- def decorator(f):1868+ def decorator(f: t.Callable[..., t.Any]) -> "Group":1869 cmd = group(*args, **kwargs)(f)1870 self.add_command(cmd)1871 return cmd1872 1873 return decorator1874 1756- def get_command(self, ctx, cmd_name):1875+ def get_command(self, ctx: Context, cmd_name: str) -> t.Optional[Command]:1876 return self.commands.get(cmd_name)1877 1759- def list_commands(self, ctx):1878+ def list_commands(self, ctx: Context) -> t.List[str]:1879 return sorted(self.commands)1880 1881 1882 class CommandCollection(MultiCommand):2 unmodified lines1885 that accepts a list of different multi commands as sources and1886 provides all the commands for each of them.1887 """1888 1770- def __init__(self, name=None, sources=None, **attrs):1889+ def __init__(1890+ self,1891+ name: t.Optional[str] = None,1892+ sources: t.Optional[t.List[MultiCommand]] = None,1893+ **attrs: t.Any,1894+ ) -> None:1895 super().__init__(name, **attrs)1896 #: The list of registered multi commands.1773- self.sources = sources or []1897+ self.sources: t.List[MultiCommand] = sources or []1898 1775- def add_source(self, multi_cmd):1899+ def add_source(self, multi_cmd: MultiCommand) -> None:1900 """Adds a new multi command to the chain dispatcher."""1901 self.sources.append(multi_cmd)1902 1779- def get_command(self, ctx, cmd_name):1903+ def get_command(self, ctx: Context, cmd_name: str) -> t.Optional[Command]:1904 for source in self.sources:1905 rv = source.get_command(ctx, cmd_name)1906+1907 if rv is not None:1908 if self.chain:1909 _check_multicommand(self, cmd_name, rv)1910+1911 return rv1912 1787- def list_commands(self, ctx):1788- rv = set()1913+ return None1914+1915+ def list_commands(self, ctx: Context) -> t.List[str]:1916+ rv: t.Set[str] = set()1917+1918 for source in self.sources:1919 rv.update(source.list_commands(ctx))1920+1921 return sorted(rv)1922 1923 1794-def _check_iter(value):1924+def _check_iter(value: t.Any) -> t.Iterator[t.Any]:1925 """Check if the value is iterable but not a string. Raises a type1926 error, or return an iterator over the value.1927 """1928 if isinstance(value, str):79 unmodified lines2008 param_type_name = "parameter"2009 2010 def __init__(2011 self,1882- param_decls=None,1883- type=None,1884- required=False,1885- default=None,1886- callback=None,1887- nargs=None,1888- multiple=False,1889- metavar=None,1890- expose_value=True,1891- is_eager=False,1892- envvar=None,1893- shell_complete=None,1894- autocompletion=None,1895- ):2012+ param_decls: t.Optional[t.Sequence[str]] = None,2013+ type: t.Optional[t.Union["ParamType", t.Any]] = None,2014+ required: bool = False,2015+ default: t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]] = None,2016+ callback: t.Optional[t.Callable[[Context, "Parameter", t.Any], t.Any]] = None,2017+ nargs: t.Optional[int] = None,2018+ multiple: bool = False,2019+ metavar: t.Optional[str] = None,2020+ expose_value: bool = True,2021+ is_eager: bool = False,2022+ envvar: t.Optional[t.Union[str, t.Sequence[str]]] = None,2023+ shell_complete: t.Optional[2024+ t.Callable[2025+ [Context, "Parameter", str], t.List[t.Union["CompletionItem", str]]2026+ ]2027+ ] = None,2028+ autocompletion: t.Optional[2029+ t.Callable[2030+ [Context, t.List[str], str], t.List[t.Union[t.Tuple[str, str], str]]2031+ ]2032+ ] = None,2033+ ) -> None:2034 self.name, self.opts, self.secondary_opts = self._parse_decls(2035 param_decls or (), expose_value2036 )2037 27 unmodified lines2065 DeprecationWarning,2066 stacklevel=2,2067 )2068 1931- def shell_complete(ctx, param, incomplete):2069+ def shell_complete(2070+ ctx: Context, param: "Parameter", incomplete: str2071+ ) -> t.List[t.Union["CompletionItem", str]]:2072 from click.shell_completion import CompletionItem2073 2074 out = []2075 1936- for c in autocompletion(ctx, [], incomplete):2076+ for c in autocompletion(ctx, [], incomplete): # type: ignore2077 if isinstance(c, tuple):2078 c = CompletionItem(c[0], help=c[1])2079 elif isinstance(c, str):2080 c = CompletionItem(c)45 unmodified lines2126 raise ValueError(2127 f"'default' {subject} must match nargs={nargs}."2128 )2129 1990- def to_info_dict(self):2130+ def to_info_dict(self) -> t.Dict[str, t.Any]:2131 """Gather information that could be useful for a tool generating2132 user-facing documentation.2133 2134 Use :meth:`click.Context.to_info_dict` to traverse the entire13 unmodified lines2148 "default": self.default,2149 "envvar": self.envvar,2150 }2151 2012- def __repr__(self):2152+ def __repr__(self) -> str:2153 return f"<{self.__class__.__name__} {self.name}>"2154 2155+ def _parse_decls(2156+ self, decls: t.Sequence[str], expose_value: bool2157+ ) -> t.Tuple[t.Optional[str], t.List[str], t.List[str]]:2158+ raise NotImplementedError()2159+2160 @property2016- def human_readable_name(self):2161+ def human_readable_name(self) -> str:2162 """Returns the human readable name of this parameter. This is the2163 same as the name for options, but the metavar for arguments.2164 """2020- return self.name2165+ return self.name # type: ignore2166 2022- def make_metavar(self):2167+ def make_metavar(self) -> str:2168 if self.metavar is not None:2169 return self.metavar2170+2171 metavar = self.type.get_metavar(self)2172+2173 if metavar is None:2174 metavar = self.type.name.upper()2175+2176 if self.nargs != 1:2177 metavar += "..."2178+2179 return metavar2180 2032- def get_default(self, ctx, call=True):2181+ @typing.overload2182+ def get_default(2183+ self, ctx: Context, call: "te.Literal[True]" = True2184+ ) -> t.Optional[t.Any]:2185+ ...2186+2187+ @typing.overload2188+ def get_default(2189+ self, ctx: Context, call: bool = ...2190+ ) -> t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]]:2191+ ...2192+2193+ def get_default(2194+ self, ctx: Context, call: bool = True2195+ ) -> t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]]:2196 """Get the default for the parameter. Tries2197 :meth:`Context.lookup_value` first, then the local default.2198 2199 :param ctx: Current context.5 unmodified lines2205 2206 .. versionchanged:: 8.02207 Added the ``call`` parameter.2208 """2046- value = ctx.lookup_default(self.name, call=False)2209+ value = ctx.lookup_default(self.name, call=False) # type: ignore2210 2211 if value is None:2212 value = self.default2213 5 unmodified lines2219 value = value()2220 2221 return self.type_cast_value(ctx, value)2222 2060- def add_to_parser(self, parser, ctx):2061- pass2223+ def add_to_parser(self, parser: OptionParser, ctx: Context) -> None:2224+ raise NotImplementedError()2225 2063- def consume_value(self, ctx, opts):2064- value = opts.get(self.name)2226+ def consume_value(2227+ self, ctx: Context, opts: t.Mapping[str, t.Any]2228+ ) -> t.Tuple[t.Any, ParameterSource]:2229+ value = opts.get(self.name) # type: ignore2230 source = ParameterSource.COMMANDLINE2231 2232 if value is None:2233 value = self.value_from_envvar(ctx)2234 source = ParameterSource.ENVIRONMENT2235 2236 if value is None:2072- value = ctx.lookup_default(self.name)2237+ value = ctx.lookup_default(self.name) # type: ignore2238 source = ParameterSource.DEFAULT_MAP2239 2240 if value is None:2241 value = self.get_default(ctx)2242 source = ParameterSource.DEFAULT2243 2244 return value, source2245 2081- def type_cast_value(self, ctx, value):2246+ def type_cast_value(self, ctx: Context, value: t.Any) -> t.Any:2247 """Convert and validate a value against the option's2248 :attr:`type`, :attr:`multiple`, and :attr:`nargs`.2249 """2250 if value is None:2251 return () if self.multiple or self.nargs == -1 else None2252 2088- def check_iter(value):2253+ def check_iter(value: t.Any) -> t.Iterator:2254 try:2255 return _check_iter(value)2256 except TypeError:2257 # This should only happen when passing in args manually,3 unmodified lines2261 _("Value must be an iterable."), ctx=ctx, param=self2262 ) from None2263 2264 if self.nargs == 1 or self.type.is_composite:2100- convert = partial(self.type, param=self, ctx=ctx)2265+ convert: t.Callable[[t.Any], t.Any] = partial(2266+ self.type, param=self, ctx=ctx2267+ )2268 elif self.nargs == -1:2269 2103- def convert(value):2270+ def convert(value: t.Any) -> t.Tuple:2271 return tuple(self.type(x, self, ctx) for x in check_iter(value))2272 2273 else: # nargs > 12274 2108- def convert(value):2275+ def convert(value: t.Any) -> t.Tuple:2276 value = tuple(check_iter(value))2277 2278 if len(value) != self.nargs:2279 raise BadParameter(12 unmodified lines2292 return tuple(convert(x) for x in check_iter(value))2293 2294 return convert(value)2295 2129- def value_is_missing(self, value):2296+ def value_is_missing(self, value: t.Any) -> bool:2297 if value is None:2298 return True2299 2300 if (self.nargs != 1 or self.multiple) and value == ():2301 return True2302 2303 return False2304 2138- def process_value(self, ctx, value):2305+ def process_value(self, ctx: Context, value: t.Any) -> t.Any:2306 if value is not None:2307 value = self.type_cast_value(ctx, value)2308 2309 if self.required and self.value_is_missing(value):3 unmodified lines2313 value = self.callback(ctx, self, value)2314 2315 return value2316 2150- def resolve_envvar_value(self, ctx):2317+ def resolve_envvar_value(self, ctx: Context) -> t.Optional[str]:2318 if self.envvar is None:2152- return2319+ return None2320 2154- if isinstance(self.envvar, (tuple, list)):2321+ if isinstance(self.envvar, str):2322+ rv = os.environ.get(self.envvar)2323+2324+ if rv:2325+ return rv2326+ else:2327 for envvar in self.envvar:2328 rv = os.environ.get(envvar)2329 2330 if rv:2331 return rv2160- else:2161- rv = os.environ.get(self.envvar)2332 2163- if rv:2164- return rv2333+ return None2334 2166- def value_from_envvar(self, ctx):2167- rv = self.resolve_envvar_value(ctx)2335+ def value_from_envvar(self, ctx: Context) -> t.Optional[t.Any]:2336+ rv: t.Optional[t.Any] = self.resolve_envvar_value(ctx)2337 2338 if rv is not None and self.nargs != 1:2339 rv = self.type.split_envvar_value(rv)2340 2341 return rv2342 2174- def handle_parse_result(self, ctx, opts, args):2343+ def handle_parse_result(2344+ self, ctx: Context, opts: t.Mapping[str, t.Any], args: t.List[str]2345+ ) -> t.Tuple[t.Any, t.List[str]]:2346 with augment_usage_errors(ctx, param=self):2347 value, source = self.consume_value(ctx, opts)2177- ctx.set_parameter_source(self.name, source)2348+ ctx.set_parameter_source(self.name, source) # type: ignore2349 2350 try:2351 value = self.process_value(ctx, value)2352 except Exception:2 unmodified lines2355 2356 value = None2357 2358 if self.expose_value:2188- ctx.params[self.name] = value2359+ ctx.params[self.name] = value # type: ignore2360 2361 return value, args2362 2192- def get_help_record(self, ctx):2363+ def get_help_record(self, ctx: Context) -> t.Optional[t.Tuple[str, str]]:2364 pass2365 2195- def get_usage_pieces(self, ctx):2366+ def get_usage_pieces(self, ctx: Context) -> t.List[str]:2367 return []2368 2198- def get_error_hint(self, ctx):2369+ def get_error_hint(self, ctx: Context) -> str:2370 """Get a stringified version of the param for use in error messages to2371 indicate which param caused the error.2372 """2373 hint_list = self.opts or [self.human_readable_name]2374 return " / ".join(repr(x) for x in hint_list)2375 2205- def shell_complete(self, ctx, incomplete):2376+ def shell_complete(self, ctx: Context, incomplete: str) -> t.List["CompletionItem"]:2377 """Return a list of completions for the incomplete value. If a2378 ``shell_complete`` function was given during init, it is used.2379 Otherwise, the :attr:`type`2380 :meth:`~click.types.ParamType.shell_complete` function is used.10 unmodified lines2391 from click.shell_completion import CompletionItem2392 2393 results = [CompletionItem(c) for c in results]2394 2224- return results2395+ return t.cast(t.List["CompletionItem"], results)2396 2397 return self.type.shell_complete(ctx, self, incomplete)2398 2399 43 unmodified lines2443 param_type_name = "option"2444 2445 def __init__(2446 self,2276- param_decls=None,2277- show_default=False,2278- prompt=False,2279- confirmation_prompt=False,2280- prompt_required=True,2281- hide_input=False,2282- is_flag=None,2283- flag_value=None,2284- multiple=False,2285- count=False,2286- allow_from_autoenv=True,2287- type=None,2288- help=None,2289- hidden=False,2290- show_choices=True,2291- show_envvar=False,2292- **attrs,2293- ):2447+ param_decls: t.Optional[t.Sequence[str]] = None,2448+ show_default: bool = False,2449+ prompt: t.Union[bool, str] = False,2450+ confirmation_prompt: t.Union[bool, str] = False,2451+ prompt_required: bool = True,2452+ hide_input: bool = False,2453+ is_flag: t.Optional[bool] = None,2454+ flag_value: t.Optional[t.Any] = None,2455+ multiple: bool = False,2456+ count: bool = False,2457+ allow_from_autoenv: bool = True,2458+ type: t.Optional[t.Union["ParamType", t.Any]] = None,2459+ help: t.Optional[str] = None,2460+ hidden: bool = False,2461+ show_choices: bool = True,2462+ show_envvar: bool = False,2463+ **attrs: t.Any,2464+ ) -> None:2465 default_is_missing = "default" not in attrs2466 super().__init__(param_decls, type=type, multiple=multiple, **attrs)2467 2468 if prompt is True:2469+ if self.name is None:2470+ raise TypeError("'name' is required with 'prompt=True'.")2471+2298- prompt_text = self.name.replace("_", " ").capitalize()2472+ prompt_text: t.Optional[str] = self.name.replace("_", " ").capitalize()2473 elif prompt is False:2474 prompt_text = None2475 else:2302- prompt_text = prompt2476+ prompt_text = t.cast(str, prompt)2477 2478 self.prompt = prompt_text2479 self.confirmation_prompt = confirmation_prompt2480 self.prompt_required = prompt_required19 unmodified lines2500 # flag if flag_value is set.2501 self._flag_needs_value = flag_value is not None2502 2503 if is_flag and default_is_missing:2330- self.default = False2504+ self.default: t.Union[t.Any, t.Callable[[], t.Any]] = False2505 2506 if flag_value is None:2507 flag_value = not self.default2508 2335- self.is_flag = is_flag2336- self.flag_value = flag_value2509+ self.is_flag: bool = is_flag2510+ self.flag_value: t.Any = flag_value2511 2512 if self.is_flag and isinstance(self.flag_value, bool) and type in [None, bool]:2339- self.type = BOOL2513+ self.type: "ParamType" = BOOL2514 self.is_bool_flag = True2515 else:2516 self.is_bool_flag = False2517 32 unmodified lines2550 2551 if self.is_flag:2552 raise TypeError("'count' is not valid with 'is_flag'.")2553 2380- def to_info_dict(self):2554+ def to_info_dict(self) -> t.Dict[str, t.Any]:2555 info_dict = super().to_info_dict()2556 info_dict.update(2557 help=self.help,2558 prompt=self.prompt,3 unmodified lines2562 hidden=self.hidden,2563 )2564 return info_dict2565 2392- def _parse_decls(self, decls, expose_value):2566+ def _parse_decls(2567+ self, decls: t.Sequence[str], expose_value: bool2568+ ) -> t.Tuple[t.Optional[str], t.List[str], t.List[str]]:2569 opts = []2570 secondary_opts = []2571 name = None2572 possible_names = []42 unmodified lines2615 )2616 2617 return name, opts, secondary_opts2618 2443- def add_to_parser(self, parser, ctx):2444- kwargs = {2445- "dest": self.name,2446- "nargs": self.nargs,2447- "obj": self,2448- }2449-2619+ def add_to_parser(self, parser: OptionParser, ctx: Context) -> None:2620 if self.multiple:2621 action = "append"2622 elif self.count:2623 action = "count"2624 else:2625 action = "store"2626 2627 if self.is_flag:2458- kwargs.pop("nargs", None)2459- action_const = f"{action}_const"2628+ action = f"{action}_const"2629+2630 if self.is_bool_flag and self.secondary_opts:2461- parser.add_option(self.opts, action=action_const, const=True, **kwargs)2631 parser.add_option(2463- self.secondary_opts, action=action_const, const=False, **kwargs2632+ obj=self, opts=self.opts, dest=self.name, action=action, const=True2633 )2634+ parser.add_option(2635+ obj=self,2636+ opts=self.secondary_opts,2637+ dest=self.name,2638+ action=action,2639+ const=False,2640+ )2641 else:2642 parser.add_option(2467- self.opts, action=action_const, const=self.flag_value, **kwargs2643+ obj=self,2644+ opts=self.opts,2645+ dest=self.name,2646+ action=action,2647+ const=self.flag_value,2648 )2649 else:2470- kwargs["action"] = action2471- parser.add_option(self.opts, **kwargs)2650+ parser.add_option(2651+ obj=self,2652+ opts=self.opts,2653+ dest=self.name,2654+ action=action,2655+ nargs=self.nargs,2656+ )2657 2473- def get_help_record(self, ctx):2658+ def get_help_record(self, ctx: Context) -> t.Optional[t.Tuple[str, str]]:2659 if self.hidden:2475- return2476- any_prefix_is_slash = []2660+ return None2661 2478- def _write_opts(opts):2662+ any_prefix_is_slash = False2663+2664+ def _write_opts(opts: t.Sequence[str]) -> str:2665+ nonlocal any_prefix_is_slash2666+2667 rv, any_slashes = join_options(opts)2668+2669 if any_slashes:2481- any_prefix_is_slash[:] = [True]2670+ any_prefix_is_slash = True2671+2672 if not self.is_flag and not self.count:2673 rv += f" {self.make_metavar()}"2674+2675 return rv2676 2677 rv = [_write_opts(self.opts)]2678+2679 if self.secondary_opts:2680 rv.append(_write_opts(self.secondary_opts))2681 2682 help = self.help or ""2683 extra = []2684+2685 if self.show_envvar:2686 envvar = self.envvar2687+2688 if envvar is None:2495- if self.allow_from_autoenv and ctx.auto_envvar_prefix is not None:2689+ if (2690+ self.allow_from_autoenv2691+ and ctx.auto_envvar_prefix is not None2692+ and self.name is not None2693+ ):2694 envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}"2695+2696 if envvar is not None:2697 var_str = (2499- ", ".join(str(d) for d in envvar)2500- if isinstance(envvar, (list, tuple))2501- else envvar2698+ envvar2699+ if isinstance(envvar, str)2700+ else ", ".join(str(d) for d in envvar)2701 )2702 extra.append(_("env var: {var}").format(var=var_str))2703 2704 default_value = self.get_default(ctx, call=False)2 unmodified lines2707 if show_default_is_str or (2708 default_value is not None and (self.show_default or ctx.show_default)2709 ):2710 if show_default_is_str:2512- default_string = f"({self.show_default})"2711+ default_string: t.Union[str, t.Any] = f"({self.show_default})"2712 elif isinstance(default_value, (list, tuple)):2713 default_string = ", ".join(str(d) for d in default_value)2714 elif callable(default_value):2715 default_string = _("(dynamic)")15 unmodified lines2731 extra.append(range_str)2732 2733 if self.required:2734 extra.append(_("required"))2735+2736 if extra:2737 extra_str = ";".join(extra)2738 help = f"{help} [{extra_str}]" if help else f"[{extra_str}]"2739 2740 return ("; " if any_prefix_is_slash else " / ").join(rv), help2741 2542- def get_default(self, ctx, call=True):2742+ @typing.overload2743+ def get_default(2744+ self, ctx: Context, call: "te.Literal[True]" = True2745+ ) -> t.Optional[t.Any]:2746+ ...2747+2748+ @typing.overload2749+ def get_default(2750+ self, ctx: Context, call: bool = ...2751+ ) -> t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]]:2752+ ...2753+2754+ def get_default(2755+ self, ctx: Context, call: bool = True2756+ ) -> t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]]:2757 # If we're a non boolean flag our default is more complex because2758 # we need to look at all flags in the same group to figure out2759 # if we're the the default one in which case we return the flag2760 # value as default.2761 if self.is_flag and not self.is_bool_flag:2762 for param in ctx.command.params:2763 if param.name == self.name and param.default:2550- return param.flag_value2764+ return param.flag_value # type: ignore2765 2766 return None2767 2768 return super().get_default(ctx, call=call)2769 2556- def prompt_for_value(self, ctx):2770+ def prompt_for_value(self, ctx: Context) -> t.Any:2771 """This is an alternative flow that can be activated in the full2772 value processing if a value does not exist. It will prompt the2773 user until a valid value exists and then returns the processed2774 value as result.2775 """2776+ assert self.prompt is not None2777+2778 # Calculate the default before prompting anything to be stable.2779 default = self.get_default(ctx)2780 2781 # If this is a prompt for a flag we need to handle this10 unmodified lines2792 confirmation_prompt=self.confirmation_prompt,2793 value_proc=lambda x: self.process_value(ctx, x),2794 )2795 2580- def resolve_envvar_value(self, ctx):2796+ def resolve_envvar_value(self, ctx: Context) -> t.Optional[str]:2797 rv = super().resolve_envvar_value(ctx)2798 2799 if rv is not None:2800 return rv2801 2586- if self.allow_from_autoenv and ctx.auto_envvar_prefix is not None:2802+ if (2803+ self.allow_from_autoenv2804+ and ctx.auto_envvar_prefix is not None2805+ and self.name is not None2806+ ):2807 envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}"2808 rv = os.environ.get(envvar)2809 2590- if rv:2591- return rv2810+ return rv2811 2593- def value_from_envvar(self, ctx):2594- rv = self.resolve_envvar_value(ctx)2812+ def value_from_envvar(self, ctx: Context) -> t.Optional[t.Any]:2813+ rv: t.Optional[t.Any] = self.resolve_envvar_value(ctx)2814 2815 if rv is None:2816 return None2817 2818 value_depth = (self.nargs != 1) + bool(self.multiple)2819 2601- if value_depth > 0 and rv is not None:2820+ if value_depth > 0:2821 rv = self.type.split_envvar_value(rv)2822 2823 if self.multiple and self.nargs != 1:2824 rv = batch(rv, self.nargs)2825 2826 return rv2827 2609- def consume_value(self, ctx, opts):2828+ def consume_value(2829+ self, ctx: Context, opts: t.Mapping[str, "Parameter"]2830+ ) -> t.Tuple[t.Any, ParameterSource]:2831 value, source = super().consume_value(ctx, opts)2832 2833 # The parser will emit a sentinel value if the option can be2834 # given as a flag without a value. This is different from None29 unmodified lines2864 """2865 2866 param_type_name = "argument"2867 2647- def __init__(self, param_decls, required=None, **attrs):2868+ def __init__(2869+ self,2870+ param_decls: t.Sequence[str],2871+ required: t.Optional[bool] = None,2872+ **attrs: t.Any,2873+ ) -> None:2874 if required is None:2875 if attrs.get("default") is not None:2876 required = False2877 else:8 unmodified lines2886 if self.default is not None and self.nargs == -1:2887 raise TypeError("'default' is not supported for nargs=-1.")2888 2889 @property2664- def human_readable_name(self):2890+ def human_readable_name(self) -> str:2891 if self.metavar is not None:2892 return self.metavar2667- return self.name.upper()2893+ return self.name.upper() # type: ignore2894 2669- def make_metavar(self):2895+ def make_metavar(self) -> str:2896 if self.metavar is not None:2897 return self.metavar2898 var = self.type.get_metavar(self)2899 if not var:2674- var = self.name.upper()2900+ var = self.name.upper() # type: ignore2901 if not self.required:2902 var = f"[{var}]"2903 if self.nargs != 1:2904 var += "..."2905 return var2906 2681- def _parse_decls(self, decls, expose_value):2907+ def _parse_decls(2908+ self, decls: t.Sequence[str], expose_value: bool2909+ ) -> t.Tuple[t.Optional[str], t.List[str], t.List[str]]:2910 if not decls:2911 if not expose_value:2912 return None, [], []2913 raise TypeError("Could not determine name for argument")6 unmodified lines2920 f" {len(decls)}."2921 )2922 return name, [arg], []2923 2696- def get_usage_pieces(self, ctx):2924+ def get_usage_pieces(self, ctx: Context) -> t.List[str]:2925 return [self.make_metavar()]2926 2699- def get_error_hint(self, ctx):2927+ def get_error_hint(self, ctx: Context) -> str:2928 return repr(self.make_metavar())2929 2702- def add_to_parser(self, parser, ctx):2930+ def add_to_parser(self, parser: OptionParser, ctx: Context) -> None:2931 parser.add_argument(dest=self.name, nargs=self.nargs, obj=self)modified:src/click/decorators.py+69 added-49 removed
1 import inspect2+import types3 import typing as t4 from functools import update_wrapper5 from gettext import gettext as _6 7 from .core import Argument8 from .core import Command9+from .core import Context10 from .core import Group11 from .core import Option12+from .core import Parameter13 from .globals import get_current_context14 from .utils import echo15 13-if t.TYPE_CHECKING:14- F = t.TypeVar("F", bound=t.Callable[..., t.Any])16+F = t.TypeVar("F", bound=t.Callable[..., t.Any])17+FC = t.TypeVar("FC", t.Callable[..., t.Any], Command)18 19 17-def pass_context(f: "F") -> "F":20+def pass_context(f: F) -> F:21 """Marks a callback as wanting to receive the current context22 object as first argument.23 """24 22- def new_func(*args, **kwargs):25+ def new_func(*args, **kwargs): # type: ignore26 return f(get_current_context(), *args, **kwargs)27 25- return update_wrapper(t.cast("F", new_func), f)28+ return update_wrapper(t.cast(F, new_func), f)29 30 28-def pass_obj(f: "F") -> "F":31+def pass_obj(f: F) -> F:32 """Similar to :func:`pass_context`, but only pass the object on the33 context onwards (:attr:`Context.obj`). This is useful if that object34 represents the state of a nested system.35 """36 34- def new_func(*args, **kwargs):37+ def new_func(*args, **kwargs): # type: ignore38 return f(get_current_context().obj, *args, **kwargs)39 37- return update_wrapper(t.cast("F", new_func), f)40+ return update_wrapper(t.cast(F, new_func), f)41 42 43 def make_pass_decorator(44 object_type: t.Type, ensure: bool = False19 unmodified lines64 :param ensure: if set to `True`, a new object will be created and65 remembered on the context if it's not there yet.66 """67 65- def decorator(f: "F") -> "F":66- def new_func(*args, **kwargs):68+ def decorator(f: F) -> F:69+ def new_func(*args, **kwargs): # type: ignore70 ctx = get_current_context()71 72 if ensure:73 obj = ctx.ensure_object(object_type)8 unmodified lines82 )83 84 return ctx.invoke(f, obj, *args, **kwargs)85 83- return update_wrapper(t.cast("F", new_func), f)86+ return update_wrapper(t.cast(F, new_func), f)87 88 return decorator89 90 11 unmodified lines102 103 .. versionadded:: 8.0104 """105 103- def decorator(f: "F") -> "F":104- def new_func(*args, **kwargs):106+ def decorator(f: F) -> F:107+ def new_func(*args, **kwargs): # type: ignore108 ctx = get_current_context()109 obj = ctx.meta[key]110 return ctx.invoke(f, obj, *args, **kwargs)111 109- return update_wrapper(t.cast("F", new_func), f)112+ return update_wrapper(t.cast(F, new_func), f)113 114 if doc_description is None:115 doc_description = f"the {key!r} key from :attr:`click.Context.meta`"116 3 unmodified lines120 )121 return decorator122 123 121-def _make_command(f, name, attrs, cls):124+def _make_command(125+ f: F,126+ name: t.Optional[str],127+ attrs: t.MutableMapping[str, t.Any],128+ cls: t.Type[Command],129+) -> Command:130 if isinstance(f, Command):131 raise TypeError("Attempted to convert a callback into a command twice.")132+133 try:125- params = f.__click_params__134+ params = f.__click_params__ # type: ignore135 params.reverse()127- del f.__click_params__136+ del f.__click_params__ # type: ignore137 except AttributeError:138 params = []139+140 help = attrs.get("help")141+142 if help is None:143 help = inspect.getdoc(f)133- if isinstance(help, bytes):134- help = help.decode("utf-8")144 else:145 help = inspect.cleandoc(help)146+147 attrs["help"] = help148 return cls(149 name=name or f.__name__.lower().replace("_", "-"),150 callback=f,1 unmodified line152 **attrs,153 )154 155 146-def command(name=None, cls=None, **attrs):156+def command(157+ name: t.Optional[str] = None,158+ cls: t.Optional[t.Type[Command]] = None,159+ **attrs: t.Any,160+) -> t.Callable[[F], Command]:161 r"""Creates a new :class:`Command` and uses the decorated function as162 callback. This will also automatically attach all decorated163 :func:`option`\s and :func:`argument`\s as parameters to the command.164 14 unmodified lines179 """180 if cls is None:181 cls = Command182 169- def decorator(f):170- cmd = _make_command(f, name, attrs, cls)183+ def decorator(f: t.Callable[..., t.Any]) -> Command:184+ cmd = _make_command(f, name, attrs, cls) # type: ignore185 cmd.__doc__ = f.__doc__186 return cmd187 188 return decorator189 190 177-def group(name=None, **attrs):191+def group(name: t.Optional[str] = None, **attrs: t.Any) -> t.Callable[[F], Group]:192 """Creates a new :class:`Group` with a function as callback. This193 works otherwise the same as :func:`command` just that the `cls`194 parameter is set to :class:`Group`.195 """196 attrs.setdefault("cls", Group)183- return command(name, **attrs)197+ return t.cast(Group, command(name, **attrs))198 199 186-def _param_memo(f, param):200+def _param_memo(f: FC, param: Parameter) -> None:201 if isinstance(f, Command):202 f.params.append(param)203 else:204 if not hasattr(f, "__click_params__"):191- f.__click_params__ = []192- f.__click_params__.append(param)205+ f.__click_params__ = [] # type: ignore206 207+ f.__click_params__.append(param) # type: ignore208 195-def argument(*param_decls, **attrs):209+210+def argument(*param_decls: str, **attrs: t.Any) -> t.Callable[[FC], FC]:211 """Attaches an argument to the command. All positional arguments are212 passed as parameter declarations to :class:`Argument`; all keyword213 arguments are forwarded unchanged (except ``cls``).214 This is equivalent to creating an :class:`Argument` instance manually2 unmodified lines217 :param cls: the argument class to instantiate. This defaults to218 :class:`Argument`.219 """220 206- def decorator(f):221+ def decorator(f: FC) -> FC:222 ArgumentClass = attrs.pop("cls", Argument)223 _param_memo(f, ArgumentClass(param_decls, **attrs))224 return f225 226 return decorator227 228 214-def option(*param_decls, **attrs):229+def option(*param_decls: str, **attrs: t.Any) -> t.Callable[[FC], FC]:230 """Attaches an option to the command. All positional arguments are231 passed as parameter declarations to :class:`Option`; all keyword232 arguments are forwarded unchanged (except ``cls``).233 This is equivalent to creating an :class:`Option` instance manually2 unmodified lines236 :param cls: the option class to instantiate. This defaults to237 :class:`Option`.238 """239 225- def decorator(f):240+ def decorator(f: FC) -> FC:241 # Issue 926, copy attrs, so pre-defined options can re-use the same cls=242 option_attrs = attrs.copy()243 244 if "help" in option_attrs:4 unmodified lines249 250 return decorator251 252 238-def confirmation_option(*param_decls, **kwargs):253+def confirmation_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]:254 """Add a ``--yes`` option which shows a prompt before continuing if255 not passed. If the prompt is declined, the program will exit.256 257 :param param_decls: One or more option names. Defaults to the single258 value ``"--yes"``.259 :param kwargs: Extra arguments are passed to :func:`option`.260 """261 247- def callback(ctx, param, value):262+ def callback(ctx: Context, param: Parameter, value: bool) -> None:263 if not value:264 ctx.abort()265 266 if not param_decls:6 unmodified lines273 kwargs.setdefault("help", "Confirm the action without prompting.")274 return option(*param_decls, **kwargs)275 276 262-def password_option(*param_decls, **kwargs):277+def password_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]:278 """Add a ``--password`` option which prompts for a password, hiding279 input and asking to enter the value again for confirmation.280 281 :param param_decls: One or more option names. Defaults to the single9 unmodified lines291 return option(*param_decls, **kwargs)292 293 294 def version_option(280- version=None,281- *param_decls,282- package_name=None,283- prog_name=None,284- message=None,285- **kwargs,286-):295+ version: t.Optional[str] = None,296+ *param_decls: str,297+ package_name: t.Optional[str] = None,298+ prog_name: t.Optional[str] = None,299+ message: t.Optional[str] = None,300+ **kwargs: t.Any,301+) -> t.Callable[[FC], FC]:302 """Add a ``--version`` option which immediately prints the version303 number and exits the program.304 305 If ``version`` is not provided, Click will try to detect it using30 unmodified lines336 message = _("%(prog)s, version %(version)s")337 338 if version is None and package_name is None:339 frame = inspect.currentframe()340+ assert frame is not None341+ assert frame.f_back is not None342 f_globals = frame.f_back.f_globals if frame is not None else None343 # break reference cycle344 # https://docs.python.org/3/library/inspect.html#the-interpreter-stack345 del frame6 unmodified lines352 353 if package_name:354 package_name = package_name.partition(".")[0]355 339- def callback(ctx, param, value):356+ def callback(ctx: Context, param: Parameter, value: bool) -> None:357 if not value or ctx.resilient_parsing:358 return359 360 nonlocal prog_name2 unmodified lines363 if prog_name is None:364 prog_name = ctx.find_root().info_name365 366 if version is None and package_name is not None:367+ metadata: t.Optional[types.ModuleType]368+369 try:351- from importlib import metadata370+ from importlib import metadata # type: ignore371 except ImportError:372 # Python < 3.8373 try:355- import importlib_metadata as metadata374+ import importlib_metadata as metadata # type: ignore375 except ImportError:376 metadata = None377 378 if metadata is None:1 unmodified line380 "Install 'importlib_metadata' to get the version on Python < 3.8."381 )382 383 try:365- version = metadata.version(package_name)366- except metadata.PackageNotFoundError:384+ version = metadata.version(package_name) # type: ignore385+ except metadata.PackageNotFoundError: # type: ignore386 raise RuntimeError(387 f"{package_name!r} is not installed. Try passing"388 " 'package_name' instead."389 )3 unmodified lines393 f"Could not determine the version for {package_name!r} automatically."394 )395 396 echo(397+ t.cast(str, message)378- message % {"prog": prog_name, "package": package_name, "version": version},398+ % {"prog": prog_name, "package": package_name, "version": version},399 color=ctx.color,400 )401 ctx.exit()402 7 unmodified lines410 kwargs["callback"] = callback411 return option(*param_decls, **kwargs)412 413 394-def help_option(*param_decls, **kwargs):414+def help_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]:415 """Add a ``--help`` option which immediately prints the help page416 and exits the program.417 418 This is usually unnecessary, as the ``--help`` option is added to4 unmodified lines423 value ``"--help"``.424 :param kwargs: Extra arguments are passed to :func:`option`.425 """426 407- def callback(ctx, param, value):427+ def callback(ctx: Context, param: Parameter, value: bool) -> None:428 if not value or ctx.resilient_parsing:429 return430 431 echo(ctx.get_help(), color=ctx.color)11 unmodified linesmodified:src/click/exceptions.py+57 added-26 removed
1 import os2+import typing as t3 from gettext import gettext as _4 from gettext import ngettext5 6 from ._compat import get_text_stderr7 from .utils import echo8 9+if t.TYPE_CHECKING:10+ from .core import Context11+ from .core import Parameter12 9-def _join_param_hints(param_hint):10- if isinstance(param_hint, (tuple, list)):13+14+def _join_param_hints(15+ param_hint: t.Optional[t.Union[t.Sequence[str], str]]16+) -> t.Optional[str]:17+ if param_hint is not None and not isinstance(param_hint, str):18 return " / ".join(repr(x) for x in param_hint)19+20 return param_hint21 22 23 class ClickException(Exception):1 unmodified line25 26 #: The exit code for this exception.27 exit_code = 128 21- def __init__(self, message):29+ def __init__(self, message: str) -> None:30 super().__init__(message)31 self.message = message32 25- def format_message(self):33+ def format_message(self) -> str:34 return self.message35 28- def __str__(self):36+ def __str__(self) -> str:37 return self.message38 31- def show(self, file=None):39+ def show(self, file: t.Optional[t.IO] = None) -> None:40 if file is None:41 file = get_text_stderr()42+43 echo(_("Error: {message}").format(message=self.format_message()), file=file)44 45 46 class UsageError(ClickException):6 unmodified lines53 """54 55 exit_code = 256 48- def __init__(self, message, ctx=None):57+ def __init__(self, message: str, ctx: t.Optional["Context"] = None) -> None:58 super().__init__(message)59 self.ctx = ctx60 self.cmd = self.ctx.command if self.ctx else None61 53- def show(self, file=None):62+ def show(self, file: t.Optional[t.IO] = None) -> None:63 if file is None:64 file = get_text_stderr()65 color = None66 hint = ""58- if self.cmd is not None and self.cmd.get_help_option(self.ctx) is not None:67+ if (68+ self.ctx is not None69+ and self.ctx.command.get_help_option(self.ctx) is not None70+ ):71 hint = _("Try '{command} {option}' for help.").format(72 command=self.ctx.command_path, option=self.ctx.help_option_names[0]73 )74 hint = f"{hint}\n"24 unmodified lines99 a string it's used as such, if it's a list then100 each item is quoted and separated.101 """102 91- def __init__(self, message, ctx=None, param=None, param_hint=None):103+ def __init__(104+ self,105+ message: str,106+ ctx: t.Optional["Context"] = None,107+ param: t.Optional["Parameter"] = None,108+ param_hint: t.Optional[str] = None,109+ ) -> None:110 super().__init__(message, ctx)111 self.param = param112 self.param_hint = param_hint113 96- def format_message(self):114+ def format_message(self) -> str:115 if self.param_hint is not None:116 param_hint = self.param_hint117 elif self.param is not None:100- param_hint = self.param.get_error_hint(self.ctx)118+ param_hint = self.param.get_error_hint(self.ctx) # type: ignore119 else:120 return _("Invalid value: {message}").format(message=self.message)121 122 return _("Invalid value for {param_hint}: {message}").format(13 unmodified lines136 ``'option'`` or ``'argument'``.137 """138 139 def __init__(122- self, message=None, ctx=None, param=None, param_hint=None, param_type=None123- ):124- super().__init__(message, ctx, param, param_hint)140+ self,141+ message: t.Optional[str] = None,142+ ctx: t.Optional["Context"] = None,143+ param: t.Optional["Parameter"] = None,144+ param_hint: t.Optional[str] = None,145+ param_type: t.Optional[str] = None,146+ ) -> None:147+ super().__init__(message or "", ctx, param, param_hint)148 self.param_type = param_type149 127- def format_message(self):150+ def format_message(self) -> str:151 if self.param_hint is not None:129- param_hint = self.param_hint152+ param_hint: t.Optional[str] = self.param_hint153 elif self.param is not None:131- param_hint = self.param.get_error_hint(self.ctx)154+ param_hint = self.param.get_error_hint(self.ctx) # type: ignore155 else:156 param_hint = None157 158 param_hint = _join_param_hints(param_hint)25 unmodified lines184 missing = _("Missing {param_type}").format(param_type=param_type)185 186 return f"{missing}{param_hint}.{msg}"187 165- def __str__(self):166- if self.message is None:188+ def __str__(self) -> str:189+ if not self.message:190 param_name = self.param.name if self.param else None191 return _("Missing parameter: {param_name}").format(param_name=param_name)192 else:193 return self.message5 unmodified lines199 200 .. versionadded:: 4.0201 """202 180- def __init__(self, option_name, message=None, possibilities=None, ctx=None):203+ def __init__(204+ self,205+ option_name: str,206+ message: t.Optional[str] = None,207+ possibilities: t.Optional[t.Sequence[str]] = None,208+ ctx: t.Optional["Context"] = None,209+ ) -> None:210 if message is None:211 message = _("No such option: {name}").format(name=option_name)212 213 super().__init__(message, ctx)214 self.option_name = option_name215 self.possibilities = possibilities216 188- def format_message(self):217+ def format_message(self) -> str:218 if not self.possibilities:219 return self.message220 221 possibility_str = ", ".join(sorted(self.possibilities))14 unmodified lines236 237 :param option_name: the name of the option being used incorrectly.238 """239 211- def __init__(self, option_name, message, ctx=None):240+ def __init__(241+ self, option_name: str, message: str, ctx: t.Optional["Context"] = None242+ ) -> None:243 super().__init__(message, ctx)244 self.option_name = option_name245 246 8 unmodified lines255 256 class FileError(ClickException):257 """Raised if a file cannot be opened."""258 228- def __init__(self, filename, hint=None):259+ def __init__(self, filename: str, hint: t.Optional[str] = None) -> None:260 if hint is None:261 hint = _("unknown error")262 263 super().__init__(hint)264 self.ui_filename = os.fsdecode(filename)265 self.filename = filename266 236- def format_message(self):267+ def format_message(self) -> str:268 return _("Could not open file {filename!r}: {message}").format(269 filename=self.ui_filename, message=self.message270 )271 10 unmodified lines282 """283 284 __slots__ = ("exit_code",)285 255- def __init__(self, code=0):286+ def __init__(self, code: int = 0) -> None:287 self.exit_code = codemodified:src/click/formatting.py+46 added-26 removed
7 unmodified lines8 # Can force a width. This is used by the test system9 FORCED_WIDTH: t.Optional[int] = None10 11 12-def measure_table(rows):13- widths = {}12+def measure_table(rows: t.Iterable[t.Tuple[str, str]]) -> t.Tuple[int, ...]:13+ widths: t.Dict[int, int] = {}14+15 for row in rows:16 for idx, col in enumerate(row):17 widths[idx] = max(widths.get(idx, 0), term_len(col))18+19 return tuple(y for x, y in sorted(widths.items()))20 21 20-def iter_rows(rows, col_count):22+def iter_rows(23+ rows: t.Iterable[t.Tuple[str, str]], col_count: int24+) -> t.Iterator[t.Tuple[str, ...]]:25 for row in rows:22- row = tuple(row)26 yield row + ("",) * (col_count - len(row))27 28 29 def wrap_text(27- text, width=78, initial_indent="", subsequent_indent="", preserve_paragraphs=False28-):30+ text: str,31+ width: int = 78,32+ initial_indent: str = "",33+ subsequent_indent: str = "",34+ preserve_paragraphs: bool = False,35+) -> str:36 """A helper function that intelligently wraps text. By default, it37 assumes that it operates on a single paragraph of text but if the38 `preserve_paragraphs` parameter is provided it will intelligently39 handle paragraphs (defined by two empty lines).22 unmodified lines62 )63 if not preserve_paragraphs:64 return wrapper.fill(text)65 59- p = []60- buf = []66+ p: t.List[t.Tuple[int, bool, str]] = []67+ buf: t.List[str] = []68 indent = None69 63- def _flush_par():70+ def _flush_par() -> None:71 if not buf:72 return73 if buf[0].strip() == "\b":74 p.append((indent or 0, True, "\n".join(buf[1:])))35 unmodified lines110 :param width: the width for the text. This defaults to the terminal111 width clamped to a maximum of 78.112 """113 107- def __init__(self, indent_increment=2, width=None, max_width=None):114+ def __init__(115+ self,116+ indent_increment: int = 2,117+ width: t.Optional[int] = None,118+ max_width: t.Optional[int] = None,119+ ) -> None:120 import shutil121 122 self.indent_increment = indent_increment123 if max_width is None:3 unmodified lines127 if width is None:128 width = max(min(shutil.get_terminal_size().columns, max_width) - 2, 50)129 self.width = width130 self.current_indent = 0119- self.buffer = []131+ self.buffer: t.List[str] = []132 121- def write(self, string):133+ def write(self, string: str) -> None:134 """Writes a unicode string into the internal buffer."""135 self.buffer.append(string)136 125- def indent(self):137+ def indent(self) -> None:138 """Increases the indentation."""139 self.current_indent += self.indent_increment140 129- def dedent(self):141+ def dedent(self) -> None:142 """Decreases the indentation."""143 self.current_indent -= self.indent_increment144 133- def write_usage(self, prog, args="", prefix=None):145+ def write_usage(146+ self, prog: str, args: str = "", prefix: t.Optional[str] = None147+ ) -> None:148 """Writes a usage line into the buffer.149 150 :param prog: the program name.151 :param args: whitespace separated list of arguments.29 unmodified lines181 )182 183 self.write("\n")184 171- def write_heading(self, heading):185+ def write_heading(self, heading: str) -> None:186 """Writes a heading into the buffer."""187 self.write(f"{'':>{self.current_indent}}{heading}:\n")188 175- def write_paragraph(self):189+ def write_paragraph(self) -> None:190 """Writes a paragraph into the buffer."""191 if self.buffer:192 self.write("\n")193 180- def write_text(self, text):194+ def write_text(self, text: str) -> None:195 """Writes re-indented text into the buffer. This rewraps and196 preserves paragraphs.197 """198 text_width = max(self.width - self.current_indent, 11)8 unmodified lines207 )208 )209 self.write("\n")210 197- def write_dl(self, rows, col_max=30, col_spacing=2):211+ def write_dl(212+ self,213+ rows: t.Sequence[t.Tuple[str, str]],214+ col_max: int = 30,215+ col_spacing: int = 2,216+ ) -> None:217 """Writes a definition list into the buffer. This is how options218 and commands are usually formatted.219 220 :param rows: a list of two item tuples for the terms and values.31 unmodified lines252 else:253 self.write("\n")254 255 @contextmanager237- def section(self, name):256+ def section(self, name: str) -> t.Iterator[None]:257 """Helpful context manager that writes a paragraph, a heading,258 and the indents.259 260 :param name: the section name that is written as heading.6 unmodified lines267 finally:268 self.dedent()269 270 @contextmanager252- def indentation(self):271+ def indentation(self) -> t.Iterator[None]:272 """A context manager that increases the indentation."""273 self.indent()274 try:275 yield276 finally:277 self.dedent()278 260- def getvalue(self):279+ def getvalue(self) -> str:280 """Returns the buffer contents."""281 return "".join(self.buffer)282 283 265-def join_options(options):284+def join_options(options: t.Sequence[str]) -> t.Tuple[str, bool]:285 """Given a list of option strings this joins them in the most appropriate286 way and returns them in the form ``(formatted_string,287 any_prefix_is_slash)`` where the second item in the tuple is a flag that288 indicates if any of the option prefixes was a slash.289 """290 rv = []291 any_prefix_is_slash = False292+293 for opt in options:294 prefix = split_opt(opt)[0]295+296 if prefix == "/":297 any_prefix_is_slash = True298+299 rv.append((len(prefix), opt))300 301 rv.sort(key=lambda x: x[0])280-281- rv = ", ".join(x[1] for x in rv)282- return rv, any_prefix_is_slash302+ return ", ".join(x[1] for x in rv), any_prefix_is_slashmodified:src/click/globals.py+27 added-5 removed
1+import typing2+import typing as t3 from threading import local4 5+if t.TYPE_CHECKING:6+ import typing_extensions as te7+ from .core import Context8+9 _local = local()10 11 6-def get_current_context(silent=False):12+@typing.overload13+def get_current_context(silent: "te.Literal[False]" = False) -> "Context":14+ ...15+16+17+@typing.overload18+def get_current_context(silent: bool = ...) -> t.Optional["Context"]:19+ ...20+21+22+def get_current_context(silent: bool = False) -> t.Optional["Context"]: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 be7 unmodified lines34 is available. The default behavior is to raise a35 :exc:`RuntimeError`.36 """37 try:22- return _local.stack[-1]38+ return t.cast("Context", _local.stack[-1])39 except (AttributeError, IndexError):40 if not silent:41 raise RuntimeError("There is no active click context.")42 43+ return None44 45+28-def push_context(ctx):46+def push_context(ctx: "Context") -> None:47 """Pushes a new context to the current stack."""48 _local.__dict__.setdefault("stack", []).append(ctx)49 50 33-def pop_context():51+def pop_context() -> None:52 """Removes the top level from the stack."""53 _local.stack.pop()54 55 38-def resolve_color_default(color=None):56+def resolve_color_default(color: t.Optional[bool] = None) -> t.Optional[bool]: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 """61 if color is not None:62 return color63+64 ctx = get_current_context(silent=True)65+66 if ctx is not None:67 return ctx.color68+69+ return Nonemodified:src/click/parser.py+90 added-42 removed
19 unmodified lines20 # This code uses parts of optparse written by Gregory P. Ward and21 # maintained by the Python Software Foundation.22 # Copyright 2001-2006 Gregory P. Ward23 # Copyright 2002-2006 Python Software Foundation24+import typing as t25 from collections import deque26 from gettext import gettext as _27 from gettext import ngettext28 1 unmodified line30 from .exceptions import BadOptionUsage31 from .exceptions import NoSuchOption32 from .exceptions import UsageError33 34+if t.TYPE_CHECKING:35+ from .core import Argument as CoreArgument36+ from .core import Context37+ from .core import Option as CoreOption38+ from .core import Parameter as CoreParameter39+40+V = t.TypeVar("V")41+42 # Sentinel value that indicates an option was passed as a flag without a43 # value but is not a flag option. Option.consume_value uses this to44 # prompt or use the flag_value.45 _flag_needs_value = object()46 47 39-def _unpack_args(args, nargs_spec):48+def _unpack_args(49+ args: t.Sequence[str], nargs_spec: t.Sequence[int]50+) -> t.Tuple[t.Sequence[t.Union[str, t.Sequence[t.Optional[str]], None]], t.List[str]]:51 """Given an iterable of arguments and an iterable of nargs specifications,52 it returns a tuple with all the unpacked arguments at the first index53 and all remaining arguments as the second.54 3 unmodified lines58 Missing items are filled with `None`.59 """60 args = deque(args)61 nargs_spec = deque(nargs_spec)51- rv = []52- spos = None62+ rv: t.List[t.Union[str, t.Tuple[t.Optional[str], ...], None]] = []63+ spos: t.Optional[int] = None64 54- def _fetch(c):65+ def _fetch(c: t.Deque[V]) -> t.Optional[V]:66 try:67 if spos is None:68 return c.popleft()69 else:2 unmodified lines72 return None73 74 while nargs_spec:75 nargs = _fetch(nargs_spec)76+77+ if nargs is None:78+ continue79+80 if nargs == 1:81 rv.append(_fetch(args))82 elif nargs > 1:83 x = [_fetch(args) for _ in range(nargs)]84+85 # If we're reversed, we're pulling in the arguments in reverse,86 # so we need to turn them around.87 if spos is not None:88 x.reverse()89+90 rv.append(tuple(x))91 elif nargs < 0:92 if spos is not None:93 raise TypeError("Cannot have two nargs < 0")94+95 spos = len(rv)96 rv.append(None)97 98 # spos is the position of the wildcard (star). If it's not `None`,5 unmodified lines104 105 return tuple(rv), list(args)106 107 90-def split_opt(opt):108+def split_opt(opt: str) -> t.Tuple[str, str]:109 first = opt[:1]110 if first.isalnum():111 return "", opt112 if opt[1:2] == first:113 return opt[:2], opt[2:]114 return first, opt[1:]115 116 99-def normalize_opt(opt, ctx):117+def normalize_opt(opt: str, ctx: t.Optional["Context"]) -> str:118 if ctx is None or ctx.token_normalize_func is None:119 return opt120 prefix, opt = split_opt(opt)121 return f"{prefix}{ctx.token_normalize_func(opt)}"122 123 106-def split_arg_string(string):124+def split_arg_string(string: str) -> t.List[str]:125 """Split an argument string as with :func:`shlex.split`, but don't126 fail if the string is incomplete. Ignores a missing closing quote or127 incomplete escape sequence and uses the partial token as-is.128 26 unmodified lines155 return out156 157 158 class Option:141- def __init__(self, opts, dest, action=None, nargs=1, const=None, obj=None):159+ def __init__(160+ self,161+ obj: "CoreOption",162+ opts: t.Sequence[str],163+ dest: t.Optional[str],164+ action: t.Optional[str] = None,165+ nargs: int = 1,166+ const: t.Optional[t.Any] = None,167+ ):168 self._short_opts = []169 self._long_opts = []170 self.prefixes = set()171 17 unmodified lines189 self.const = const190 self.obj = obj191 192 @property167- def takes_value(self):193+ def takes_value(self) -> bool:194 return self.action in ("store", "append")195 170- def process(self, value, state):196+ def process(self, value: str, state: "ParsingState") -> None:197 if self.action == "store":172- state.opts[self.dest] = value198+ state.opts[self.dest] = value # type: ignore199 elif self.action == "store_const":174- state.opts[self.dest] = self.const200+ state.opts[self.dest] = self.const # type: ignore201 elif self.action == "append":176- state.opts.setdefault(self.dest, []).append(value)202+ state.opts.setdefault(self.dest, []).append(value) # type: ignore203 elif self.action == "append_const":178- state.opts.setdefault(self.dest, []).append(self.const)204+ state.opts.setdefault(self.dest, []).append(self.const) # type: ignore205 elif self.action == "count":180- state.opts[self.dest] = state.opts.get(self.dest, 0) + 1206+ state.opts[self.dest] = state.opts.get(self.dest, 0) + 1 # type: ignore207 else:208 raise ValueError(f"unknown action '{self.action}'")209 state.order.append(self.obj)210 211 212 class Argument:187- def __init__(self, dest, nargs=1, obj=None):213+ def __init__(self, obj: "CoreArgument", dest: t.Optional[str], nargs: int = 1):214 self.dest = dest215 self.nargs = nargs216 self.obj = obj217 192- def process(self, value, state):218+ def process(219+ self,220+ value: t.Union[t.Optional[str], t.Sequence[t.Optional[str]]],221+ state: "ParsingState",222+ ) -> None:223 if self.nargs > 1:224+ assert value is not None225 holes = sum(1 for x in value if x is None)226 if holes == len(value):227 value = None228 elif holes != 0:5 unmodified lines234 235 if self.nargs == -1 and self.obj.envvar is not None:236 value = None237 207- state.opts[self.dest] = value238+ state.opts[self.dest] = value # type: ignore239 state.order.append(self.obj)240 241 242 class ParsingState:212- def __init__(self, rargs):213- self.opts = {}214- self.largs = []243+ def __init__(self, rargs: t.List[str]) -> None:244+ self.opts: t.Dict[str, t.Any] = {}245+ self.largs: t.List[str] = []246 self.rargs = rargs216- self.order = []247+ self.order: t.List["CoreParameter"] = []248 249 250 class OptionParser:251 """The option parser is an internal class that is ultimately used to8 unmodified lines260 :param ctx: optionally the :class:`~click.Context` where this parser261 should go with.262 """263 233- def __init__(self, ctx=None):264+ def __init__(self, ctx: t.Optional["Context"] = None) -> None:265 #: The :class:`~click.Context` for this parser. This might be266 #: `None` for some advanced use cases.267 self.ctx = ctx268 #: This controls how the parser deals with interspersed arguments.5 unmodified lines274 #: default it will error out (which is sensible), but there is a275 #: second mode where it will ignore it and continue processing276 #: after shifting all the unknown options into the resulting args.277 self.ignore_unknown_options = False278+279 if ctx is not None:280 self.allow_interspersed_args = ctx.allow_interspersed_args281 self.ignore_unknown_options = ctx.ignore_unknown_options250- self._short_opt = {}251- self._long_opt = {}282+283+ self._short_opt: t.Dict[str, Option] = {}284+ self._long_opt: t.Dict[str, Option] = {}285 self._opt_prefixes = {"-", "--"}253- self._args = []286+ self._args: t.List[Argument] = []287 255- def add_option(self, opts, dest, action=None, nargs=1, const=None, obj=None):288+ def add_option(289+ self,290+ obj: "CoreOption",291+ opts: t.Sequence[str],292+ dest: t.Optional[str],293+ action: t.Optional[str] = None,294+ nargs: int = 1,295+ const: t.Optional[t.Any] = None,296+ ) -> None:297 """Adds a new option named `dest` to the parser. The destination298 is not inferred (unlike with optparse) and needs to be explicitly299 provided. Action can be any of ``store``, ``store_const``,300 ``append``, ``appnd_const`` or ``count``.301 302 The `obj` can be used to identify the option in the order list303 that is returned from the parser.304 """264- if obj is None:265- obj = dest305 opts = [normalize_opt(opt, self.ctx) for opt in opts]267- option = Option(opts, dest, action=action, nargs=nargs, const=const, obj=obj)306+ option = Option(obj, opts, dest, action=action, nargs=nargs, const=const)307 self._opt_prefixes.update(option.prefixes)308 for opt in option._short_opts:309 self._short_opt[opt] = option310 for opt in option._long_opts:311 self._long_opt[opt] = option312 274- def add_argument(self, dest, nargs=1, obj=None):313+ def add_argument(314+ self, obj: "CoreArgument", dest: t.Optional[str], nargs: int = 1315+ ) -> None:316 """Adds a positional argument named `dest` to the parser.317 318 The `obj` can be used to identify the option in the order list319 that is returned from the parser.320 """280- if obj is None:281- obj = dest282- self._args.append(Argument(dest=dest, nargs=nargs, obj=obj))321+ self._args.append(Argument(obj, dest=dest, nargs=nargs))322 284- def parse_args(self, args):323+ def parse_args(324+ self, args: t.List[str]325+ ) -> t.Tuple[t.Dict[str, t.Any], t.List[str], t.List["CoreParameter"]]:326 """Parses positional arguments and returns ``(values, args, order)``327 for the parsed options and arguments as well as the leftover328 arguments if there are any. The order is a list of objects as they329 appear on the command line. If arguments appear multiple times they7 unmodified lines337 if self.ctx is None or not self.ctx.resilient_parsing:338 raise339 return state.opts, state.largs, state.order340 300- def _process_args_for_args(self, state):341+ def _process_args_for_args(self, state: ParsingState) -> None:342 pargs, args = _unpack_args(343 state.largs + state.rargs, [x.nargs for x in self._args]344 )345 2 unmodified lines348 349 state.largs = args350 state.rargs = []351 311- def _process_args_for_options(self, state):352+ def _process_args_for_options(self, state: ParsingState) -> None:353 while state.rargs:354 arg = state.rargs.pop(0)355 arglen = len(arg)356 # Double dashes always handled explicitly regardless of what27 unmodified lines384 # If allow_interspersed_args is false, largs will always be385 # *empty* -- still a subset of [arg0, ..., arg(i-1)], but386 # not a very interesting subset!387 347- def _match_long_opt(self, opt, explicit_value, state):388+ def _match_long_opt(389+ self, opt: str, explicit_value: t.Optional[str], state: ParsingState390+ ) -> None:391 if opt not in self._long_opt:392 from difflib import get_close_matches393 394 possibilities = get_close_matches(opt, self._long_opt)19 unmodified lines414 value = None415 416 option.process(value, state)417 375- def _match_short_opt(self, arg, state):418+ def _match_short_opt(self, arg: str, state: ParsingState) -> None:419 stop = False420 i = 1421 prefix = arg[0]422 unknown_options = []31 unmodified lines454 # that can be achieved while still ignoring unknown arguments.455 if self.ignore_unknown_options and unknown_options:456 state.largs.append(f"{prefix}{''.join(unknown_options)}")457 415- def _get_value_from_state(self, option_name, option, state):458+ def _get_value_from_state(459+ self, option_name: str, option: Option, state: ParsingState460+ ) -> t.Any:461 nargs = option.nargs462 463 if len(state.rargs) < nargs:464 if option.obj._flag_needs_value:27 unmodified lines492 del state.rargs[:nargs]493 494 return value495 451- def _process_opts(self, arg, state):496+ def _process_opts(self, arg: str, state: ParsingState) -> None:497 explicit_value = None498 # Long option handling happens in two parts. The first part is499 # supporting explicitly attached values. In any case, we will try500 # to long match the option first.15 unmodified lines516 # (applies to "--foo" for instance), we do not dispatch to the517 # short option code and will instead raise the no option518 # error.519 if arg[:2] not in self._opt_prefixes:475- return self._match_short_opt(arg, state)520+ self._match_short_opt(arg, state)521+ return522+523 if not self.ignore_unknown_options:524 raise525+526 state.largs.append(arg)added:src/click/py.typed
modified:src/click/shell_completion.py+65 added-36 removed
2 unmodified lines3 import typing as t4 from gettext import gettext as _5 6 from .core import Argument7+from .core import BaseCommand8+from .core import Context9 from .core import MultiCommand10 from .core import Option11+from .core import Parameter12 from .core import ParameterSource13 from .parser import split_arg_string14 from .utils import echo15 16 14-def shell_complete(cli, ctx_args, prog_name, complete_var, instruction):17+def shell_complete(18+ cli: BaseCommand,19+ ctx_args: t.Dict[str, t.Any],20+ prog_name: str,21+ complete_var: str,22+ instruction: str,23+) -> int:24 """Perform shell completion for the given CLI program.25 26 :param cli: Command being called.27 :param ctx_args: Extra arguments to pass to44 unmodified lines72 """73 74 __slots__ = ("value", "type", "help", "_info")75 67- def __init__(self, value, type="plain", help=None, **kwargs):76+ def __init__(77+ self,78+ value: t.Any,79+ type: str = "plain",80+ help: t.Optional[str] = None,81+ **kwargs: t.Any,82+ ) -> None:83 self.value = value84 self.type = type85 self.help = help86 self._info = kwargs87 73- def __getattr__(self, name):88+ def __getattr__(self, name: str) -> t.Any:89 return self._info.get(name)90 91 92 # Only Bash >= 4.4 has the nosort option.106 unmodified lines199 200 .. versionadded:: 8.0201 """202 188- name: t.ClassVar[t.Optional[str]] = None203+ name: t.ClassVar[str]204 """Name to register the shell as with :func:`add_completion_class`.205 This is used in completion instructions (``{name}_source`` and206 ``{name}_complete``).207 """208+193- source_template: t.ClassVar[t.Optional[str]] = None209+ source_template: t.ClassVar[str]210 """Completion script template formatted by :meth:`source`. This must211 be provided by subclasses.212 """213 198- def __init__(self, cli, ctx_args, prog_name, complete_var):214+ def __init__(215+ self,216+ cli: BaseCommand,217+ ctx_args: t.Dict[str, t.Any],218+ prog_name: str,219+ complete_var: str,220+ ) -> None:221 self.cli = cli222 self.ctx_args = ctx_args223 self.prog_name = prog_name224 self.complete_var = complete_var225 226 @property205- def func_name(self):227+ def func_name(self) -> str:228 """The name of the shell function defined by the completion229 script.230 """231 safe_name = re.sub(r"\W*", "", self.prog_name.replace("-", "_"), re.ASCII)232 return f"_{safe_name}_completion"233 212- def source_vars(self):234+ def source_vars(self) -> t.Dict[str, t.Any]:235 """Vars for formatting :attr:`source_template`.236 237 By default this provides ``complete_func``, ``complete_var``,238 and ``prog_name``.3 unmodified lines242 "complete_var": self.complete_var,243 "prog_name": self.prog_name,244 }245 224- def source(self):246+ def source(self) -> str:247 """Produce the shell script that defines the completion248 function. By default this ``%``-style formats249 :attr:`source_template` with the dict returned by250 :meth:`source_vars`.251 """252 return self.source_template % self.source_vars()253 232- def get_completion_args(self):254+ def get_completion_args(self) -> t.Tuple[t.List[str], str]:255 """Use the env vars defined by the shell script to return a256 tuple of ``args, incomplete``. This must be implemented by257 subclasses.258 """259 raise NotImplementedError260 239- def get_completions(self, args, incomplete):261+ def get_completions(262+ self, args: t.List[str], incomplete: str263+ ) -> t.List[CompletionItem]:264 """Determine the context and last complete command or parameter265 from the complete args. Call that object's ``shell_complete``266 method to get the completions for the incomplete value.267 268 :param args: List of complete args before the incomplete value.269 :param incomplete: Value being completed. May be empty.270 """271 ctx = _resolve_context(self.cli, self.ctx_args, self.prog_name, args)248-249- if ctx is None:250- return []251-272 obj, incomplete = _resolve_incomplete(ctx, args, incomplete)273 return obj.shell_complete(ctx, incomplete)274 255- def format_completion(self, item):275+ def format_completion(self, item: CompletionItem) -> str:276 """Format a completion item into the form recognized by the277 shell script. This must be implemented by subclasses.278 279 :param item: Completion item to format.280 """281 raise NotImplementedError282 263- def complete(self):283+ def complete(self) -> str:284 """Produce the completion data to send back to the shell.285 286 By default this calls :meth:`get_completion_args`, gets the287 completions, then calls :meth:`format_completion` for each10 unmodified lines298 299 name = "bash"300 source_template = _SOURCE_BASH301 282- def _check_version(self):302+ def _check_version(self) -> None:303 import subprocess304 305 output = subprocess.run(["bash", "--version"], stdout=subprocess.PIPE)306 match = re.search(r"version (\d)\.(\d)\.\d", output.stdout.decode())12 unmodified lines319 raise RuntimeError(320 _("Couldn't detect Bash version, shell completion is not supported.")321 )322 303- def source(self):323+ def source(self) -> str:324 self._check_version()325 return super().source()326 307- def get_completion_args(self):327+ def get_completion_args(self) -> t.Tuple[t.List[str], str]:328 cwords = split_arg_string(os.environ["COMP_WORDS"])329 cword = int(os.environ["COMP_CWORD"])330 args = cwords[1:cword]331 13 unmodified lines345 346 name = "zsh"347 source_template = _SOURCE_ZSH348 329- def get_completion_args(self):349+ def get_completion_args(self) -> t.Tuple[t.List[str], str]:350 cwords = split_arg_string(os.environ["COMP_WORDS"])351 cword = int(os.environ["COMP_CWORD"])352 args = cwords[1:cword]353 13 unmodified lines367 368 name = "fish"369 source_template = _SOURCE_FISH370 351- def get_completion_args(self):371+ def get_completion_args(self) -> t.Tuple[t.List[str], str]:372 cwords = split_arg_string(os.environ["COMP_WORDS"])373 incomplete = os.environ["COMP_CWORD"]374 args = cwords[1:]375 10 unmodified lines386 387 return f"{item.type},{item.value}"388 389 370-_available_shells = {390+_available_shells: t.Dict[str, t.Type[ShellComplete]] = {391 "bash": BashComplete,392 "fish": FishComplete,393 "zsh": ZshComplete,394 }395 396 377-def add_completion_class(cls, name=None):397+def add_completion_class(398+ cls: t.Type[ShellComplete], name: t.Optional[str] = None399+) -> None:400 """Register a :class:`ShellComplete` subclass under the given name.401 The name will be provided by the completion instruction environment402 variable during completion.403 7 unmodified lines411 412 _available_shells[name] = cls413 414 393-def get_completion_class(shell):415+def get_completion_class(shell: str) -> t.Optional[t.Type[ShellComplete]]:416 """Look up a registered :class:`ShellComplete` subclass by the name417 provided by the completion instruction environment variable. If the418 name isn't registered, returns ``None``.419 1 unmodified line421 """422 return _available_shells.get(shell)423 424 403-def _is_incomplete_argument(ctx, param):425+def _is_incomplete_argument(ctx: Context, param: Parameter) -> bool:426 """Determine if the given parameter is an argument that can still427 accept values.428 429 :param ctx: Invocation context for the command represented by the2 unmodified lines432 """433 if not isinstance(param, Argument):434 return False435 436+ assert param.name is not None437 value = ctx.params[param.name]438 return (439 param.nargs == -1440 or ctx.get_parameter_source(param.name) is not ParameterSource.COMMANDLINE4 unmodified lines445 )446 )447 448 426-def _start_of_option(value):449+def _start_of_option(value: str) -> bool:450 """Check if the value looks like the start of an option."""428- return value and not value[0].isalnum()451+ return not value[0].isalnum() if value else False452 453 431-def _is_incomplete_option(args, param):454+def _is_incomplete_option(args: t.List[str], param: Parameter) -> bool:455 """Determine if the given parameter is an option that needs a value.456 457 :param args: List of complete args before the incomplete value.458 :param param: Option object being checked.15 unmodified lines474 475 return last_option is not None and last_option in param.opts476 477 455-def _resolve_context(cli, ctx_args, prog_name, args):478+def _resolve_context(479+ cli: BaseCommand, ctx_args: t.Dict[str, t.Any], prog_name: str, args: t.List[str]480+) -> Context:481 """Produce the context hierarchy starting with the command and482 traversing the complete arguments. This only follows the commands,483 it doesn't trigger input prompts or callbacks.484 5 unmodified lines490 ctx = cli.make_context(prog_name, args.copy(), **ctx_args)491 args = ctx.protected_args + ctx.args492 493 while args:469- if isinstance(ctx.command, MultiCommand):470- if not ctx.command.chain:471- name, cmd, args = ctx.command.resolve_command(ctx, args)494+ command = ctx.command495 496+ if isinstance(command, MultiCommand):497+ if not command.chain:498+ name, cmd, args = command.resolve_command(ctx, args)499+500 if cmd is None:501 return ctx502 503 ctx = cmd.make_context(name, args, parent=ctx, resilient_parsing=True)504 args = ctx.protected_args + ctx.args505 else:506 while args:480- name, cmd, args = ctx.command.resolve_command(ctx, args)507+ name, cmd, args = command.resolve_command(ctx, args)508 509 if cmd is None:510 return ctx511 7 unmodified lines519 )520 args = sub_ctx.args521 522 ctx = sub_ctx496- args = sub_ctx.protected_args + sub_ctx.args523+ args = [*sub_ctx.protected_args, *sub_ctx.args]524 else:525 break526 527 return ctx528 529 503-def _resolve_incomplete(ctx, args, incomplete):530+def _resolve_incomplete(531+ ctx: Context, args: t.List[str], incomplete: str532+) -> t.Tuple[t.Union[BaseCommand, Parameter], str]:533 """Find the Click object that will handle the completion of the534 incomplete value. Return the object and the incomplete value.535 536 :param ctx: Invocation context for the command represented by38 unmodified linesmodified:src/click/termui.py+117 added-78 removed
1 unmodified line2 import io3 import itertools4 import os5 import sys6+import typing7 import typing as t8 from gettext import gettext as _9 9-from ._compat import is_bytes10 from ._compat import isatty11 from ._compat import strip_ansi12 from ._compat import WIN13 from .exceptions import Abort14 from .exceptions import UsageError15 from .globals import resolve_color_default16 from .types import Choice17 from .types import convert_type18+from .types import ParamType19 from .utils import echo20 from .utils import LazyFile21 22+if t.TYPE_CHECKING:23+ from ._termui_impl import ProgressBar24+25+V = t.TypeVar("V")26+27 # The prompt functions to use. The doc tools currently override these28 # functions to customize how they work.23-visible_prompt_func = input29+visible_prompt_func: t.Callable[[str], str] = input30 31 _ansi_colors = {32 "black": 30,33 "red": 31,15 unmodified lines49 }50 _ansi_reset_all = "\033[0m"51 52 47-def hidden_prompt_func(prompt):53+def hidden_prompt_func(prompt: str) -> str:54 import getpass55 56 return getpass.getpass(prompt)57 58 59 def _build_prompt(54- text, suffix, show_default=False, default=None, show_choices=True, type=None55-):60+ text: str,61+ suffix: str,62+ show_default: bool = False,63+ default: t.Optional[t.Any] = None,64+ show_choices: bool = True,65+ type: t.Optional[ParamType] = None,66+) -> str:67 prompt = text68 if type is not None and show_choices and isinstance(type, Choice):69 prompt += f" ({', '.join(map(str, type.choices))})"70 if default is not None and show_default:71 prompt = f"{prompt} [{_format_default(default)}]"72 return f"{prompt}{suffix}"73 74 64-def _format_default(default):75+def _format_default(default: t.Any) -> t.Any:76 if isinstance(default, (io.IOBase, LazyFile)) and hasattr(default, "name"):66- return default.name77+ return default.name # type: ignore78 79 return default80 81 82 def prompt(72- text,73- default=None,74- hide_input=False,75- confirmation_prompt=False,76- type=None,77- value_proc=None,78- prompt_suffix=": ",79- show_default=True,80- err=False,81- show_choices=True,82-):83+ text: str,84+ default: t.Optional[t.Any] = None,85+ hide_input: bool = False,86+ confirmation_prompt: t.Union[bool, str] = False,87+ type: t.Optional[ParamType] = None,88+ value_proc: t.Optional[t.Callable[[str], t.Any]] = None,89+ prompt_suffix: str = ": ",90+ show_default: bool = True,91+ err: bool = False,92+ show_choices: bool = True,93+) -> t.Any:94 """Prompts a user for input. This is a convenience function that can95 be used to prompt a user for input later.96 97 If the user aborts the input by sending a interrupt signal, this32 unmodified lines130 .. versionadded:: 4.0131 Added the `err` parameter.132 133 """123- result = None134 125- def prompt_func(text):135+ def prompt_func(text: str) -> str:136 f = hidden_prompt_func if hide_input else visible_prompt_func137 try:138 # Write the prompt separately so that we get nice139 # coloring through colorama on Windows19 unmodified lines159 if confirmation_prompt:160 if confirmation_prompt is True:161 confirmation_prompt = _("Repeat for confirmation")162 163+ confirmation_prompt = t.cast(str, confirmation_prompt)164 confirmation_prompt = _build_prompt(confirmation_prompt, prompt_suffix)165 155- while 1:156- while 1:166+ while True:167+ while True:168 value = prompt_func(prompt)169 if value:170 break171 elif default is not None:8 unmodified lines180 echo(_("Error: {e.message}").format(e=e), err=err) # noqa: B306181 continue182 if not confirmation_prompt:183 return result173- while 1:184+ while True:185+ confirmation_prompt = t.cast(str, confirmation_prompt)186 value2 = prompt_func(confirmation_prompt)187 if value2:188 break189 if value == value2:1 unmodified line191 echo(_("Error: The two entered values do not match."), err=err)192 193 194 def confirm(183- text, default=False, abort=False, prompt_suffix=": ", show_default=True, err=False184-):195+ text: str,196+ default: t.Optional[bool] = False,197+ abort: bool = False,198+ prompt_suffix: str = ": ",199+ show_default: bool = True,200+ err: bool = False,201+) -> bool:202 """Prompts for confirmation (yes/no question).203 204 If the user aborts the input by sending a interrupt signal this205 function will catch it and raise a :exc:`Abort` exception.20 unmodified lines226 show_default,227 "y/n" if default is None else ("Y/n" if default else "y/N"),228 )229 213- while 1:230+ while True:231 try:232 # Write the prompt separately so that we get nice233 # coloring through colorama on Windows234 echo(prompt, nl=False, err=err)14 unmodified lines249 raise Abort()250 return rv251 252 236-def get_terminal_size():253+def get_terminal_size() -> os.terminal_size:254 """Returns the current size of the terminal as tuple in the form255 ``(width, height)`` in columns and rows.256 257 .. deprecated:: 8.011 unmodified lines269 )270 return shutil.get_terminal_size()271 272 256-def echo_via_pager(text_or_generator, color=None):273+def echo_via_pager(274+ text_or_generator: t.Union[t.Iterable[str], t.Callable[[], t.Iterable[str]], str],275+ color: t.Optional[bool] = None,276+) -> None:277 """This function takes a text and shows it via an environment specific278 pager on stdout.279 280 .. versionchanged:: 3.06 unmodified lines287 """288 color = resolve_color_default(color)289 290 if inspect.isgeneratorfunction(text_or_generator):271- i = text_or_generator()291+ i = t.cast(t.Callable[[], t.Iterable[str]], text_or_generator)()292 elif isinstance(text_or_generator, str):293 i = [text_or_generator]294 else:275- i = iter(text_or_generator)295+ i = iter(t.cast(t.Iterable[str], text_or_generator))296 297 # convert every element of i to a text type if necessary298 text_generator = (el if isinstance(el, str) else str(el) for el in i)299 2 unmodified lines302 return pager(itertools.chain(text_generator, "\n"), color)303 304 305 def progressbar(286- iterable=None,287- length=None,288- label=None,289- show_eta=True,290- show_percent=None,291- show_pos=False,292- item_show_func=None,293- fill_char="#",294- empty_char="-",295- bar_template="%(label)s [%(bar)s] %(info)s",296- info_sep=" ",297- width=36,298- file=None,299- color=None,300- update_min_steps=1,301-):306+ iterable: t.Optional[t.Iterable[V]] = None,307+ length: t.Optional[int] = None,308+ label: t.Optional[str] = None,309+ show_eta: bool = True,310+ show_percent: t.Optional[bool] = None,311+ show_pos: bool = False,312+ item_show_func: t.Optional[t.Callable[[t.Optional[V]], t.Optional[str]]] = None,313+ fill_char: str = "#",314+ empty_char: str = "-",315+ bar_template: str = "%(label)s [%(bar)s] %(info)s",316+ info_sep: str = " ",317+ width: int = 36,318+ file: t.Optional[t.TextIO] = None,319+ color: t.Optional[bool] = None,320+ update_min_steps: int = 1,321+) -> "ProgressBar":322 """This function creates an iterable context manager that can be used323 to iterate over something while showing a progress bar. It will324 either iterate over the `iterable` or `length` items (that are counted325 up). While iteration happens, this function will print a rendered127 unmodified lines453 update_min_steps=update_min_steps,454 )455 456 437-def clear():457+def clear() -> None:458 """Clears the terminal screen. This will have the effect of clearing459 the whole visible space of the terminal and moving the cursor to the460 top left. This does not do anything if not connected to a terminal.461 6 unmodified lines468 else:469 sys.stdout.write("\033[2J\033[1;1H")470 471 452-def _interpret_color(color, offset=0):472+def _interpret_color(473+ color: t.Union[int, t.Tuple[int, int, int], str], offset: int = 0474+) -> str:475 if isinstance(color, int):476 return f"{38 + offset};5;{color:d}"477 478 if isinstance(color, (tuple, list)):3 unmodified lines482 return str(_ansi_colors[color] + offset)483 484 485 def style(464- text,465- fg=None,466- bg=None,467- bold=None,468- dim=None,469- underline=None,470- overline=None,471- italic=None,472- blink=None,473- reverse=None,474- strikethrough=None,475- reset=True,476-):486+ text: t.Any,487+ fg: t.Optional[t.Union[int, t.Tuple[int, int, int], str]] = None,488+ bg: t.Optional[t.Union[int, t.Tuple[int, int, int], str]] = None,489+ bold: t.Optional[bool] = None,490+ dim: t.Optional[bool] = None,491+ underline: t.Optional[bool] = None,492+ overline: t.Optional[bool] = None,493+ italic: t.Optional[bool] = None,494+ blink: t.Optional[bool] = None,495+ reverse: t.Optional[bool] = None,496+ strikethrough: t.Optional[bool] = None,497+ reset: bool = True,498+) -> str:499 """Styles a text with ANSI styles and returns the new string. By500 default the styling is self contained which means that at the end501 of the string a reset code is issued. This can be prevented by502 passing ``reset=False``.107 unmodified lines610 bits.append(_ansi_reset_all)611 return "".join(bits)612 613 592-def unstyle(text):614+def unstyle(text: str) -> str:615 """Removes ANSI styling information from a string. Usually it's not616 necessary to use this function as Click's echo function will617 automatically remove styling if necessary.618 3 unmodified lines622 """623 return strip_ansi(text)624 625 604-def secho(message=None, file=None, nl=True, err=False, color=None, **styles):626+def secho(627+ message: t.Optional[t.Any] = None,628+ file: t.Optional[t.IO] = None,629+ nl: bool = True,630+ err: bool = False,631+ color: t.Optional[bool] = None,632+ **styles: t.Any,633+) -> None:634 """This function combines :func:`echo` and :func:`style` into one635 call. As such the following two calls are the same::636 637 click.secho('Hello World!', fg='green')12 unmodified lines650 passed through without style applied.651 652 .. versionadded:: 2.0653 """625- if message is not None and not is_bytes(message):654+ if message is not None and not isinstance(message, (bytes, bytearray)):655 message = style(message, **styles)656 657 return echo(message, file=file, nl=nl, err=err, color=color)658 659 660 def edit(632- text=None, editor=None, env=None, require_save=True, extension=".txt", filename=None633-):661+ text: t.Optional[t.AnyStr] = None,662+ editor: t.Optional[str] = None,663+ env: t.Optional[t.Mapping[str, str]] = None,664+ require_save: bool = True,665+ extension: str = ".txt",666+ filename: t.Optional[str] = None,667+) -> t.Optional[t.AnyStr]:668 r"""Edits the given text in the defined editor. If an editor is given669 (should be the full path to the executable but the regular operating670 system search path is used for finding the executable) it overrides671 the detected editor. Optionally, some environment variables can be21 unmodified lines693 file as an indirection in that case.694 """695 from ._termui_impl import Editor696 663- editor = Editor(664- editor=editor, env=env, require_save=require_save, extension=extension665- )697+ ed = Editor(editor=editor, env=env, require_save=require_save, extension=extension)698+699 if filename is None:667- return editor.edit(text)668- editor.edit_file(filename)700+ return ed.edit(text)701 702+ ed.edit_file(filename)703+ return None704 671-def launch(url, wait=False, locate=False):705+706+def launch(url: str, wait: bool = False, locate: bool = False) -> int:707 """This function launches the given URL (or filename) in the default708 viewer application for this file type. If this is an executable, it709 might launch the executable in a new session. The return value is710 the exit code of the launched application. Usually, ``0`` indicates25 unmodified lines736 # for unittesting purposes.737 _getchar: t.Optional[t.Callable[[bool], str]] = None738 739 705-def getchar(echo=False):740+def getchar(echo: bool = False) -> str:741 """Fetches a single character from the terminal and returns it. This742 will always return a unicode character and under certain rare743 circumstances this might return more than one character. The744 situations which more than one character is returned is when for11 unmodified lines756 757 :param echo: if set to `True`, the character read will also show up on758 the terminal. The default is to not show it.759 """725- f = _getchar726- if f is None:760+ global _getchar761+762+ if _getchar is None:763 from ._termui_impl import getchar as f728- return f(echo)764 765+ _getchar = f766 731-def raw_terminal():767+ return _getchar(echo)768+769+770+def raw_terminal() -> t.ContextManager[int]:771 from ._termui_impl import raw_terminal as f772 773 return f()774 775 737-def pause(info=None, err=False):776+def pause(info: t.Optional[str] = None, err: bool = False) -> None:777 """This command stops execution and waits for the user to press any778 key to continue. This is similar to the Windows batch "pause"779 command. If the program is not run through a terminal, this command780 will instead do nothing.27 unmodified linesmodified:src/click/testing.py+102 added-69 removed
3 unmodified lines4 import shlex5 import shutil6 import sys7 import tempfile8+import typing as t9+from types import TracebackType10 11 from . import formatting12 from . import termui13 from . import utils14 from ._compat import _find_binary_reader15 16+if t.TYPE_CHECKING:17+ from .core import BaseCommand18 19+20 class EchoingStdin:16- def __init__(self, input, output):21+ def __init__(self, input: t.BinaryIO, output: t.BinaryIO) -> None:22 self._input = input23 self._output = output24 self._paused = False25 21- def __getattr__(self, x):26+ def __getattr__(self, x: str) -> t.Any:27 return getattr(self._input, x)28 24- def _echo(self, rv):29+ def _echo(self, rv: bytes) -> bytes:30 if not self._paused:31 self._output.write(rv)32 33 return rv34 30- def read(self, n=-1):35+ def read(self, n: int = -1) -> bytes:36 return self._echo(self._input.read(n))37 33- def read1(self, n=-1):34- return self._echo(self._input.read1(n))38+ def read1(self, n: int = -1) -> bytes:39+ return self._echo(self._input.read1(n)) # type: ignore40 36- def readline(self, n=-1):41+ def readline(self, n: int = -1) -> bytes:42 return self._echo(self._input.readline(n))43 39- def readlines(self):44+ def readlines(self) -> t.List[bytes]:45 return [self._echo(x) for x in self._input.readlines()]46 42- def __iter__(self):47+ def __iter__(self) -> t.Iterator[bytes]:48 return iter(self._echo(x) for x in self._input)49 45- def __repr__(self):50+ def __repr__(self) -> str:51 return repr(self._input)52 53 54 @contextlib.contextmanager50-def _pause_echo(stream):55+def _pause_echo(stream: t.Optional[EchoingStdin]) -> t.Iterator[None]:56 if stream is None:57 yield58 else:59 stream._paused = True1 unmodified line61 stream._paused = False62 63 64 class _NamedTextIOWrapper(io.TextIOWrapper):60- def __init__(self, buffer, name=None, mode=None, **kwargs):65+ def __init__(66+ self, buffer: t.BinaryIO, name: str, mode: str, **kwargs: t.Any67+ ) -> None:68 super().__init__(buffer, **kwargs)69 self._name = name70 self._mode = mode71 72 @property66- def name(self):73+ def name(self) -> str:74 return self._name75 76 @property70- def mode(self):77+ def mode(self) -> str:78 return self._mode79 80 74-def make_input_stream(input, charset):81+def make_input_stream(82+ input: t.Optional[t.Union[str, bytes, t.IO]], charset: str83+) -> t.BinaryIO:84 # Is already an input stream.85 if hasattr(input, "read"):77- rv = _find_binary_reader(input)86+ rv = _find_binary_reader(t.cast(t.IO, input))87 88 if rv is not None:89 return rv90 91 raise TypeError("Could not find binary reader for input stream.")92 93 if input is None:94 input = b""86- elif not isinstance(input, bytes):95+ elif isinstance(input, str):96 input = input.encode(charset)97 89- return io.BytesIO(input)98+ return io.BytesIO(t.cast(bytes, input))99 100 101 class Result:102 """Holds the captured result of an invoked CLI script."""103 104 def __init__(105 self,97- runner,98- stdout_bytes,99- stderr_bytes,100- return_value,101- exit_code,102- exception,103- exc_info=None,106+ runner: "CliRunner",107+ stdout_bytes: bytes,108+ stderr_bytes: t.Optional[bytes],109+ return_value: t.Any,110+ exit_code: int,111+ exception: t.Optional[BaseException],112+ exc_info: t.Optional[113+ t.Tuple[t.Type[BaseException], BaseException, TracebackType]114+ ] = None,115 ):116 #: The runner that created the result117 self.runner = runner118 #: The standard output as bytes.11 unmodified lines130 #: The traceback131 self.exc_info = exc_info132 133 @property123- def output(self):134+ def output(self) -> str:135 """The (standard) output as unicode string."""136 return self.stdout137 138 @property128- def stdout(self):139+ def stdout(self) -> str:140 """The standard output as unicode string."""141 return self.stdout_bytes.decode(self.runner.charset, "replace").replace(142 "\r\n", "\n"143 )144 145 @property135- def stderr(self):146+ def stderr(self) -> str:147 """The standard error as unicode string."""148 if self.stderr_bytes is None:149 raise ValueError("stderr not separately captured")150 return self.stderr_bytes.decode(self.runner.charset, "replace").replace(151 "\r\n", "\n"152 )153 143- def __repr__(self):154+ def __repr__(self) -> str:155 exc_str = repr(self.exception) if self.exception else "okay"156 return f"<{type(self).__name__} {exc_str}>"157 158 15 unmodified lines174 noisy stderr, such that each may be measured175 independently176 """177 167- def __init__(self, charset="utf-8", env=None, echo_stdin=False, mix_stderr=True):178+ def __init__(179+ self,180+ charset: str = "utf-8",181+ env: t.Optional[t.Mapping[str, t.Optional[str]]] = None,182+ echo_stdin: bool = False,183+ mix_stderr: bool = True,184+ ) -> None:185 self.charset = charset186 self.env = env or {}187 self.echo_stdin = echo_stdin188 self.mix_stderr = mix_stderr189 173- def get_default_prog_name(self, cli):190+ def get_default_prog_name(self, cli: "BaseCommand") -> str:191 """Given a command object it will return the default program name192 for it. The default is the `name` attribute or ``"root"`` if not193 set.194 """195 return cli.name or "root"196 180- def make_env(self, overrides=None):197+ def make_env(198+ self, overrides: t.Optional[t.Mapping[str, t.Optional[str]]] = None199+ ) -> t.Mapping[str, t.Optional[str]]:200 """Returns the environment overrides for invoking a script."""201 rv = dict(self.env)202 if overrides:203 rv.update(overrides)204 return rv205 206 @contextlib.contextmanager188- def isolation(self, input=None, env=None, color=False):207+ def isolation(208+ self,209+ input: t.Optional[t.Union[str, bytes, t.IO]] = None,210+ env: t.Optional[t.Mapping[str, t.Optional[str]]] = None,211+ color: bool = False,212+ ) -> t.Iterator[t.Tuple[io.BytesIO, t.Optional[io.BytesIO]]]:213 """A context manager that sets up the isolation for invoking of a214 command line tool. This sets up stdin with the given input data215 and `os.environ` with the overrides from the given dictionary.216 This also rebinds some internals in Click to be mocked (like the12 unmodified lines229 230 .. versionchanged:: 4.0231 Added the ``color`` parameter.232 """209- input = make_input_stream(input, self.charset)233+ bytes_input = make_input_stream(input, self.charset)234 echo_input = None235 236 old_stdin = sys.stdin237 old_stdout = sys.stdout5 unmodified lines243 244 bytes_output = io.BytesIO()245 246 if self.echo_stdin:223- input = echo_input = EchoingStdin(input, bytes_output)247+ bytes_input = echo_input = t.cast(248+ t.BinaryIO, EchoingStdin(bytes_input, bytes_output)249+ )250 225- sys.stdin = input = _NamedTextIOWrapper(226- input, encoding=self.charset, name="<stdin>", mode="r"251+ sys.stdin = text_input = _NamedTextIOWrapper(252+ bytes_input, encoding=self.charset, name="<stdin>", mode="r"253 )254 255 if self.echo_stdin:256 # Force unbuffered reads, otherwise TextIOWrapper reads a257 # large chunk which is echoed early.232- input._CHUNK_SIZE = 1258+ text_input._CHUNK_SIZE = 1 # type: ignore259 260 sys.stdout = _NamedTextIOWrapper(261 bytes_output, encoding=self.charset, name="<stdout>", mode="w"262 )10 unmodified lines273 mode="w",274 errors="backslashreplace",275 )276 251- @_pause_echo(echo_input)252- def visible_input(prompt=None):277+ @_pause_echo(echo_input) # type: ignore278+ def visible_input(prompt: t.Optional[str] = None) -> str:279 sys.stdout.write(prompt or "")254- val = input.readline().rstrip("\r\n")280+ val = text_input.readline().rstrip("\r\n")281 sys.stdout.write(f"{val}\n")282 sys.stdout.flush()283 return val284 259- @_pause_echo(echo_input)260- def hidden_input(prompt=None):285+ @_pause_echo(echo_input) # type: ignore286+ def hidden_input(prompt: t.Optional[str] = None) -> str:287 sys.stdout.write(f"{prompt or ''}\n")288 sys.stdout.flush()263- return input.readline().rstrip("\r\n")289+ return text_input.readline().rstrip("\r\n")290 265- @_pause_echo(echo_input)266- def _getchar(echo):291+ @_pause_echo(echo_input) # type: ignore292+ def _getchar(echo: bool) -> str:293 char = sys.stdin.read(1)294 295 if echo:296 sys.stdout.write(char)2 unmodified lines299 return char300 301 default_color = color302 277- def should_strip_ansi(stream=None, color=None):303+ def should_strip_ansi(304+ stream: t.Optional[t.IO] = None, color: t.Optional[bool] = None305+ ) -> bool:306 if color is None:307 return not default_color308 return not color309 310 old_visible_prompt_func = termui.visible_prompt_func311 old_hidden_prompt_func = termui.hidden_prompt_func312 old__getchar_func = termui._getchar285- old_should_strip_ansi = utils.should_strip_ansi313+ old_should_strip_ansi = utils.should_strip_ansi # type: ignore314 termui.visible_prompt_func = visible_input315 termui.hidden_prompt_func = hidden_input316 termui._getchar = _getchar289- utils.should_strip_ansi = should_strip_ansi317+ utils.should_strip_ansi = should_strip_ansi # type: ignore318 319 old_env = {}320 try:321 for key, value in env.items():20 unmodified lines342 sys.stdin = old_stdin343 termui.visible_prompt_func = old_visible_prompt_func344 termui.hidden_prompt_func = old_hidden_prompt_func345 termui._getchar = old__getchar_func318- utils.should_strip_ansi = old_should_strip_ansi346+ utils.should_strip_ansi = old_should_strip_ansi # type: ignore347 formatting.FORCED_WIDTH = old_forced_width348 349 def invoke(350 self,323- cli,324- args=None,325- input=None,326- env=None,327- catch_exceptions=True,328- color=False,329- **extra,330- ):351+ cli: "BaseCommand",352+ args: t.Optional[t.Union[str, t.Sequence[str]]] = None,353+ input: t.Optional[t.Union[str, bytes, t.IO]] = None,354+ env: t.Optional[t.Mapping[str, t.Optional[str]]] = None,355+ catch_exceptions: bool = True,356+ color: bool = False,357+ **extra: t.Any,358+ ) -> Result:359 """Invokes a command in an isolated environment. The arguments are360 forwarded directly to the command line script, the `extra` keyword361 arguments are passed to the :meth:`~clickpkg.Command.main` function of362 the command.29 unmodified lines392 """393 exc_info = None394 with self.isolation(input=input, env=env, color=color) as outstreams:395 return_value = None368- exception = None396+ exception: t.Optional[BaseException] = None397 exit_code = 0398 399 if isinstance(args, str):400 args = shlex.split(args)6 unmodified lines407 try:408 return_value = cli.main(args=args or (), prog_name=prog_name, **extra)409 except SystemExit as e:410 exc_info = sys.exc_info()383- exit_code = e.code384- if exit_code is None:385- exit_code = 0411+ e_code = t.cast(t.Optional[t.Union[int, t.Any]], e.code)412 413+ if e_code is None:414+ e_code = 0415+387- if exit_code != 0:416+ if e_code != 0:417 exception = e418 390- if not isinstance(exit_code, int):391- sys.stdout.write(str(exit_code))419+ if not isinstance(e_code, int):420+ sys.stdout.write(str(e_code))421 sys.stdout.write("\n")393- exit_code = 1422+ e_code = 1423 424+ exit_code = e_code425+426 except Exception as e:427 if not catch_exceptions:428 raise429 exception = e4 unmodified lines434 stdout = outstreams[0].getvalue()435 if self.mix_stderr:436 stderr = None437 else:407- stderr = outstreams[1].getvalue()438+ stderr = outstreams[1].getvalue() # type: ignore439 440 return Result(441 runner=self,442 stdout_bytes=stdout,443 stderr_bytes=stderr,444 return_value=return_value,445 exit_code=exit_code,446 exception=exception,416- exc_info=exc_info,447+ exc_info=exc_info, # type: ignore448 )449 450 @contextlib.contextmanager420- def isolated_filesystem(self, temp_dir=None):451+ def isolated_filesystem(452+ self, temp_dir: t.Optional[t.Union[str, os.PathLike]] = None453+ ) -> t.Iterator[str]:454 """A context manager that creates a temporary directory and455 changes the current working directory to it. This isolates tests456 that affect the contents of the CWD to prevent them from457 interfering with each other.22 unmodified linesmodified:src/click/types.py+158 added-79 removed
11 unmodified lines12 from .exceptions import BadParameter13 from .utils import LazyFile14 from .utils import safecall15 16+if t.TYPE_CHECKING:17+ import typing_extensions as te18+ from .core import Context19+ from .core import Parameter20+ from .shell_completion import CompletionItem21 22+23 class ParamType:24 """Represents the type of a parameter. Validates and converts values25 from the command line or Python into the correct type.26 10 unmodified lines37 arguments are ``None``. This can occur when converting prompt38 input.39 """40 35- is_composite = False41+ is_composite: t.ClassVar[bool] = False42+ arity: t.ClassVar[int] = 143 44 #: the descriptive name of this type38- name: t.Optional[str] = None45+ name: str46 47 #: if a list of this type is expected and the value is pulled from a48 #: string environment variable, this is what splits it up. `None`49 #: means any whitespace. For all parameters the general rule is that1 unmodified line51 #: are split by ``os.path.pathsep`` by default (":" on Unix and ";" on52 #: Windows).53 envvar_list_splitter: t.ClassVar[t.Optional[str]] = None54 48- def to_info_dict(self):55+ def to_info_dict(self) -> t.Dict[str, t.Any]:56 """Gather information that could be useful for a tool generating57 user-facing documentation.58 59 Use :meth:`click.Context.to_info_dict` to traverse the entire5 unmodified lines65 param_type = type(self).__name__.partition("ParamType")[0]66 param_type = param_type.partition("ParameterType")[0]67 return {"param_type": param_type, "name": self.name}68 62- def __call__(self, value, param=None, ctx=None):69+ def __call__(70+ self,71+ value: t.Any,72+ param: t.Optional["Parameter"] = None,73+ ctx: t.Optional["Context"] = None,74+ ) -> t.Any:75 if value is not None:76 return self.convert(value, param, ctx)77 66- def get_metavar(self, param):78+ def get_metavar(self, param: "Parameter") -> t.Optional[str]:79 """Returns the metavar default for this param if it provides one."""80 69- def get_missing_message(self, param):81+ def get_missing_message(self, param: "Parameter") -> t.Optional[str]:82 """Optionally might return extra information about a missing83 parameter.84 85 .. versionadded:: 2.086 """87 76- def convert(self, value, param, ctx):88+ def convert(89+ self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]90+ ) -> t.Any:91 """Convert the value to the correct type. This is not called if92 the value is ``None`` (the missing value).93 94 This must accept string values from the command line, as well as13 unmodified lines108 be ``None``.109 """110 return value111 98- def split_envvar_value(self, rv):112+ def split_envvar_value(self, rv: str) -> t.Sequence[str]:113 """Given a value from an environment variable this splits it up114 into small chunks depending on the defined envvar list splitter.115 116 If the splitter is set to `None`, which means that whitespace splits,1 unmodified line118 and trailing splitters usually lead to empty items being included.119 """120 return (rv or "").split(self.envvar_list_splitter)121 108- def fail(self, message, param=None, ctx=None):122+ def fail(123+ self,124+ message: str,125+ param: t.Optional["Parameter"] = None,126+ ctx: t.Optional["Context"] = None,127+ ) -> t.NoReturn:128 """Helper method to fail with an invalid value message."""129 raise BadParameter(message, ctx=ctx, param=param)130 112- def shell_complete(self, ctx, param, incomplete):131+ def shell_complete(132+ self, ctx: "Context", param: "Parameter", incomplete: str133+ ) -> t.List["CompletionItem"]:134 """Return a list of135 :class:`~click.shell_completion.CompletionItem` objects for the136 incomplete value. Most types do not provide completions, but137 some do, and this allows custom types to provide custom11 unmodified lines149 class CompositeParamType(ParamType):150 is_composite = True151 152 @property132- def arity(self):153+ def arity(self) -> int: # type: ignore154 raise NotImplementedError()155 156 157 class FuncParamType(ParamType):137- def __init__(self, func):158+ def __init__(self, func: t.Callable[[t.Any], t.Any]) -> None:159 self.name = func.__name__160 self.func = func161 141- def to_info_dict(self):162+ def to_info_dict(self) -> t.Dict[str, t.Any]:163 info_dict = super().to_info_dict()164 info_dict["func"] = self.func165 return info_dict166 146- def convert(self, value, param, ctx):167+ def convert(168+ self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]169+ ) -> t.Any:170 try:171 return self.func(value)172 except ValueError:173 try:6 unmodified lines180 181 class UnprocessedParamType(ParamType):182 name = "text"183 161- def convert(self, value, param, ctx):184+ def convert(185+ self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]186+ ) -> t.Any:187 return value188 164- def __repr__(self):189+ def __repr__(self) -> str:190 return "UNPROCESSED"191 192 193 class StringParamType(ParamType):194 name = "text"195 171- def convert(self, value, param, ctx):196+ def convert(197+ self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]198+ ) -> t.Any:199 if isinstance(value, bytes):200 enc = _get_argv_encoding()201 try:202 value = value.decode(enc)8 unmodified lines211 value = value.decode("utf-8", "replace")212 return value213 return str(value)214 188- def __repr__(self):215+ def __repr__(self) -> str:216 return "STRING"217 218 219 class Choice(ParamType):14 unmodified lines234 """235 236 name = "choice"237 211- def __init__(self, choices, case_sensitive=True):238+ def __init__(self, choices: t.Sequence[str], case_sensitive: bool = True) -> None:239 self.choices = choices240 self.case_sensitive = case_sensitive241 215- def to_info_dict(self):242+ def to_info_dict(self) -> t.Dict[str, t.Any]:243 info_dict = super().to_info_dict()244 info_dict["choices"] = self.choices245 info_dict["case_sensitive"] = self.case_sensitive246 return info_dict247 221- def get_metavar(self, param):248+ def get_metavar(self, param: "Parameter") -> str:249 choices_str = "|".join(self.choices)250 251 # Use curly braces to indicate a required argument.252 if param.required and param.param_type_name == "argument":1 unmodified line254 255 # Use square braces to indicate an option or optional argument.256 return f"[{choices_str}]"257 231- def get_missing_message(self, param):258+ def get_missing_message(self, param: "Parameter") -> str:259 return _("Choose from:\n\t{choices}").format(choices=",\n\t".join(self.choices))260 234- def convert(self, value, param, ctx):261+ def convert(262+ self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]263+ ) -> t.Any:264 # Match through normalization and case sensitivity265 # first do token_normalize_func, then lowercase266 # preserve original `value` to produce an accurate message in267 # `self.fail`27 unmodified lines295 param,296 ctx,297 )298 270- def __repr__(self):299+ def __repr__(self) -> str:300 return f"Choice({list(self.choices)})"301 273- def shell_complete(self, ctx, param, incomplete):302+ def shell_complete(303+ self, ctx: "Context", param: "Parameter", incomplete: str304+ ) -> t.List["CompletionItem"]:305 """Complete choices that start with the incomplete value.306 307 :param ctx: Invocation context for this command.308 :param param: The parameter that is requesting completion.36 unmodified lines345 """346 347 name = "datetime"348 318- def __init__(self, formats=None):349+ def __init__(self, formats: t.Optional[t.Sequence[str]] = None):350 self.formats = formats or ["%Y-%m-%d", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%d %H:%M:%S"]351 321- def to_info_dict(self):352+ def to_info_dict(self) -> t.Dict[str, t.Any]:353 info_dict = super().to_info_dict()354 info_dict["formats"] = self.formats355 return info_dict356 326- def get_metavar(self, param):357+ def get_metavar(self, param: "Parameter") -> str:358 return f"[{'|'.join(self.formats)}]"359 329- def _try_to_convert_date(self, value, format):360+ def _try_to_convert_date(self, value: t.Any, format: str) -> t.Optional[datetime]:361 try:362 return datetime.strptime(value, format)363 except ValueError:364 return None365 335- def convert(self, value, param, ctx):366+ def convert(367+ self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]368+ ) -> t.Any:369 if isinstance(value, datetime):370 return value371 372 for format in self.formats:12 unmodified lines385 param,386 ctx,387 )388 356- def __repr__(self):389+ def __repr__(self) -> str:390 return "DateTime"391 392 393 class _NumberParamTypeBase(ParamType):361- _number_class: t.ClassVar[t.Optional[t.Type]] = None394+ _number_class: t.ClassVar[t.Type]395 363- def convert(self, value, param, ctx):396+ def convert(397+ self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]398+ ) -> t.Any:399 try:400 return self._number_class(value)401 except ValueError:402 self.fail(5 unmodified lines408 )409 410 411 class _NumberRangeBase(_NumberParamTypeBase):377- def __init__(self, min=None, max=None, min_open=False, max_open=False, clamp=False):412+ def __init__(413+ self,414+ min: t.Optional[float] = None,415+ max: t.Optional[float] = None,416+ min_open: bool = False,417+ max_open: bool = False,418+ clamp: bool = False,419+ ) -> None:420 self.min = min421 self.max = max422 self.min_open = min_open423 self.max_open = max_open424 self.clamp = clamp425 384- def to_info_dict(self):426+ def to_info_dict(self) -> t.Dict[str, t.Any]:427 info_dict = super().to_info_dict()428 info_dict.update(429 min=self.min,430 max=self.max,2 unmodified lines433 clamp=self.clamp,434 )435 return info_dict436 395- def convert(self, value, param, ctx):437+ def convert(438+ self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]439+ ) -> t.Any:440 import operator441 442 rv = super().convert(value, param, ctx)399- lt_min = self.min is not None and (443+ lt_min: bool = self.min is not None and (444 operator.le if self.min_open else operator.lt445 )(rv, self.min)402- gt_max = self.max is not None and (446+ gt_max: bool = self.max is not None and (447 operator.ge if self.max_open else operator.gt448 )(rv, self.max)449 450 if self.clamp:451 if lt_min:408- return self._clamp(self.min, 1, self.min_open)452+ return self._clamp(self.min, 1, self.min_open) # type: ignore453 454 if gt_max:411- return self._clamp(self.max, -1, self.max_open)455+ return self._clamp(self.max, -1, self.max_open) # type: ignore456 457 if lt_min or gt_max:458 self.fail(459 _("{value} is not in the range {range}.").format(4 unmodified lines464 )465 466 return rv467 424- def _clamp(self, bound, dir, open):468+ def _clamp(self, bound: float, dir: "te.Literal[1, -1]", open: bool) -> float:469 """Find the valid value to clamp to bound in the given470 direction.471 472 :param bound: The boundary value.1 unmodified line474 :param open: If true, the range does not include the bound.475 """476 raise NotImplementedError477 434- def _describe_range(self):478+ def _describe_range(self) -> str:479 """Describe the range for use in help text."""480 if self.min is None:481 op = "<" if self.max_open else "<="482 return f"x{op}{self.max}"5 unmodified lines488 lop = "<" if self.min_open else "<="489 rop = "<" if self.max_open else "<="490 return f"{self.min}{lop}x{rop}{self.max}"491 448- def __repr__(self):492+ def __repr__(self) -> str:493 clamp = " clamped" if self.clamp else ""494 return f"<{type(self).__name__} {self._describe_range()}{clamp}>"495 496 497 class IntParamType(_NumberParamTypeBase):498 name = "integer"499 _number_class = int500 457- def __repr__(self):501+ def __repr__(self) -> str:502 return "INT"503 504 505 class IntRange(_NumberRangeBase, IntParamType):12 unmodified lines518 """519 520 name = "integer range"521 478- def _clamp(self, bound, dir, open):522+ def _clamp( # type: ignore523+ self, bound: int, dir: "te.Literal[1, -1]", open: bool524+ ) -> int:525 if not open:526 return bound527 528 return bound + dir2 unmodified lines531 class FloatParamType(_NumberParamTypeBase):532 name = "float"533 _number_class = float534 489- def __repr__(self):535+ def __repr__(self) -> str:536 return "FLOAT"537 538 539 class FloatRange(_NumberRangeBase, FloatParamType):13 unmodified lines553 """554 555 name = "float range"556 511- def __init__(self, min=None, max=None, min_open=False, max_open=False, clamp=False):557+ def __init__(558+ self,559+ min: t.Optional[float] = None,560+ max: t.Optional[float] = None,561+ min_open: bool = False,562+ max_open: bool = False,563+ clamp: bool = False,564+ ) -> None:565 super().__init__(566 min=min, max=max, min_open=min_open, max_open=max_open, clamp=clamp567 )568 569 if (min_open or max_open) and clamp:570 raise TypeError("Clamping is not supported for open bounds.")571 519- def _clamp(self, bound, dir, open):572+ def _clamp(self, bound: float, dir: "te.Literal[1, -1]", open: bool) -> float:573 if not open:574 return bound575 576 # Could use Python 3.9's math.nextafter here, but clamping an4 unmodified lines581 582 class BoolParamType(ParamType):583 name = "boolean"584 532- def convert(self, value, param, ctx):585+ def convert(586+ self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]587+ ) -> t.Any:588 if value in {False, True}:589 return bool(value)590 591 norm = value.strip().lower()7 unmodified lines599 self.fail(600 _("{value!r} is not a valid boolean.").format(value=value), param, ctx601 )602 548- def __repr__(self):603+ def __repr__(self) -> str:604 return "BOOL"605 606 607 class UUIDParameterType(ParamType):608 name = "uuid"609 555- def convert(self, value, param, ctx):610+ def convert(611+ self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]612+ ) -> t.Any:613 import uuid614 615 if isinstance(value, uuid.UUID):616 return value6 unmodified lines623 self.fail(624 _("{value!r} is not a valid UUID.").format(value=value), param, ctx625 )626 570- def __repr__(self):627+ def __repr__(self) -> str:628 return "UUID"629 630 631 class File(ParamType):26 unmodified lines658 name = "filename"659 envvar_list_splitter = os.path.pathsep660 661 def __init__(605- self, mode="r", encoding=None, errors="strict", lazy=None, atomic=False606- ):662+ self,663+ mode: str = "r",664+ encoding: t.Optional[str] = None,665+ errors: t.Optional[str] = "strict",666+ lazy: t.Optional[bool] = None,667+ atomic: bool = False,668+ ) -> None:669 self.mode = mode670 self.encoding = encoding671 self.errors = errors672 self.lazy = lazy673 self.atomic = atomic674 613- def to_info_dict(self):675+ def to_info_dict(self) -> t.Dict[str, t.Any]:676 info_dict = super().to_info_dict()677 info_dict.update(mode=self.mode, encoding=self.encoding)678 return info_dict679 618- def resolve_lazy_flag(self, value):680+ def resolve_lazy_flag(self, value: t.Any) -> bool:681 if self.lazy is not None:682 return self.lazy683 if value == "-":684 return False685 elif "w" in self.mode:686 return True687 return False688 627- def convert(self, value, param, ctx):689+ def convert(690+ self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]691+ ) -> t.Any:692 try:693 if hasattr(value, "read") or hasattr(value, "write"):694 return value695 696 lazy = self.resolve_lazy_flag(value)697 698 if lazy:699+ f: t.IO = t.cast(700+ t.IO,635- f = LazyFile(636- value, self.mode, self.encoding, self.errors, atomic=self.atomic701+ LazyFile(702+ value, self.mode, self.encoding, self.errors, atomic=self.atomic703+ ),704 )705+706 if ctx is not None:639- ctx.call_on_close(f.close_intelligently)707+ ctx.call_on_close(f.close_intelligently) # type: ignore708+709 return f710 711 f, should_close = open_stream(712 value, self.mode, self.encoding, self.errors, atomic=self.atomic713 )714+715 # If a context is provided, we automatically close the file716 # at the end of the context execution (or flush out). If a717 # context does not exist, it's the caller's responsibility to718 # properly close the file. This for instance happens when the2 unmodified lines721 if should_close:722 ctx.call_on_close(safecall(f.close))723 else:724 ctx.call_on_close(safecall(f.flush))725+726 return f727 except OSError as e: # noqa: B014728 self.fail(f"{os.fsdecode(value)!r}: {get_strerror(e)}", param, ctx)729 659- def shell_complete(self, ctx, param, incomplete):730+ def shell_complete(731+ self, ctx: "Context", param: "Parameter", incomplete: str732+ ) -> t.List["CompletionItem"]:733 """Return a special completion marker that tells the completion734 system to use the shell to provide file path completions.735 736 :param ctx: Invocation context for this command.42 unmodified lines779 envvar_list_splitter = os.path.pathsep780 781 def __init__(782 self,710- exists=False,711- file_okay=True,712- dir_okay=True,713- writable=False,714- readable=True,715- resolve_path=False,716- allow_dash=False,717- path_type=None,783+ exists: bool = False,784+ file_okay: bool = True,785+ dir_okay: bool = True,786+ writable: bool = False,787+ readable: bool = True,788+ resolve_path: bool = False,789+ allow_dash: bool = False,790+ path_type: t.Optional[t.Type] = None,791 ):792 self.exists = exists793 self.file_okay = file_okay794 self.dir_okay = dir_okay9 unmodified lines804 self.name = _("directory")805 else:806 self.name = _("path")807 735- def to_info_dict(self):808+ def to_info_dict(self) -> t.Dict[str, t.Any]:809 info_dict = super().to_info_dict()810 info_dict.update(811 exists=self.exists,812 file_okay=self.file_okay,3 unmodified lines816 allow_dash=self.allow_dash,817 )818 return info_dict819 747- def coerce_path_result(self, rv):820+ def coerce_path_result(self, rv: t.Any) -> t.Any:821 if self.type is not None and not isinstance(rv, self.type):822 if self.type is str:823 rv = os.fsdecode(rv)824 elif self.type is bytes:2 unmodified lines827 rv = self.type(rv)828 829 return rv830 758- def convert(self, value, param, ctx):831+ def convert(832+ self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]833+ ) -> t.Any:834 rv = value835 836 is_dash = self.file_okay and self.allow_dash and rv in (b"-", "-")837 52 unmodified lines890 )891 892 return self.coerce_path_result(rv)893 819- def shell_complete(self, ctx, param, incomplete):894+ def shell_complete(895+ self, ctx: "Context", param: "Parameter", incomplete: str896+ ) -> t.List["CompletionItem"]:897 """Return a special completion marker that tells the completion898 system to use the shell to provide path completions for only899 directories or any paths.900 22 unmodified lines923 924 :param types: a list of types that should be used for the tuple items.925 """926 850- def __init__(self, types):927+ def __init__(self, types: t.Sequence[t.Union[t.Type, ParamType]]) -> None:928 self.types = [convert_type(ty) for ty in types]929 853- def to_info_dict(self):930+ def to_info_dict(self) -> t.Dict[str, t.Any]:931 info_dict = super().to_info_dict()932 info_dict["types"] = [t.to_info_dict() for t in self.types]933 return info_dict934 935 @property859- def name(self):936+ def name(self) -> str: # type: ignore937 return f"<{' '.join(ty.name for ty in self.types)}>"938 939 @property863- def arity(self):940+ def arity(self) -> int: # type: ignore941 return len(self.types)942 866- def convert(self, value, param, ctx):943+ def convert(944+ self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]945+ ) -> t.Any:946 len_type = len(self.types)947 len_value = len(value)948 949 if len_value != len_type:9 unmodified lines959 960 return tuple(ty(x, param, ctx) for ty, x in zip(self.types, value))961 962 884-def convert_type(ty, default=None):963+def convert_type(ty: t.Optional[t.Any], default: t.Optional[t.Any] = None) -> ParamType:964 """Find the most appropriate :class:`ParamType` for the given Python965 type. If the type isn't provided, it can be inferred from a default966 value.967 """89 unmodified linesmodified:src/click/utils.py+90 added-56 removed
1 import os2 import sys3 import typing as t4+from functools import update_wrapper5+from types import ModuleType6 7 from ._compat import _default_text_stderr8 from ._compat import _default_text_stdout9 from ._compat import _find_binary_writer10 from ._compat import auto_wrap_for_ansi11 from ._compat import binary_streams12 from ._compat import get_filesystem_encoding13 from ._compat import get_strerror12-from ._compat import is_bytes14 from ._compat import open_stream15 from ._compat import should_strip_ansi16 from ._compat import strip_ansi17 from ._compat import text_streams18 from ._compat import WIN19 from .globals import resolve_color_default20 21+if t.TYPE_CHECKING:22+ import typing_extensions as te23 24+F = t.TypeVar("F", bound=t.Callable[..., t.Any])25+26+21-def _posixify(name):27+def _posixify(name: str) -> str:28 return "-".join(name.split()).lower()29 30 25-def safecall(func):31+def safecall(func: F) -> F:32 """Wraps a function so that it swallows exceptions."""33 28- def wrapper(*args, **kwargs):34+ def wrapper(*args, **kwargs): # type: ignore35 try:36 return func(*args, **kwargs)37 except Exception:38 pass39 34- return wrapper40+ return update_wrapper(t.cast(F, wrapper), func)41 42 37-def make_str(value):43+def make_str(value: t.Any) -> str:44 """Converts a value into a valid string."""45 if isinstance(value, bytes):46 try:47 return value.decode(get_filesystem_encoding())59 unmodified lines107 files for writing.108 """109 110 def __init__(105- self, filename, mode="r", encoding=None, errors="strict", atomic=False111+ self,112+ filename: str,113+ mode: str = "r",114+ encoding: t.Optional[str] = None,115+ errors: t.Optional[str] = "strict",116+ atomic: bool = False,117 ):118 self.name = filename119 self.mode = mode120 self.encoding = encoding121 self.errors = errors122 self.atomic = atomic123+ self._f: t.Optional[t.IO]124 125 if filename == "-":126 self._f, self.should_close = open_stream(filename, mode, encoding, errors)127 else:4 unmodified lines132 open(filename, mode).close()133 self._f = None134 self.should_close = True135 124- def __getattr__(self, name):136+ def __getattr__(self, name: str) -> t.Any:137 return getattr(self.open(), name)138 127- def __repr__(self):139+ def __repr__(self) -> str:140 if self._f is not None:141 return repr(self._f)142 return f"<unopened file '{self.name}' {self.mode}>"143 132- def open(self):144+ def open(self) -> t.IO:145 """Opens the file if it's not yet open. This call might fail with146 a :exc:`FileError`. Not handling this error will produce an error147 that Click shows.148 """9 unmodified lines158 raise FileError(self.name, hint=get_strerror(e))159 self._f = rv160 return rv161 150- def close(self):162+ def close(self) -> None:163 """Closes the underlying file, no matter what."""164 if self._f is not None:165 self._f.close()166 155- def close_intelligently(self):167+ def close_intelligently(self) -> None:168 """This function only closes the file if it was opened by the lazy169 file wrapper. For instance this will never close stdin.170 """171 if self.should_close:172 self.close()173 162- def __enter__(self):174+ def __enter__(self) -> "LazyFile":175 return self176 165- def __exit__(self, exc_type, exc_value, tb):177+ def __exit__(self, exc_type, exc_value, tb): # type: ignore178 self.close_intelligently()179 168- def __iter__(self):180+ def __iter__(self) -> t.Iterator[t.AnyStr]:181 self.open()170- return iter(self._f)182+ return iter(self._f) # type: ignore183 184 185 class KeepOpenFile:174- def __init__(self, file):186+ def __init__(self, file: t.IO) -> None:187 self._file = file188 177- def __getattr__(self, name):189+ def __getattr__(self, name: str) -> t.Any:190 return getattr(self._file, name)191 180- def __enter__(self):192+ def __enter__(self) -> "KeepOpenFile":193 return self194 183- def __exit__(self, exc_type, exc_value, tb):195+ def __exit__(self, exc_type, exc_value, tb): # type: ignore196 pass197 186- def __repr__(self):198+ def __repr__(self) -> str:199 return repr(self._file)200 189- def __iter__(self):201+ def __iter__(self) -> t.Iterator[t.AnyStr]:202 return iter(self._file)203 204 193-def echo(message=None, file=None, nl=True, err=False, color=None):205+def echo(206+ message: t.Optional[t.Any] = None,207+ file: t.Optional[t.IO] = None,208+ nl: bool = True,209+ err: bool = False,210+ color: t.Optional[bool] = None,211+) -> None:212 """Print a message and newline to stdout or a file. This should be213 used instead of :func:`print` because it provides better support214 for different data, files, and environments.215 38 unmodified lines254 file = _default_text_stdout()255 256 # Convert non bytes/text into the native string type.257 if message is not None and not isinstance(message, (str, bytes, bytearray)):240- message = str(message)258+ out: t.Optional[t.Union[str, bytes]] = str(message)259+ else:260+ out = message261 262 if nl:243- message = message or ""244- if isinstance(message, str):245- message += "\n"263+ out = out or ""264+ if isinstance(out, str):265+ out += "\n"266 else:247- message += b"\n"267+ out += b"\n"268 269+ if not out:270+ file.flush()271+ return272+273 # If there is a message and the value looks like bytes, we manually274 # need to find the binary stream and write the message in there.275 # This is done separately so that most stream types will work as you276 # would expect. Eg: you can write to StringIO for other cases.253- if message and is_bytes(message):277+ if isinstance(out, (bytes, bytearray)):278 binary_file = _find_binary_writer(file)279+280 if binary_file is not None:281 file.flush()257- binary_file.write(message)282+ binary_file.write(out)283 binary_file.flush()284 return285 286 # ANSI style code support. For no message or bytes, nothing happens.287 # When outputting to a file instead of a terminal, strip codes.263- if message and not is_bytes(message):288+ else:289 color = resolve_color_default(color)290+291 if should_strip_ansi(file, color):266- message = strip_ansi(message)292+ out = strip_ansi(out)293 elif WIN:294 if auto_wrap_for_ansi is not None:269- file = auto_wrap_for_ansi(file)295+ file = auto_wrap_for_ansi(file) # type: ignore296 elif not color:271- message = strip_ansi(message)297+ out = strip_ansi(out)298 273- if message:274- file.write(message)299+ file.write(out) # type: ignore300 file.flush()301 302 278-def get_binary_stream(name):303+def get_binary_stream(name: "te.Literal['stdin', 'stdout', 'stderr']") -> t.BinaryIO:304 """Returns a system stream for byte processing.305 306 :param name: the name of the stream to open. Valid names are ``'stdin'``,307 ``'stdout'`` and ``'stderr'``3 unmodified lines311 raise TypeError(f"Unknown standard stream '{name}'")312 return opener()313 314 290-def get_text_stream(name, encoding=None, errors="strict"):315+def get_text_stream(316+ name: "te.Literal['stdin', 'stdout', 'stderr']",317+ encoding: t.Optional[str] = None,318+ errors: t.Optional[str] = "strict",319+) -> t.TextIO:320 """Returns a system stream for text processing. This usually returns321 a wrapped stream around a binary stream returned from322 :func:`get_binary_stream` but it also can take shortcuts for already323 correctly configured streams.9 unmodified lines333 return opener(encoding, errors)334 335 336 def open_file(308- filename, mode="r", encoding=None, errors="strict", lazy=False, atomic=False309-):337+ filename: str,338+ mode: str = "r",339+ encoding: t.Optional[str] = None,340+ errors: t.Optional[str] = "strict",341+ lazy: bool = False,342+ atomic: bool = False,343+) -> t.IO:344 """This is similar to how the :class:`File` works but for manual345 usage. Files are opened non lazy by default. This can open regular346 files as well as stdin/stdout if ``'-'`` is passed.347 15 unmodified lines363 :param atomic: in atomic mode writes go into a temporary file and it's364 moved on close.365 """366 if lazy:333- return LazyFile(filename, mode, encoding, errors, atomic=atomic)367+ return t.cast(t.IO, LazyFile(filename, mode, encoding, errors, atomic=atomic))368 f, should_close = open_stream(filename, mode, encoding, errors, atomic=atomic)369 if not should_close:336- f = KeepOpenFile(f)370+ f = t.cast(t.IO, KeepOpenFile(f))371 return f372 373 340-def get_os_args():374+def get_os_args() -> t.Sequence[str]:375 """Returns the argument part of ``sys.argv``, removing the first376 value which is the name of the script.377 378 .. deprecated:: 8.010 unmodified lines389 )390 return sys.argv[1:]391 392 359-def format_filename(filename, shorten=False):393+def format_filename(394+ filename: t.Union[str, bytes, os.PathLike], shorten: bool = False395+) -> str:396 """Formats a filename for user display. The main purpose of this397 function is to ensure that the filename can be displayed at all. This398 will decode the filename to unicode if necessary in a way that it will399 not fail. Optionally, it can shorten the filename to not include the9 unmodified lines409 410 return os.fsdecode(filename)411 412 377-def get_app_dir(app_name, roaming=True, force_posix=False):413+def get_app_dir(app_name: str, roaming: bool = True, force_posix: bool = False) -> str:414 r"""Returns the config folder for the application. The default behavior415 is to return whatever is most appropriate for the operating system.416 417 To give you an idea, for an app called ``"Foo Bar"``, something like6 unmodified lines424 Unix:425 ``~/.config/foo-bar``426 Unix (POSIX):427 ``~/.foo-bar``392- Win XP (roaming):393- ``C:\Documents and Settings\<user>\Local Settings\Application Data\Foo Bar``394- Win XP (not roaming):395- ``C:\Documents and Settings\<user>\Application Data\Foo Bar``396- Win 7 (roaming):428+ Windows (roaming):429 ``C:\Users\<user>\AppData\Roaming\Foo Bar``398- Win 7 (not roaming):430+ Windows (not roaming):431 ``C:\Users\<user>\AppData\Local\Foo Bar``432 433 .. versionadded:: 2.0434 32 unmodified lines467 other cleanup code, and the case where the underlying file is not a broken468 pipe, all calls and attributes are proxied.469 """470 439- def __init__(self, wrapped):471+ def __init__(self, wrapped: t.IO) -> None:472 self.wrapped = wrapped473 442- def flush(self):474+ def flush(self) -> None:475 try:476 self.wrapped.flush()477 except OSError as e:478 import errno479 480 if e.errno != errno.EPIPE:481 raise482 451- def __getattr__(self, attr):483+ def __getattr__(self, attr: str) -> t.Any:484 return getattr(self.wrapped, attr)485 486 455-def _detect_program_name(path=None, _main=sys.modules["__main__"]):487+def _detect_program_name(488+ path: t.Optional[str] = None, _main: ModuleType = sys.modules["__main__"]489+) -> str:490 """Determine the command used to run the program, for use in help491 text. If a file or entry point was executed, the file name is492 returned. If ``python -m`` was used to execute a module or package,493 ``python -m name`` is returned.30 unmodified lines524 525 # Executed a module, like "python -m example".526 # Rewritten by Python from "-m script" to "/path/to/script.py".527 # Need to look at main module to determine how it was executed.494- py_module = _main.__package__528+ py_module = t.cast(str, _main.__package__)529 name = os.path.splitext(os.path.basename(path))[0]530 531 # A submodule like "example.cli".532 if name != "__main__":48 unmodified linesmodified:tests/test_termui.py+15 added-19 removed
16 unmodified lines17 def time(self):18 return self.now19 20 21-def _create_progress(length=10, length_known=True, **kwargs):21+def _create_progress(length=10, **kwargs):22 progress = click.progressbar(tuple(range(length)))23 for key, value in kwargs.items():24 setattr(progress, key, value)25- progress.length_known = length_known25 return progress26 27 28 def test_progressbar_strip_regression(runner, monkeypatch):5 unmodified lines34 for _ in progress:35 pass36 37 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)39- assert label in runner.invoke(cli, []).output38+ assert (39+ label40+ in runner.invoke(cli, [], standalone_mode=False, catch_exceptions=False).output41+ )42 43 44 def test_progressbar_length_hint(runner, monkeypatch):45 class Hinted:66 unmodified lines112 113 114 @pytest.mark.parametrize("pos, length", [(0, 5), (-1, 1), (5, 5), (6, 5), (4, 0)])115 def test_progressbar_format_pos(runner, pos, length):114- with _create_progress(length, length_known=length != 0, pos=pos) as progress:116+ with _create_progress(length, pos=pos) as progress:117 result = progress.format_pos()116- if progress.length_known:117- assert result == f"{pos}/{length}"118+ assert result == f"{pos}/{length}"118- else:119- assert result == str(pos)119 120 121 @pytest.mark.parametrize(122 "length, finished, pos, avg, expected",123 [124 (8, False, 7, 0, "#######-"),125 (0, True, 8, 0, "########"),127- (0, False, 8, 0, "--------"),128- (0, False, 5, 3, "#-------"),126 ],127 )128 def test_progressbar_format_bar(runner, length, finished, pos, avg, expected):129 with _create_progress(133- length, length_known=length != 0, width=8, pos=pos, finished=finished, avg=[avg]130+ length, width=8, pos=pos, finished=finished, avg=[avg]131 ) as progress:132 assert progress.format_bar() == expected133 134 135 @pytest.mark.parametrize(139- "length, length_known, show_percent, show_pos, pos, expected",136+ "length, show_percent, show_pos, pos, expected",137 [141- (0, True, True, True, 0, " [--------] 0/0 0%"),142- (0, True, False, True, 0, " [--------] 0/0"),143- (0, True, False, False, 0, " [--------]"),144- (0, False, False, False, 0, " [--------]"),145- (8, True, True, True, 8, " [########] 8/8 100%"),138+ (0, True, True, 0, " [--------] 0/0 0%"),139+ (0, False, True, 0, " [--------] 0/0"),140+ (0, False, False, 0, " [--------]"),141+ (0, False, False, 0, " [--------]"),142+ (8, True, True, 8, " [########] 8/8 100%"),143 ],144 )145 def test_progressbar_format_progress_line(149- runner, length, length_known, show_percent, show_pos, pos, expected146+ runner, length, show_percent, show_pos, pos, expected147 ):148 with _create_progress(149 length,153- length_known,150 width=8,151 show_percent=show_percent,152 pos=pos,153 show_pos=show_pos,290 unmodified linesmodified:tests/test_testing.py+3 added-3 removed
12 unmodified lines13 @click.command()14 def test():15 i = click.get_binary_stream("stdin")16 o = click.get_binary_stream("stdout")17- while 1:17+ while True:18 chunk = i.read(4096)19 if not chunk:20 break21 o.write(chunk)9 unmodified lines31 @click.command()32 def test():33 i = click.get_binary_stream("stdin")34 o = click.get_binary_stream("stdout")35- while 1:35+ while True:36 chunk = i.read(4096)37 if not chunk:38 break39 o.write(chunk)49 unmodified lines89 @click.command()90 def test():91 i = click.get_binary_stream("stdin")92 o = click.get_binary_stream("stdout")93- while 1:93+ while True:94 chunk = i.read(4096)95 if not chunk:96 break97 o.write(chunk)323 unmodified linesmodified:MANIFEST.in+1 added
4 unmodified lines5 graft docs6 prune docs/_build7 graft examples8 graft tests9+include src/click/py.typed10 global-exclude *.pycmodified:setup.cfg+3 added-2 removed
77 unmodified lines78 [mypy]79 files = src/click80 python_version = 3.681 disallow_subclassing_any = True82-# disallow_untyped_calls = True83-# disallow_untyped_defs = True82+disallow_untyped_calls = True83+disallow_untyped_defs = True84 disallow_incomplete_defs = True85+check_untyped_defs = True86 no_implicit_optional = True87 local_partial_types = True88 no_implicit_reexport = True89 strict_equality = True14 unmodified lines