Skip to content
Myr

Merge pull request #1856 from pallets/typing

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

add typing annotations

authored by David Lord · committed by GitHub · parents fd4b3d8, b3ee530 · Browse files · 22 files+1733 added−1110 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+1733 added−1110 removed

  • tests:+18 added−22 removed
  • other:+1715 added−1088 removed

22 files+1733 added−1110 removed

modified:examples/termui/termui.py+1 added-1 removed
143 unmodified lines
144@cli.command()145def 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 lines
modified:src/click/_compat.py+137 added-98 removed
15 unmodified lines
16auto_wrap_for_ansi: t.Optional[t.Callable[[t.TextIO], t.TextIO]] = None17_ansi_re = re.compile(r"\033\[[;?0-9]*[a-zA-Z]")181920def get_filesystem_encoding():20def get_filesystem_encoding() -> str:21 return sys.getfilesystemencoding() or sys.getdefaultencoding()222324def _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 lines
41 force_writable=force_writable,42 )434441def is_ascii_encoding(encoding):45def 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 False515249def get_best_encoding(stream):53def 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 lines
6061class _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)7570 def __del__(self):76 def __del__(self) -> None:77 try:78 self.detach()79 except Exception:80 pass8176 def isatty(self):82 def isatty(self) -> bool:83 # https://bitbucket.org/pypy/pypy/issue/180384 return self._stream.isatty()8586
6 unmodified lines
93 put badly patched objects on sys (one such offender are certain version94 of jupyter notebook).95 """9691 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_writable10696 def __getattr__(self, name):107 def __getattr__(self, name: str) -> t.Any:108 return getattr(self._stream, name)10999 def read1(self, size):110 def read1(self, size: int) -> bytes:111 f = getattr(self._stream, "read1", None)112113 if f is not None:102 return f(size)114 return t.cast(bytes, f(size))115116 return self._stream.read(size)117106 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 True129118 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 True144133 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 True154155144def is_bytes(x):145 return isinstance(x, (bytes, memoryview, bytearray))146147148def _is_binary_reader(stream, default=False):156def _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.163164157def _is_binary_writer(stream, default=False):165def _is_binary_writer(stream: t.IO, default: bool = False) -> bool:166 try:167 stream.write(b"")168 except Exception:169 try:
4 unmodified lines
174 return default175 return True176177170def _find_binary_reader(stream):178def _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)185186 buf = getattr(stream, "buffer", None)187188 # 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)192193 return None194186def _find_binary_writer(stream):195196def _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)203204 buf = getattr(stream, "buffer", None)205206 # 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)210211 return None212213202def _stream_is_misconfigured(stream):214def _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")221222211def _is_compat_stream_attr(stream, attr, value):223def _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)230231220def _is_compatible_text_stream(stream, encoding, errors):232def _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 line
240 ) and _is_compat_stream_attr(stream, "errors", errors)241242243def _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_stream262263 # Otherwise, get the underlying binary reader.249 binary_reader = find_binary(text_stream)264 possible_binary_reader = find_binary(text_stream)265266 # 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_stream270271 binary_reader = possible_binary_reader272273 # Default errors to replace instead of strict in order to get274 # something that works.275 if errors is None:276 errors = "replace"
8 unmodified lines
285 force_writable=force_writable,286 )287288272def _force_correct_text_reader(text_reader, encoding, errors, force_readable=False):289def _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 lines
301 force_readable=force_readable,302 )303304283def _force_correct_text_writer(text_writer, encoding, errors, force_writable=False):305def _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 lines
317 force_writable=force_writable,318 )319320294def get_binary_stdin():321def 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 reader326327301def get_binary_stdout():328def 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 writer333334308def get_binary_stderr():335def 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 writer340341315def get_text_stdin(encoding=None, errors=None):342def 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)349350322def get_text_stdout(encoding=None, errors=None):351def 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)358359329def get_text_stderr(encoding=None, errors=None):360def 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)367368336def get_strerror(e, default=None):337 if hasattr(e, "strerror"):338 msg = e.strerror339 else:340 if default is not None:341 msg = default342 else:343 msg = str(e)344 if isinstance(msg, bytes):345 msg = msg.decode("utf-8", "replace")346 return msg347348349def _wrap_io_open(file, mode, encoding, errors):369def _wrap_io_open(370 file: t.Union[str, os.PathLike, int],371 mode: str,372 encoding: t.Optional[str],373 errors: t.Optional[str],374) -> t.IO:375 """Handles not passing ``encoding`` and ``errors`` in binary mode."""376 if "b" in mode:377 return open(file, mode)378379 return open(file, mode, encoding=encoding, errors=errors)380381357def open_stream(filename, mode="r", encoding=None, errors="strict", atomic=False):382def open_stream(383 filename: str,384 mode: str = "r",385 encoding: t.Optional[str] = None,386 errors: t.Optional[str] = "strict",387 atomic: bool = False,388) -> t.Tuple[t.IO, bool]:389 binary = "b" in mode390391 # Standard streams first. These are simple because they don't need392 # special handling for the atomic flag. It's entirely ignored.
30 unmodified lines
423 import errno424 import random425426 try:396 perm = os.stat(filename).st_mode427 perm: t.Optional[int] = os.stat(filename).st_mode428 except OSError:429 perm = None430431 flags = os.O_RDWR | os.O_CREAT | os.O_EXCL
22 unmodified lines
454 if perm is not None:455 os.chmod(tmp_filename, perm) # in case perm includes bits in umask456457 f = _wrap_io_open(fd, mode, encoding, errors)427 return _AtomicFile(f, tmp_filename, os.path.realpath(filename)), True458 af = _AtomicFile(f, tmp_filename, os.path.realpath(filename))459 return t.cast(t.IO, af), True460461462class _AtomicFile:431 def __init__(self, f, tmp_filename, real_filename):463 def __init__(self, f: t.IO, tmp_filename: str, real_filename: str) -> None:464 self._f = f465 self._tmp_filename = tmp_filename466 self._real_filename = real_filename467 self.closed = False468469 @property438 def name(self):470 def name(self) -> str:471 return self._real_filename472441 def close(self, delete=False):473 def close(self, delete: bool = False) -> None:474 if self.closed:475 return476 self._f.close()477 os.replace(self._tmp_filename, self._real_filename)478 self.closed = True479448 def __getattr__(self, name):480 def __getattr__(self, name: str) -> t.Any:481 return getattr(self._f, name)482451 def __enter__(self):483 def __enter__(self) -> "_AtomicFile":484 return self485454 def __exit__(self, exc_type, exc_value, tb):486 def __exit__(self, exc_type, exc_value, tb): # type: ignore487 self.close(delete=exc_type is not None)488457 def __repr__(self):489 def __repr__(self) -> str:490 return repr(self._f)491492461def strip_ansi(value):493def strip_ansi(value: str) -> str:494 return _ansi_re.sub("", value)495496465def _is_jupyter_kernel_output(stream):497def _is_jupyter_kernel_output(stream: t.IO) -> bool:498 while isinstance(stream, (_FixupStream, _NonClosingTextIOWrapper)):499 stream = stream._stream500501 return stream.__class__.__module__.startswith("ipykernel.")502503472def should_strip_ansi(stream=None, color=None):504def should_strip_ansi(505 stream: t.Optional[t.IO] = None, color: t.Optional[bool] = None506) -> bool:507 if color is None:508 if stream is None:509 stream = sys.stdin510 return not isatty(stream) and not _is_jupyter_kernel_output(stream)
5 unmodified lines
516# NOTE: double check is needed so mypy does not analyze this on Linux517if sys.platform.startswith("win") and WIN:518 from ._winconsole import _get_windows_console_stream519486 def _get_argv_encoding():520 def _get_argv_encoding() -> str:521 import locale522523 return locale.getpreferredencoding()524
38 unmodified lines
563564565else:566533 def _get_argv_encoding():567 def _get_argv_encoding() -> str:568 return getattr(sys.stdin, "encoding", None) or get_filesystem_encoding()569536 def _get_windows_console_stream(f, encoding, errors):570 def _get_windows_console_stream(571 f: t.TextIO, encoding: t.Optional[str], errors: t.Optional[str]572 ) -> t.Optional[t.TextIO]:573 return None574575540def term_len(x):576def term_len(x: str) -> int:577 return len(strip_ansi(x))578579544def isatty(stream):580def isatty(stream: t.IO) -> bool:581 try:582 return stream.isatty()583 except Exception:584 return False585586551def _make_cached_stream_func(src_func, wrapper_func):552 cache = WeakKeyDictionary()587def _make_cached_stream_func(588 src_func: t.Callable[[], t.TextIO], wrapper_func: t.Callable[[], t.TextIO]589) -> t.Callable[[], t.TextIO]:590 cache: t.MutableMapping[t.TextIO, t.TextIO] = WeakKeyDictionary()591554 def func():592 def func() -> t.TextIO:593 stream = src_func()594 try:595 rv = cache.get(stream)596 except Exception:
1 unmodified line
598 if rv is not None:599 return rv600 rv = wrapper_func()601 try:564 stream = src_func() # In case wrapper_func() modified the stream602 cache[stream] = rv603 except Exception:604 pass605 return rv
5 unmodified lines
611_default_text_stdout = _make_cached_stream_func(lambda: sys.stdout, get_text_stdout)612_default_text_stderr = _make_cached_stream_func(lambda: sys.stderr, get_text_stderr)613614578binary_streams = {615binary_streams: t.Mapping[str, t.Callable[[], t.BinaryIO]] = {616 "stdin": get_binary_stdin,617 "stdout": get_binary_stdout,618 "stderr": get_binary_stderr,619}620584text_streams = {621text_streams: t.Mapping[622 str, t.Callable[[t.Optional[str], t.Optional[str]], t.TextIO]623] = {624 "stdin": get_text_stdin,625 "stdout": get_text_stdout,626 "stderr": get_text_stderr,627}
modified:src/click/_termui_impl.py+126 added-110 removed
6 unmodified lines
7import math8import os9import sys10import time11import typing as t12from gettext import gettext as _1314from ._compat import _default_text_stdout15from ._compat import CYGWIN
5 unmodified lines
21from ._compat import WIN22from .exceptions import ClickException23from .utils import echo2425V = t.TypeVar("V")2627if os.name == "nt":28 BEFORE_BAR = "\r"29 AFTER_BAR = "\n"30else:31 BEFORE_BAR = "\r\033[?25l"32 AFTER_BAR = "\033[?25h\n"333432def _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 hint484935class 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_template
12 unmodified lines
69 self.width = width70 self.autowidth = width == 07172 if length is None:88 length = _length_hint(iterable)73 from operator import length_hint7475 length = length_hint(iterable, -1)7677 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] = None95107 def __enter__(self):96 def __enter__(self) -> "ProgressBar":97 self.entered = True98 self.render_progress()99 return self100112 def __exit__(self, exc_type, exc_value, tb):101 def __exit__(self, exc_type, exc_value, tb): # type: ignore102 self.render_finish()103115 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()109121 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: ignore117129 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()123124 @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)129130 @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))135136 @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.0141153 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 //= 60
6 unmodified lines
153 else:154 return f"{hours:02}:{minutes:02}:{seconds:02}"155 return ""156168 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 pos162174 def format_pct(self):163 def format_pct(self) -> str:164 return f"{int(self.pct * 100): 4}%"[1:]165177 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 bar184196 def format_progress_line(self):185 def format_progress_line(self) -> str:186 show_percent = self.show_percent187188 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_pos191192 if self.show_pos:193 info_bits.append(self.format_pos())
14 unmodified lines
208 "info": self.info_sep.join(info_bits),209 }210 ).rstrip()211223 def render_progress(self):212 def render_progress(self) -> None:213 import shutil214215 if self.is_hidden:216 # Only output the label as it changes if the output is not a
12 unmodified lines
229 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_width236237 clear_width = self.width
15 unmodified lines
253 self._last_line = line254 echo(line, file=self.file, color=self.color, nl=False)255 self.file.flush()256268 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 = True261262 if (time.time() - self.last_eta) < 1.0:263 return
9 unmodified lines
273 step = time.time() - self.start274275 self.avg = self.avg[-6:] + [step]276288 self.eta_known = self.length_known277 self.eta_known = self.length is not None278290 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 lines
301 self.make_step(self._completed_intervals)302 self.render_progress()303 self._completed_intervals = 0304316 def finish(self):317 self.eta_known = 0305 def finish(self) -> None:306 self.eta_known = False307 self.current_item = None308 self.finished = True309321 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 lines
340 self.finish()341 self.render_progress()342343355def pager(generator, color=None):344def 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 lines
369 finally:370 os.unlink(filename)371372384def _pipepager(generator, cmd, color):373def _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 subprocess
11 unmodified lines
389 elif "r" in less_flags or "R" in less_flags:390 color = True391392 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)399410 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()405406 # Less doesn't respect ^C, but catches it for its own UI purposes (aborting407 # search or other commands inside less).408 #
10 unmodified lines
419 else:420 break421422433def _tempfilepager(generator, cmd, color):423def _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 tempfile428437 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 lines
439 finally:440 os.unlink(filename)441442451def _nullpager(stream, generator, color):443def _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)451452453class 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 = extension465466 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 lines
476 if os.system(f"which {editor} >/dev/null 2>&1") == 0:477 return editor478 return "vi"479480 def edit_file(self, filename):480 def edit_file(self, filename: str) -> None:481 import subprocess482483 editor = self.get_editor()484 environ: t.Optional[t.Dict[str, str]] = None485486 if self.env:487 environ = os.environ.copy()488 environ.update(self.env)487 else:488 environ = None489490 try:491 c = subprocess.Popen(f'{editor} "{filename}"', env=environ, shell=True)492 exit_code = c.wait()493 if exit_code != 0:
4 unmodified lines
498 raise ClickException(499 _("{editor}: Editing failed: {e}").format(editor=editor, e=e)500 )501501 def edit(self, text):502 def edit(self, text: t.Optional[t.AnyStr]) -> t.Optional[t.AnyStr]:503 import tempfile504505 if not text:505 text = ""506507 is_bytes = isinstance(text, (bytes, bytearray))508509 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"512513 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")517518 fd, name = tempfile.mkstemp(prefix="editor-", suffix=self.extension)519 f: t.BinaryIO520521 try:522 with os.fdopen(fd, "wb") as f:522 f.write(text)523 f.write(data)524525 # 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 modified
10 unmodified lines
538539 with open(name, "rb") as f:540 rv = f.read()541541 if is_bytes:542 if isinstance(text, (bytes, bytearray)):543 return rv544544 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)548549549def open_url(url, wait=False, locate=False):550def open_url(url: str, wait: bool = False, locate: bool = False) -> int:551 import subprocess552553 def _unquote_file(url: str) -> str:554 from urllib.parse import unquote
20 unmodified lines
575 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)591592 try:593 if locate:
12 unmodified lines
606 return 0607 return 1608609609def _translate_ch_to_exc(ch):610def _translate_ch_to_exc(ch: str) -> t.Optional[BaseException]:611 if ch == "\x03":612 raise KeyboardInterrupt()613614 if ch == "\x04" and not WIN: # Unix-like, Ctrl+D615 raise EOFError()616617 if ch == "\x1a" and WIN: # Windows, Ctrl+Z618 raise EOFError()619620 return None621622623if WIN:624 import msvcrt625626 @contextlib.contextmanager622 def raw_terminal():623 yield627 def raw_terminal() -> t.Iterator[int]:628 yield -1629625 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 lines
656 # 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]661662 if echo:656 func = msvcrt.getwche663 func = msvcrt.getwche # type: ignore664 else:658 func = msvcrt.getwch665 func = msvcrt.getwch # type: ignore666667 rv = func()668669 if rv in ("\x00", "\xe0"):670 # \x00 and \xe0 are control characters that indicate special key,671 # see above.672 rv += func()673674 _translate_ch_to_exc(rv)675 return rv676677
1 unmodified line
679 import tty680 import termios681682 @contextlib.contextmanager674 def raw_terminal():683 def raw_terminal() -> t.Iterator[int]:684 f: t.Optional[t.TextIO]685 fd: int686687 if not isatty(sys.stdin):688 f = open("/dev/tty")689 fd = f.fileno()690 else:691 fd = sys.stdin.fileno()692 f = None693694 try:695 old_settings = termios.tcgetattr(fd)696697 try:698 tty.setraw(fd)699 yield fd700 finally:701 termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)702 sys.stdout.flush()703704 if f is not None:705 f.close()706 except termios.error:707 pass708694 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")712713 if echo and isatty(sys.stdout):714 sys.stdout.write(ch)715716 _translate_ch_to_exc(ch)717 return ch
modified:src/click/_textwrap.py+15 added-3 removed
1import textwrap2import typing as t3from contextlib import contextmanager456class 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)1516 if self.break_long_words:17 last = reversed_chunks[-1]
4 unmodified lines
22 elif not cur_line:23 cur_line.append(reversed_chunks.pop())2425 @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 += indent3132 try:33 yield34 finally:35 self.initial_indent = old_initial_indent36 self.subsequent_indent = old_subsequent_indent3730 def indent_only(self, text):38 def indent_only(self, text: str) -> str:39 rv = []4041 for idx, line in enumerate(text.splitlines()):42 indent = self.initial_indent4344 if idx > 0:45 indent = self.subsequent_indent4647 rv.append(f"{indent}{line}")4849 return "\n".join(rv)
modified:src/click/_unicodefun.py+20 added-13 removed
1 unmodified line
2import os3from gettext import gettext as _456def _verify_python_env():6def _verify_python_env() -> None:7 """Ensures that the environment is good for Unicode."""8 try:9 import locale9 from locale import getpreferredencoding1011 fs_enc = codecs.lookup(locale.getpreferredencoding()).name11 fs_enc = codecs.lookup(getpreferredencoding()).name12 except Exception:13 fs_enc = "ascii"1415 if fs_enc != "ascii":16 return1718 extra = [
9 unmodified lines
28 import subprocess2930 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 = ""4041 good_locales = set()42 has_c_utf8 = False4338 # Make sure we're operating on text here.39 if isinstance(rv, bytes):40 rv = rv.decode("ascii", "replace")4144 for line in rv.splitlines():45 locale = line.strip()4647 if locale.lower().endswith((".utf-8", ".utf8")):48 good_locales.add(locale)4950 if locale.lower() in ("c.utf8", "c.utf-8"):51 has_c_utf8 = True5253 if not good_locales:
24 unmodified lines
78 ).format(locales=", ".join(sorted(good_locales)))79 )8081 bad_locale = None8278 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_locale8687 if env_locale is not None:88 break8990 if bad_locale is not None:91 extra.append(92 _(93 "Click discovered that you exported a UTF-8 locale"
7 unmodified lines
modified:src/click/_winconsole.py+21 added-43 removed
7 unmodified lines
8# echo and prompt.9import io10import sys11import time12import typing as t13from ctypes import byref14from ctypes import c_char15from ctypes import c_char_p16from ctypes import c_int
161 unmodified lines
178 return bytes_written179180181class 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_stream185186 @property186 def name(self):187 def name(self) -> str:188 return self.buffer.name189189 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)198198 def writelines(self, lines):199 def writelines(self, lines: t.Iterable[t.AnyStr]) -> None:200 for line in lines:201 self.write(line)202202 def __getattr__(self, name):203 def __getattr__(self, name: str) -> t.Any:204 return getattr(self._text_stream, name)205205 def isatty(self):206 def isatty(self) -> bool:207 return self.buffer.isatty()208209 def __repr__(self):210 return f"<ConsoleStream name={self.name!r} encoding={self.encoding!r}>"211212212class WindowsChunkedWriter:213 """214 Wraps a stream (such as stdout), acting as a transparent proxy for all215 attribute access apart from method 'write()' which we wrap to write in216 limited chunks due to a Windows limitation on binary console streams.217 """218219 def __init__(self, wrapped):220 # double-underscore everything to prevent clashes with names of221 # attributes on the wrapped stream object.222 self.__wrapped = wrapped223224 def __getattr__(self, name):225 return getattr(self.__wrapped, name)226227 def write(self, text):228 total_to_write = len(text)229 written = 0230231 while written < total_to_write:232 to_write = min(total_to_write - written, MAX_BYTES_WRITTEN)233 self.__wrapped.write(text[written : written + to_write])234 written += to_write235236237def _get_text_stdin(buffer_stream):213def _get_text_stdin(buffer_stream: t.BinaryIO) -> t.TextIO:214 text_stream = _NonClosingTextIOWrapper(215 io.BufferedReader(_WindowsConsoleReader(STDIN_HANDLE)),216 "utf-16-le",217 "strict",218 line_buffering=True,219 )244 return ConsoleStream(text_stream, buffer_stream)220 return t.cast(t.TextIO, ConsoleStream(text_stream, buffer_stream))221222247def _get_text_stdout(buffer_stream):223def _get_text_stdout(buffer_stream: t.BinaryIO) -> t.TextIO:224 text_stream = _NonClosingTextIOWrapper(225 io.BufferedWriter(_WindowsConsoleWriter(STDOUT_HANDLE)),226 "utf-16-le",227 "strict",228 line_buffering=True,229 )254 return ConsoleStream(text_stream, buffer_stream)230 return t.cast(t.TextIO, ConsoleStream(text_stream, buffer_stream))231232257def _get_text_stderr(buffer_stream):233def _get_text_stderr(buffer_stream: t.BinaryIO) -> t.TextIO:234 text_stream = _NonClosingTextIOWrapper(235 io.BufferedWriter(_WindowsConsoleWriter(STDERR_HANDLE)),236 "utf-16-le",237 "strict",238 line_buffering=True,239 )264 return ConsoleStream(text_stream, buffer_stream)240 return t.cast(t.TextIO, ConsoleStream(text_stream, buffer_stream))241242267_stream_factories = {243_stream_factories: t.Mapping[int, t.Callable[[t.BinaryIO], t.TextIO]] = {244 0: _get_text_stdin,245 1: _get_text_stdout,246 2: _get_text_stderr,247}248249274def _is_console(f):250def _is_console(f: t.TextIO) -> bool:251 if not hasattr(f, "fileno"):252 return False253254 try:
4 unmodified lines
259 handle = msvcrt.get_osfhandle(fileno)260 return bool(GetConsoleMode(handle, byref(DWORD())))261262287def _get_windows_console_stream(f, encoding, errors):263def _get_windows_console_stream(264 f: t.TextIO, encoding: t.Optional[str], errors: t.Optional[str]265) -> t.Optional[t.TextIO]:266 if (267 get_buffer is not None268 and encoding in {"utf-16-le", None}269 and errors in {"strict", None}270 and _is_console(f)271 ):272 func = _stream_factories.get(f.fileno())273 if func is not None:296 f = getattr(f, "buffer", None)274 b = getattr(f, "buffer", None)275298 if f is None:276 if b is None:277 return None278301 return func(f)279 return func(b)
modified:src/click/core.py+569 added-346 removed
1import enum2import errno3import os4import sys5import typing6import typing as t7from collections import abc8from contextlib import contextmanager9from contextlib import ExitStack10from functools import partial11from functools import update_wrapper
21 unmodified lines
33from .types import _NumberRangeBase34from .types import BOOL35from .types import convert_type36from .types import IntRange37from .types import ParamType38from .utils import _detect_program_name39from .utils import _expand_args40from .utils import echo41from .utils import make_default_short_help42from .utils import make_str43from .utils import PacifyFlushWrapper4442_missing = object()45if t.TYPE_CHECKING:46 import typing_extensions as te47 from .shell_completion import CompletionItem4844SUBCOMMAND_METAVAR = "COMMAND [ARGS]..."45SUBCOMMANDS_METAVAR = "COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]..."49F = t.TypeVar("F", bound=t.Callable[..., t.Any])50V = t.TypeVar("V")515248def _fast_exit(code):53def _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.5657 :param code: Exit code.
2 unmodified lines
60 sys.stderr.flush()61 os._exit(code)626359def _complete_visible_commands(ctx, incomplete):64def _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.6970 :param ctx: Invocation context for the group.71 :param incomplete: Value being completed. May be empty.72 """73 multi = t.cast(MultiCommand, ctx.command)7466 for name in ctx.command.list_commands(ctx):75 for name in multi.list_commands(ctx):76 if name.startswith(incomplete):68 command = ctx.command.get_command(ctx, name)77 command = multi.get_command(ctx, name)7870 if not command.hidden:79 if command is not None and not command.hidden:80 yield name, command818274def _check_multicommand(base_command, cmd_name, cmd, register=False):83def _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 lines
103 f" {base_command.name!r})."104 )10510696def batch(iterable, batch_size):107def batch(iterable: t.Iterable[V], batch_size: int) -> t.List[t.Tuple[V, ...]]:108 return list(zip(*repeat(iter(iterable), batch_size)))109110111@contextmanager101def augment_usage_errors(ctx, param=None):112def 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 lines
126 e.ctx = ctx127 raise128129117def iter_params_for_processing(invocation_order, declaration_order):130def 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 """138123 def sort_key(item):139 def sort_key(item: "Parameter") -> t.Tuple[bool, float]:140 try:125 idx = invocation_order.index(item)141 idx: float = invocation_order.index(item)142 except ValueError:143 idx = float("inf")128 return (not item.is_eager, idx)144145 return not item.is_eager, idx146147 return sorted(declaration_order, key=sort_key)148149150class ParameterSource(enum.Enum):
114 unmodified lines
265266 #: The formatter class to create with :meth:`make_formatter`.267 #:268 #: .. versionadded:: 8.0252 formatter_class = HelpFormatter269 formatter_class: t.Type["HelpFormatter"] = HelpFormatter270271 def __init__(272 self,256 command,257 parent=None,258 info_name=None,259 obj=None,260 auto_envvar_prefix=None,261 default_map=None,262 terminal_width=None,263 max_content_width=None,264 resilient_parsing=False,265 allow_extra_args=None,266 allow_interspersed_args=None,267 ignore_unknown_options=None,268 help_option_names=None,269 token_normalize_func=None,270 color=None,271 show_default=None,272 ):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.281 self.params = {}298 self.params: t.Dict[str, t.Any] = {}299 #: the leftover arguments.283 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.288 self.protected_args = []305 self.protected_args: t.List[str] = []306307 if obj is None and parent is not None:308 obj = parent.obj309310 #: the user object stored.292 self.obj = obj293 self._meta = getattr(parent, "meta", {})311 self.obj: t.Optional[t.Any] = obj312 self._meta: t.Dict[str, t.Any] = getattr(parent, "meta", {})313314 #: 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)302 self.default_map = default_map322323 self.default_map: t.Optional[t.Dict[str, t.Any]] = default_map324325 #: 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 be
2 unmodified lines
331 #: 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`.314 self.invoked_subcommand = None335 self.invoked_subcommand: t.Optional[str] = None336337 if terminal_width is None and parent is not None:338 terminal_width = parent.terminal_width339340 #: The width of the terminal (None is autodetection).319 self.terminal_width = terminal_width341 self.terminal_width: t.Optional[int] = terminal_width342343 if max_content_width is None and parent is not None:344 max_content_width = parent.max_content_width345346 #: The maximum width of formatted content (None implies a sensible347 #: default which is 80 for most things).325 self.max_content_width = max_content_width348 self.max_content_width: t.Optional[int] = max_content_width349350 if allow_extra_args is None:351 allow_extra_args = command.allow_extra_args352353 #: 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_args358359 if allow_interspersed_args is None:360 allow_interspersed_args = command.allow_interspersed_args361362 #: Indicates if the context allows mixing of arguments and363 #: options or not.364 #:365 #: .. versionadded:: 3.0341 self.allow_interspersed_args = allow_interspersed_args366 self.allow_interspersed_args: bool = allow_interspersed_args367368 if ignore_unknown_options is None:369 ignore_unknown_options = command.ignore_unknown_options370371 #: 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.0353 self.ignore_unknown_options = ignore_unknown_options379 self.ignore_unknown_options: bool = ignore_unknown_options380381 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"]386387 #: The names for the help options.362 self.help_option_names = help_option_names388 self.help_option_names: t.List[str] = help_option_names389390 if token_normalize_func is None and parent is not None:391 token_normalize_func = parent.token_normalize_func392393 #: An optional normalization function for tokens. This is394 #: options, choices, commands etc.369 self.token_normalize_func = token_normalize_func395 self.token_normalize_func: t.Optional[396 t.Callable[[str], str]397 ] = token_normalize_func398399 #: 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.374 self.resilient_parsing = resilient_parsing402 self.resilient_parsing: bool = resilient_parsing403404 # 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 lines
414 f"{parent.auto_envvar_prefix}_{self.info_name.upper()}"415 )416 else:417 auto_envvar_prefix = auto_envvar_prefix.upper()418419 if auto_envvar_prefix is not None:420 auto_envvar_prefix = auto_envvar_prefix.replace("-", "_")392 self.auto_envvar_prefix = auto_envvar_prefix421422 self.auto_envvar_prefix: t.Optional[str] = auto_envvar_prefix423424 if color is None and parent is not None:425 color = parent.color426427 #: Controls if styling output is wanted or not.398 self.color = color428 self.color: t.Optional[bool] = color429430 if show_default is None and parent is not None:431 show_default = parent.show_default432433 #: Show option default values when formatting help text.404 self.show_default = show_default434 self.show_default: t.Optional[bool] = show_default435406 self._close_callbacks = []436 self._close_callbacks: t.List[t.Callable[[], t.Any]] = []437 self._depth = 0408 self._parameter_source = {}438 self._parameter_source: t.Dict[str, ParameterSource] = {}439 self._exit_stack = ExitStack()440411 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 lines
458 "ignore_unknown_options": self.ignore_unknown_options,459 "auto_envvar_prefix": self.auto_envvar_prefix,460 }461432 def __enter__(self):462 def __enter__(self) -> "Context":463 self._depth += 1464 push_context(self)465 return self466437 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()472473 @contextmanager444 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 cleanup
29 unmodified lines
508 if not cleanup:509 self._depth -= 1510511 @property482 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 lines
535 .. versionadded:: 5.0536 """537 return self._meta538509 def make_formatter(self):539 def make_formatter(self) -> HelpFormatter:540 """Creates the :class:`~click.HelpFormatter` for the help and541 usage output.542543 To quickly customize the formatter class used without overriding
5 unmodified lines
549 return self.formatter_class(550 width=self.terminal_width, max_width=self.max_content_width551 )552523 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 lines
578 .. versionadded:: 8.0579 """580 return self._exit_stack.enter_context(context_manager)581552 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.584585 This can be used to close resources opened during the script586 execution. Resources that support Python's context manager
3 unmodified lines
590 :param f: The function to execute on teardown.591 """592 return self._exit_stack.callback(f)593564 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 line
600 # In case the context is reused, create a new exit stack.601 self._exit_stack = ExitStack()602603 @property574 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 line
610 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]614615 if isinstance(self.parent.command, Command):584 for param in self.parent.command.get_params(self):585 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))618619 rv = f"{' '.join(parent_command_path)} {rv}"620 return rv.lstrip()621589 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 node628596 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."""598 node = self631 node: t.Optional["Context"] = self632633 while node is not None:634 if isinstance(node.obj, object_type):635 return node.obj636637 node = node.parent638639 return None640604 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 rv649613 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 ...655656 @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 ...661662 def lookup_default(self, name: str, call: bool = True) -> t.Optional[t.Any]:663 """Get the default for a parameter from :attr:`default_map`.664665 :param name: Name of the parameter.666 :param call: If the default is a callable, call it. Disable to
9 unmodified lines
676 return value()677678 return value679680 return None681631 def fail(self, message):682 def fail(self, message: str) -> t.NoReturn:683 """Aborts the execution of the program with a specific error684 message.685686 :param message: the error message to fail with.687 """688 raise UsageError(message, self)689639 def abort(self):690 def abort(self) -> t.NoReturn:691 """Aborts the script."""692 raise Abort()693643 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)697647 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)703653 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)709659 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.713714 :meta private:715 """716 return type(self)(command, info_name=command.name, parent=self)717667 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:726727 1. the first argument can be a callback and all other arguments and
11 unmodified lines
739 .. versionchanged:: 8.0740 All ``kwargs`` are tracked in :attr:`params` so they will be741 passed if :meth:`forward` is called at multiple levels.742 """687 self, callback = args[:2]688 ctx = self743 if isinstance(__callback, Command):744 other_cmd = __callback745690 # It's also possible to invoke another command which might or691 # might not have a callback. In that case we also fill692 # in defaults and make a new context for this command.693 if isinstance(callback, Command):694 other_cmd = callback695 callback = other_cmd.callback696697 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.callback752702 ctx = self._make_sub_context(other_cmd)753 ctx = __self._make_sub_context(other_cmd)754755 for param in other_cmd.params:756 if param.name not in kwargs and param.expose_value:706 kwargs[param.name] = param.get_default(ctx)757 kwargs[param.name] = param.get_default(ctx) # type: ignore758759 # Track all kwargs as params, so that forward() will pass760 # them on in subsequent calls.761 ctx.params.update(kwargs)762 else:763 ctx = __self764712 args = args[2:]713 with augment_usage_errors(self):765 with augment_usage_errors(__self):766 with ctx:715 return callback(*args, **kwargs)767 return __callback(*args, **kwargs)768717 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.775776 .. versionchanged:: 8.0777 All ``kwargs`` are tracked in :attr:`params` so they will be778 passed if ``forward`` is called at multiple levels.779 """726 self, cmd = args[:2]727780 # Can only forward to other commands, not direct callbacks.729 if not isinstance(cmd, Command):781 if not isinstance(__cmd, Command):782 raise TypeError("Callback is not a command.")783732 for param in self.params:784 for param in __self.params:785 if param not in kwargs:734 kwargs[param] = self.params[param]786 kwargs[param] = __self.params[param]787736 return self.invoke(cmd, **kwargs)788 return __self.invoke(__cmd, *args, **kwargs)789738 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.793794 :param name: The name of the parameter.795 :param source: A member of :class:`~click.core.ParameterSource`.796 """797 self._parameter_source[name] = source798747 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.802803 This can be useful for determining when a user specified a value
35 unmodified lines
839840 #: The context class to create with :meth:`make_context`.841 #:842 #: .. versionadded:: 8.0791 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 = False850799 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 = name861862 if context_settings is None:863 context_settings = {}864865 #: an optional dictionary with defaults passed to the context.808 self.context_settings = context_settings866 self.context_settings: t.Dict[str, t.Any] = context_settings867810 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 lines
878 .. versionadded:: 8.0879 """880 return {"name": self.name}881824 def __repr__(self):882 def __repr__(self) -> str:883 return f"<{self.__class__.__name__} {self.name}>"884827 def get_usage(self, ctx):885 def get_usage(self, ctx: Context) -> str:886 raise NotImplementedError("Base commands cannot get usage")887830 def get_help(self, ctx):888 def get_help(self, ctx: Context) -> str:889 raise NotImplementedError("Base commands cannot get help")890833 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.901902 To quickly customize the context class used without overriding903 this method, set the :attr:`context_class` attribute.904841 :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's845 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 lines
918 for key, value in self.context_settings.items():919 if key not in extra:920 extra[key] = value921858 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 )925926 with ctx.scope(cleanup=False):927 self.parse_args(ctx, args)928 return ctx929864 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.")936871 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")942877 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.946947 Any command could be part of a chained multi-command, so sibling
6 unmodified lines
954 .. versionadded:: 8.0955 """956 from click.shell_completion import CompletionItem957892 results = []958 results: t.List["CompletionItem"] = []959960 while ctx.parent is not None:961 ctx = ctx.parent962
5 unmodified lines
968 )969970 return results971972 @typing.overload973 def main(974 self,908 args=None,909 prog_name=None,910 complete_var=None,911 standalone_mode=True,912 **extra,913 ):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 ...982983 @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 ...993994 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 lines
1076 e.show()1077 sys.exit(e.exit_code)1078 except OSError as e:1079 if e.errno == errno.EPIPE:992 sys.stdout = PacifyFlushWrapper(sys.stdout)993 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 lines
1100 raise1101 echo(_("Aborted!"), file=sys.stderr)1102 sys.exit(1)11031016 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 lines
11281129 rv = shell_complete(self, ctx_args, prog_name, complete_var, instruction)1130 _fast_exit(rv)11311039 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)11351136
33 unmodified lines
1170 """11711172 def __init__(1173 self,1081 name,1082 context_settings=None,1083 callback=None,1084 params=None,1085 help=None,1086 epilog=None,1087 short_help=None,1088 options_metavar="[OPTIONS]",1089 add_help_option=True,1090 no_args_is_help=False,1091 hidden=False,1092 deprecated=False,1093 ):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.1101 self.params = params or []1194 self.params: t.List["Parameter"] = params or []11951196 # 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]12001201 self.help = help1202 self.epilog = epilog1203 self.options_metavar = options_metavar1204 self.short_help = short_help
1 unmodified line
1206 self.no_args_is_help = no_args_is_help1207 self.hidden = hidden1208 self.deprecated = deprecated12091115 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 lines
1218 deprecated=self.deprecated,1219 )1220 return info_dict12211127 def __repr__(self):1128 return f"<{self.__class__.__name__} {self.name}>"11291130 def get_usage(self, ctx):1222 def get_usage(self, ctx: Context) -> str:1223 """Formats the usage line into a string and returns it.12241225 Calls :meth:`format_usage` internally.1226 """1227 formatter = ctx.make_formatter()1228 self.format_usage(ctx, formatter)1229 return formatter.getvalue().rstrip("\n")12301139 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)12341235 if help_option is not None:1143 rv = rv + [help_option]1236 rv = [*rv, help_option]12371238 return rv12391146 def format_usage(self, ctx, formatter):1240 def format_usage(self, ctx: Context, formatter: HelpFormatter) -> None:1241 """Writes the usage line into the formatter.12421243 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))12471154 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 []12531254 for param in self.get_params(ctx):1255 rv.extend(param.get_usage_pieces(ctx))12561257 return rv12581163 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)1169 return all_names1265 return list(all_names)12661171 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)12701271 if not help_options or not self.add_help_option:1175 return1272 return None12731177 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 lines
1284 callback=show_help,1285 help=_("Show this message and exit."),1286 )12871191 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 parser12941198 def get_help(self, ctx):1295 def get_help(self, ctx: Context) -> str:1296 """Formats the help into a string and returns it.12971298 Calls :meth:`format_help` internally.1299 """1300 formatter = ctx.make_formatter()1301 self.format_help(ctx, formatter)1302 return formatter.getvalue().rstrip("\n")13031207 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 lines
1314 text = _("(Deprecated) {text}").format(text=text)13151316 return text.strip()13171221 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.13201321 This is a low-level method called by :meth:`get_help`.1322
8 unmodified lines
1331 self.format_help_text(ctx, formatter)1332 self.format_options(ctx, formatter)1333 self.format_epilog(ctx, formatter)13341238 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 ""13381339 if self.deprecated:
4 unmodified lines
13441345 with formatter.indentation():1346 formatter.write_text(text)13471251 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 lines
1356 if opts:1357 with formatter.section(_("Options")):1358 formatter.write_dl(opts)13591263 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)13661270 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 lines
13861387 ctx.args = args1388 return args13891293 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:1298 echo(1299 style(1300 _("DeprecationWarning: The command {name!r} is deprecated.").format(1301 name=self.name1302 ),1303 fg="red",1304 ),1305 err=True,1306 )1395 message = _(1396 "DeprecationWarning: The command {name!r} is deprecated."1397 ).format(name=self.name)1398 echo(style(message, fg="red"), err=True)13991400 if self.callback is not None:1401 return ctx.invoke(self.callback, **ctx.params)14021311 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.14061407 :param ctx: Invocation context for this command.
2 unmodified lines
1410 .. versionadded:: 8.01411 """1412 from click.shell_completion import CompletionItem14131322 results = []1414 results: t.List["CompletionItem"] = []14151416 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.multiple1331 and ctx.get_parameter_source(param.name)1423 and ctx.get_parameter_source(param.name) # type: ignore1424 is ParameterSource.COMMANDLINE1425 )1426 ):1427 continue14281429 results.extend(1430 CompletionItem(name, help=param.help)1339 for name in param.opts + param.secondary_opts1431 for name in [*param.opts, *param.secondary_opts]1432 if name.startswith(incomplete)1433 )14341435 results.extend(super().shell_complete(ctx, incomplete))
29 unmodified lines
1465 allow_interspersed_args = False14661467 def __init__(1468 self,1377 name=None,1378 invoke_without_command=False,1379 no_args_is_help=None,1380 subcommand_metavar=None,1381 chain=False,1382 result_callback=None,1383 **attrs,1384 ):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)14781479 if no_args_is_help is None:1480 no_args_is_help = not invoke_without_command14811482 self.no_args_is_help = no_args_is_help1483 self.invoke_without_command = invoke_without_command14841485 if subcommand_metavar is None:1486 if chain:1392 subcommand_metavar = SUBCOMMANDS_METAVAR1487 subcommand_metavar = "COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]..."1488 else:1394 subcommand_metavar = SUBCOMMAND_METAVAR1489 subcommand_metavar = "COMMAND [ARGS]..."14901491 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 lines
1501 "Multi commands in chain mode cannot have"1502 " optional arguments."1503 )15041409 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 = {}15081509 for name in self.list_commands(ctx):1510 command = self.get_command(ctx, name)15111512 if command is None:1513 continue15141515 sub_ctx = ctx._make_sub_context(command)15161517 with sub_ctx.scope(cleanup=False):1518 commands[name] = command.to_info_dict(sub_ctx)15191520 info_dict.update(commands=commands, chain=self.chain)1521 return info_dict15221423 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 rv15271428 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)15311432 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 subcommand
20 unmodified lines
15571558 .. versionadded:: 3.01559 """15601461 def decorator(f):1561 def decorator(f: F) -> F:1562 old_callback = self._result_callback15631564 if old_callback is None or replace:1565 self._result_callback = f1566 return f15671468 def function(__value, *args, **kwargs):1469 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)15711471 self._result_callback = rv = update_wrapper(function, f)1572 self._result_callback = rv = update_wrapper(t.cast(F, function), f)1573 return rv15741575 return decorator15761476 def resultcallback(self, replace=False):1577 def resultcallback(self, replace: bool = False) -> t.Callable[[F], F]:1578 import warnings15791580 warnings.warn(1581 "'resultcallback' has been renamed to 'result_callback'."
2 unmodified lines
1584 stacklevel=2,1585 )1586 return self.result_callback(replace=replace)15871487 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 lines
1612 if rows:1613 with formatter.section(_("Commands")):1614 formatter.write_dl(rows)16151515 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 lines
1627 ctx.protected_args, ctx.args = rest[:1], rest[1:]16281629 return ctx.args16301530 def invoke(self, ctx):1531 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 lines
1644 return _process_result([] if self.chain else None)1645 ctx.fail(_("Missing command."))16461647 # Fetch args back out1547 args = ctx.protected_args + ctx.args1648 args = [*ctx.protected_args, *ctx.args]1649 ctx.args = []1650 ctx.protected_args = []16511652 # If we're not in chain mode, we only allow the invocation of a
3 unmodified lines
1656 # 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 lines
1678 # 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 lines
1695 with sub_ctx:1696 rv.append(sub_ctx.command.invoke(sub_ctx))1697 return _process_result(rv)16981596 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_name17041705 # Get the command
16 unmodified lines
1722 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:]17251621 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 """1625 raise NotImplementedError()1730 raise NotImplementedError17311627 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 []17371633 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 lines
1775 #: as the default :class:`Command` class. This is useful to make all1776 #: subcommands use a custom command class.1777 #:1778 #: .. versionadded:: 8.01674 command_class: t.Optional[t.Type[BaseCommand]] = None1779 command_class: t.Optional[t.Type[Command]] = None17801781 #: 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 lines
1790 #: .. 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]17931689 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)18011802 if commands is None:1803 commands = {}1694 elif isinstance(commands, (list, tuple)):1695 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}18061807 #: The registered subcommands by their exported names.1698 self.commands = commands1808 self.commands: t.Dict[str, Command] = commands18091700 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.name
1 unmodified line
1816 raise TypeError("Command has no name.")1817 _check_multicommand(self, name, cmd, register=True)1818 self.commands[name] = cmd18191710 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 lines
18351836 if self.command_class is not None and "cls" not in kwargs:1837 kwargs["cls"] = self.command_class18381727 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 cmd18431844 return decorator18451734 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 lines
1864 kwargs["cls"] = type(self)1865 else:1866 kwargs["cls"] = self.group_class18671754 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 cmd18721873 return decorator18741761 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)18771764 def list_commands(self, ctx):1878 def list_commands(self, ctx: Context) -> t.List[str]:1879 return sorted(self.commands)188018811882class CommandCollection(MultiCommand):
2 unmodified lines
1885 that accepts a list of different multi commands as sources and1886 provides all the commands for each of them.1887 """18881775 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.1778 self.sources = sources or []1897 self.sources: t.List[MultiCommand] = sources or []18981780 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)19021784 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)19061907 if rv is not None:1908 if self.chain:1909 _check_multicommand(self, cmd_name, rv)19101911 return rv19121792 def list_commands(self, ctx):1793 rv = set()1913 return None19141915 def list_commands(self, ctx: Context) -> t.List[str]:1916 rv: t.Set[str] = set()19171918 for source in self.sources:1919 rv.update(source.list_commands(ctx))19201921 return sorted(rv)192219231799def _check_iter(value):1924def _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 lines
2008 param_type_name = "parameter"20092010 def __init__(2011 self,1887 param_decls=None,1888 type=None,1889 required=False,1890 default=None,1891 callback=None,1892 nargs=None,1893 multiple=False,1894 metavar=None,1895 expose_value=True,1896 is_eager=False,1897 envvar=None,1898 shell_complete=None,1899 autocompletion=None,1900 ):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 lines
2065 DeprecationWarning,2066 stacklevel=2,2067 )20681936 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 CompletionItem20732074 out = []20751941 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 lines
2126 raise ValueError(2127 f"'default' {subject} must match nargs={nargs}."2128 )21291995 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.21332134 Use :meth:`click.Context.to_info_dict` to traverse the entire
13 unmodified lines
2148 "default": self.default,2149 "envvar": self.envvar,2150 }21512017 def __repr__(self):2152 def __repr__(self) -> str:2153 return f"<{self.__class__.__name__} {self.name}>"21542155 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()21592160 @property2021 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 """2025 return self.name2165 return self.name # type: ignore21662027 def make_metavar(self):2167 def make_metavar(self) -> str:2168 if self.metavar is not None:2169 return self.metavar21702171 metavar = self.type.get_metavar(self)21722173 if metavar is None:2174 metavar = self.type.name.upper()21752176 if self.nargs != 1:2177 metavar += "..."21782179 return metavar21802037 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 ...21862187 @typing.overload2188 def get_default(2189 self, ctx: Context, call: bool = ...2190 ) -> t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]]:2191 ...21922193 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.21982199 :param ctx: Current context.
5 unmodified lines
22052206 .. versionchanged:: 8.02207 Added the ``call`` parameter.2208 """2051 value = ctx.lookup_default(self.name, call=False)2209 value = ctx.lookup_default(self.name, call=False) # type: ignore22102211 if value is None:2212 value = self.default2213
5 unmodified lines
2219 value = value()22202221 return self.type_cast_value(ctx, value)22222065 def add_to_parser(self, parser, ctx):2066 pass2223 def add_to_parser(self, parser: OptionParser, ctx: Context) -> None:2224 raise NotImplementedError()22252068 def consume_value(self, ctx, opts):2069 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.COMMANDLINE22312232 if value is None:2233 value = self.value_from_envvar(ctx)2234 source = ParameterSource.ENVIRONMENT22352236 if value is None:2077 value = ctx.lookup_default(self.name)2237 value = ctx.lookup_default(self.name) # type: ignore2238 source = ParameterSource.DEFAULT_MAP22392240 if value is None:2241 value = self.get_default(ctx)2242 source = ParameterSource.DEFAULT22432244 return value, source22452086 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 None22522093 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 lines
2261 _("Value must be an iterable."), ctx=ctx, param=self2262 ) from None22632264 if self.nargs == 1 or self.type.is_composite:2105 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:22692108 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))22722273 else: # nargs > 122742113 def convert(value):2275 def convert(value: t.Any) -> t.Tuple:2276 value = tuple(check_iter(value))22772278 if len(value) != self.nargs:2279 raise BadParameter(
12 unmodified lines
2292 return tuple(convert(x) for x in check_iter(value))22932294 return convert(value)22952134 def value_is_missing(self, value):2296 def value_is_missing(self, value: t.Any) -> bool:2297 if value is None:2298 return True22992300 if (self.nargs != 1 or self.multiple) and value == ():2301 return True23022303 return False23042143 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)23082309 if self.required and self.value_is_missing(value):
3 unmodified lines
2313 value = self.callback(ctx, self, value)23142315 return value23162155 def resolve_envvar_value(self, ctx):2317 def resolve_envvar_value(self, ctx: Context) -> t.Optional[str]:2318 if self.envvar is None:2157 return2319 return None23202159 if isinstance(self.envvar, (tuple, list)):2321 if isinstance(self.envvar, str):2322 rv = os.environ.get(self.envvar)23232324 if rv:2325 return rv2326 else:2327 for envvar in self.envvar:2328 rv = os.environ.get(envvar)23292330 if rv:2331 return rv2165 else:2166 rv = os.environ.get(self.envvar)23322168 if rv:2169 return rv2333 return None23342171 def value_from_envvar(self, ctx):2172 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)23372338 if rv is not None and self.nargs != 1:2339 rv = self.type.split_envvar_value(rv)23402341 return rv23422179 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)2182 ctx.set_parameter_source(self.name, source)2348 ctx.set_parameter_source(self.name, source) # type: ignore23492350 try:2351 value = self.process_value(ctx, value)2352 except Exception:
2 unmodified lines
23552356 value = None23572358 if self.expose_value:2193 ctx.params[self.name] = value2359 ctx.params[self.name] = value # type: ignore23602361 return value, args23622197 def get_help_record(self, ctx):2363 def get_help_record(self, ctx: Context) -> t.Optional[t.Tuple[str, str]]:2364 pass23652200 def get_usage_pieces(self, ctx):2366 def get_usage_pieces(self, ctx: Context) -> t.List[str]:2367 return []23682203 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)23752210 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 lines
2391 from click.shell_completion import CompletionItem23922393 results = [CompletionItem(c) for c in results]23942229 return results2395 return t.cast(t.List["CompletionItem"], results)23962397 return self.type.shell_complete(ctx, self, incomplete)23982399
43 unmodified lines
2443 param_type_name = "option"24442445 def __init__(2446 self,2281 param_decls=None,2282 show_default=False,2283 prompt=False,2284 confirmation_prompt=False,2285 prompt_required=True,2286 hide_input=False,2287 is_flag=None,2288 flag_value=None,2289 multiple=False,2290 count=False,2291 allow_from_autoenv=True,2292 type=None,2293 help=None,2294 hidden=False,2295 show_choices=True,2296 show_envvar=False,2297 **attrs,2298 ):2299 default_is_missing = attrs.get("default", _missing) is _missing2447 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)24672468 if prompt is True:2469 if self.name is None:2470 raise TypeError("'name' is required with 'prompt=True'.")24712303 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:2307 prompt_text = prompt2476 prompt_text = t.cast(str, prompt)24772478 self.prompt = prompt_text2479 self.confirmation_prompt = confirmation_prompt2480 self.prompt_required = prompt_required
19 unmodified lines
2500 # flag if flag_value is set.2501 self._flag_needs_value = flag_value is not None25022503 if is_flag and default_is_missing:2335 self.default = False2504 self.default: t.Union[t.Any, t.Callable[[], t.Any]] = False25052506 if flag_value is None:2507 flag_value = not self.default25082340 self.is_flag = is_flag2341 self.flag_value = flag_value2509 self.is_flag: bool = is_flag2510 self.flag_value: t.Any = flag_value25112512 if self.is_flag and isinstance(self.flag_value, bool) and type in [None, bool]:2344 self.type = BOOL2513 self.type: "ParamType" = BOOL2514 self.is_bool_flag = True2515 else:2516 self.is_bool_flag = False2517
32 unmodified lines
25502551 if self.is_flag:2552 raise TypeError("'count' is not valid with 'is_flag'.")25532385 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 lines
2562 hidden=self.hidden,2563 )2564 return info_dict25652397 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 lines
2615 )26162617 return name, opts, secondary_opts26182448 def add_to_parser(self, parser, ctx):2449 kwargs = {2450 "dest": self.name,2451 "nargs": self.nargs,2452 "obj": self,2453 }24542619 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"26262627 if self.is_flag:2463 kwargs.pop("nargs", None)2464 action_const = f"{action}_const"2628 action = f"{action}_const"26292630 if self.is_bool_flag and self.secondary_opts:2466 parser.add_option(self.opts, action=action_const, const=True, **kwargs)2631 parser.add_option(2468 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(2472 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:2475 kwargs["action"] = action2476 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 )26572478 def get_help_record(self, ctx):2658 def get_help_record(self, ctx: Context) -> t.Optional[t.Tuple[str, str]]:2659 if self.hidden:2480 return2481 any_prefix_is_slash = []2660 return None26612483 def _write_opts(opts):2662 any_prefix_is_slash = False26632664 def _write_opts(opts: t.Sequence[str]) -> str:2665 nonlocal any_prefix_is_slash26662667 rv, any_slashes = join_options(opts)26682669 if any_slashes:2486 any_prefix_is_slash[:] = [True]2670 any_prefix_is_slash = True26712672 if not self.is_flag and not self.count:2673 rv += f" {self.make_metavar()}"26742675 return rv26762677 rv = [_write_opts(self.opts)]26782679 if self.secondary_opts:2680 rv.append(_write_opts(self.secondary_opts))26812682 help = self.help or ""2683 extra = []26842685 if self.show_envvar:2686 envvar = self.envvar26872688 if envvar is None:2500 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()}"26952696 if envvar is not None:2697 var_str = (2504 ", ".join(str(d) for d in envvar)2505 if isinstance(envvar, (list, tuple))2506 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))27032704 default_value = self.get_default(ctx, call=False)
2 unmodified lines
2707 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:2517 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 lines
2731 extra.append(range_str)27322733 if self.required:2734 extra.append(_("required"))27352736 if extra:2737 extra_str = ";".join(extra)2738 help = f"{help} [{extra_str}]" if help else f"[{extra_str}]"27392740 return ("; " if any_prefix_is_slash else " / ").join(rv), help27412547 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 ...27472748 @typing.overload2749 def get_default(2750 self, ctx: Context, call: bool = ...2751 ) -> t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]]:2752 ...27532754 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:2555 return param.flag_value2764 return param.flag_value # type: ignore27652766 return None27672768 return super().get_default(ctx, call=call)27692561 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 None27772778 # Calculate the default before prompting anything to be stable.2779 default = self.get_default(ctx)27802781 # If this is a prompt for a flag we need to handle this
10 unmodified lines
2792 confirmation_prompt=self.confirmation_prompt,2793 value_proc=lambda x: self.process_value(ctx, x),2794 )27952585 def resolve_envvar_value(self, ctx):2796 def resolve_envvar_value(self, ctx: Context) -> t.Optional[str]:2797 rv = super().resolve_envvar_value(ctx)27982799 if rv is not None:2800 return rv28012591 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)28092595 if rv:2596 return rv2810 return rv28112598 def value_from_envvar(self, ctx):2599 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)28142815 if rv is None:2816 return None28172818 value_depth = (self.nargs != 1) + bool(self.multiple)28192606 if value_depth > 0 and rv is not None:2820 if value_depth > 0:2821 rv = self.type.split_envvar_value(rv)28222823 if self.multiple and self.nargs != 1:2824 rv = batch(rv, self.nargs)28252826 return rv28272614 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)28322833 # The parser will emit a sentinel value if the option can be2834 # given as a flag without a value. This is different from None
29 unmodified lines
2864 """28652866 param_type_name = "argument"28672652 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 lines
2886 if self.default is not None and self.nargs == -1:2887 raise TypeError("'default' is not supported for nargs=-1.")28882889 @property2669 def human_readable_name(self):2890 def human_readable_name(self) -> str:2891 if self.metavar is not None:2892 return self.metavar2672 return self.name.upper()2893 return self.name.upper() # type: ignore28942674 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:2679 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 var29062686 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 lines
2920 f" {len(decls)}."2921 )2922 return name, [arg], []29232701 def get_usage_pieces(self, ctx):2924 def get_usage_pieces(self, ctx: Context) -> t.List[str]:2925 return [self.make_metavar()]29262704 def get_error_hint(self, ctx):2927 def get_error_hint(self, ctx: Context) -> str:2928 return repr(self.make_metavar())29292707 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
1import inspect2import types3import typing as t4from functools import update_wrapper5from gettext import gettext as _67from .core import Argument8from .core import Command9from .core import Context10from .core import Group11from .core import Option12from .core import Parameter13from .globals import get_current_context14from .utils import echo1513if t.TYPE_CHECKING:14 F = t.TypeVar("F", bound=t.Callable[..., t.Any])16F = t.TypeVar("F", bound=t.Callable[..., t.Any])17FC = t.TypeVar("FC", t.Callable[..., t.Any], Command)181917def pass_context(f: "F") -> "F":20def pass_context(f: F) -> F:21 """Marks a callback as wanting to receive the current context22 object as first argument.23 """2422 def new_func(*args, **kwargs):25 def new_func(*args, **kwargs): # type: ignore26 return f(get_current_context(), *args, **kwargs)2725 return update_wrapper(t.cast("F", new_func), f)28 return update_wrapper(t.cast(F, new_func), f)293028def pass_obj(f: "F") -> "F":31def 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 """3634 def new_func(*args, **kwargs):37 def new_func(*args, **kwargs): # type: ignore38 return f(get_current_context().obj, *args, **kwargs)3937 return update_wrapper(t.cast("F", new_func), f)40 return update_wrapper(t.cast(F, new_func), f)414243def make_pass_decorator(44 object_type: t.Type, ensure: bool = False
19 unmodified lines
64 :param ensure: if set to `True`, a new object will be created and65 remembered on the context if it's not there yet.66 """6765 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()7172 if ensure:73 obj = ctx.ensure_object(object_type)
8 unmodified lines
82 )8384 return ctx.invoke(f, obj, *args, **kwargs)8583 return update_wrapper(t.cast("F", new_func), f)86 return update_wrapper(t.cast(F, new_func), f)8788 return decorator8990
11 unmodified lines
102103 .. versionadded:: 8.0104 """105103 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)111109 return update_wrapper(t.cast("F", new_func), f)112 return update_wrapper(t.cast(F, new_func), f)113114 if doc_description is None:115 doc_description = f"the {key!r} key from :attr:`click.Context.meta`"116
3 unmodified lines
120 )121 return decorator122123121def _make_command(f, name, attrs, cls):124def _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.")132133 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 = []139140 help = attrs.get("help")141142 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)146147 attrs["help"] = help148 return cls(149 name=name or f.__name__.lower().replace("_", "-"),150 callback=f,
1 unmodified line
152 **attrs,153 )154155146def command(name=None, cls=None, **attrs):156def 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 lines
179 """180 if cls is None:181 cls = Command182169 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 cmd187188 return decorator189190177def group(name=None, **attrs):191def 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))198199186def _param_memo(f, param):200def _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: ignore206207 f.__click_params__.append(param) # type: ignore208195def argument(*param_decls, **attrs):209210def 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 manually
2 unmodified lines
217 :param cls: the argument class to instantiate. This defaults to218 :class:`Argument`.219 """220206 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 f225226 return decorator227228214def option(*param_decls, **attrs):229def 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 manually
2 unmodified lines
236 :param cls: the option class to instantiate. This defaults to237 :class:`Option`.238 """239225 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()243244 if "help" in option_attrs:
4 unmodified lines
249250 return decorator251252238def confirmation_option(*param_decls, **kwargs):253def 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.256257 :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 """261247 def callback(ctx, param, value):262 def callback(ctx: Context, param: Parameter, value: bool) -> None:263 if not value:264 ctx.abort()265266 if not param_decls:
6 unmodified lines
273 kwargs.setdefault("help", "Confirm the action without prompting.")274 return option(*param_decls, **kwargs)275276262def password_option(*param_decls, **kwargs):277def 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.280281 :param param_decls: One or more option names. Defaults to the single
9 unmodified lines
291 return option(*param_decls, **kwargs)292293294def 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.304305 If ``version`` is not provided, Click will try to detect it using
30 unmodified lines
336 message = _("%(prog)s, version %(version)s")337338 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 frame
6 unmodified lines
352353 if package_name:354 package_name = package_name.partition(".")[0]355339 def callback(ctx, param, value):356 def callback(ctx: Context, param: Parameter, value: bool) -> None:357 if not value or ctx.resilient_parsing:358 return359360 nonlocal prog_name
2 unmodified lines
363 if prog_name is None:364 prog_name = ctx.find_root().info_name365366 if version is None and package_name is not None:367 metadata: t.Optional[types.ModuleType]368369 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 = None377378 if metadata is None:
1 unmodified line
380 "Install 'importlib_metadata' to get the version on Python < 3.8."381 )382383 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 lines
393 f"Could not determine the version for {package_name!r} automatically."394 )395396 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 lines
410 kwargs["callback"] = callback411 return option(*param_decls, **kwargs)412413394def help_option(*param_decls, **kwargs):414def 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.417418 This is usually unnecessary, as the ``--help`` option is added to
4 unmodified lines
423 value ``"--help"``.424 :param kwargs: Extra arguments are passed to :func:`option`.425 """426407 def callback(ctx, param, value):427 def callback(ctx: Context, param: Parameter, value: bool) -> None:428 if not value or ctx.resilient_parsing:429 return430431 echo(ctx.get_help(), color=ctx.color)
11 unmodified lines
modified:src/click/exceptions.py+57 added-26 removed
1import os2import typing as t3from gettext import gettext as _4from gettext import ngettext56from ._compat import get_text_stderr7from .utils import echo89if t.TYPE_CHECKING:10 from .core import Context11 from .core import Parameter129def _join_param_hints(param_hint):10 if isinstance(param_hint, (tuple, list)):1314def _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)1920 return param_hint212223class ClickException(Exception):
1 unmodified line
2526 #: The exit code for this exception.27 exit_code = 12821 def __init__(self, message):29 def __init__(self, message: str) -> None:30 super().__init__(message)31 self.message = message3225 def format_message(self):33 def format_message(self) -> str:34 return self.message3528 def __str__(self):36 def __str__(self) -> str:37 return self.message3831 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()4243 echo(_("Error: {message}").format(message=self.format_message()), file=file)444546class UsageError(ClickException):
6 unmodified lines
53 """5455 exit_code = 25648 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 None6153 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 lines
99 a string it's used as such, if it's a list then100 each item is quoted and separated.101 """10291 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_hint11396 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)121122 return _("Invalid value for {param_hint}: {message}").format(
13 unmodified lines
136 ``'option'`` or ``'argument'``.137 """138139 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_type149127 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 = None157158 param_hint = _join_param_hints(param_hint)
25 unmodified lines
184 missing = _("Missing {param_type}").format(param_type=param_type)185186 return f"{missing}{param_hint}.{msg}"187165 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.message
5 unmodified lines
199200 .. versionadded:: 4.0201 """202180 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)212213 super().__init__(message, ctx)214 self.option_name = option_name215 self.possibilities = possibilities216188 def format_message(self):217 def format_message(self) -> str:218 if not self.possibilities:219 return self.message220221 possibility_str = ", ".join(sorted(self.possibilities))
14 unmodified lines
236237 :param option_name: the name of the option being used incorrectly.238 """239211 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_name245246
8 unmodified lines
255256class FileError(ClickException):257 """Raised if a file cannot be opened."""258228 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")262263 super().__init__(hint)264 self.ui_filename = os.fsdecode(filename)265 self.filename = filename266236 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 lines
282 """283284 __slots__ = ("exit_code",)285255 def __init__(self, code=0):286 def __init__(self, code: int = 0) -> None:287 self.exit_code = code
modified:src/click/formatting.py+46 added-26 removed
7 unmodified lines
8# Can force a width. This is used by the test system9FORCED_WIDTH: t.Optional[int] = None101112def measure_table(rows):13 widths = {}12def measure_table(rows: t.Iterable[t.Tuple[str, str]]) -> t.Tuple[int, ...]:13 widths: t.Dict[int, int] = {}1415 for row in rows:16 for idx, col in enumerate(row):17 widths[idx] = max(widths.get(idx, 0), term_len(col))1819 return tuple(y for x, y in sorted(widths.items()))202120def iter_rows(rows, col_count):22def 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))272829def 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 lines
62 )63 if not preserve_paragraphs:64 return wrapper.fill(text)6559 p = []60 buf = []66 p: t.List[t.Tuple[int, bool, str]] = []67 buf: t.List[str] = []68 indent = None6963 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 lines
110 :param width: the width for the text. This defaults to the terminal111 width clamped to a maximum of 78.112 """113107 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 shutil121122 self.indent_increment = indent_increment123 if max_width is None:
3 unmodified lines
127 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] = []132121 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)136125 def indent(self):137 def indent(self) -> None:138 """Increases the indentation."""139 self.current_indent += self.indent_increment140129 def dedent(self):141 def dedent(self) -> None:142 """Decreases the indentation."""143 self.current_indent -= self.indent_increment144133 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.149150 :param prog: the program name.151 :param args: whitespace separated list of arguments.
29 unmodified lines
181 )182183 self.write("\n")184171 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")188175 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")193180 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 lines
207 )208 )209 self.write("\n")210197 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.219220 :param rows: a list of two item tuples for the terms and values.
31 unmodified lines
252 else:253 self.write("\n")254255 @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.259260 :param name: the section name that is written as heading.
6 unmodified lines
267 finally:268 self.dedent()269270 @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()278260 def getvalue(self):279 def getvalue(self) -> str:280 """Returns the buffer contents."""281 return "".join(self.buffer)282283265def join_options(options):284def 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 = False292293 for opt in options:294 prefix = split_opt(opt)[0]295296 if prefix == "/":297 any_prefix_is_slash = True298299 rv.append((len(prefix), opt))300301 rv.sort(key=lambda x: x[0])280281 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_slash
modified:src/click/globals.py+27 added-5 removed
1import typing2import typing as t3from threading import local45if t.TYPE_CHECKING:6 import typing_extensions as te7 from .core import Context89_local = local()10116def get_current_context(silent=False):12@typing.overload13def get_current_context(silent: "te.Literal[False]" = False) -> "Context":14 ...151617@typing.overload18def get_current_context(silent: bool = ...) -> t.Optional["Context"]:19 ...202122def 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 be
7 unmodified lines
34 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.")4243 return None444528def push_context(ctx):46def push_context(ctx: "Context") -> None:47 """Pushes a new context to the current stack."""48 _local.__dict__.setdefault("stack", []).append(ctx)495033def pop_context():51def pop_context() -> None:52 """Removes the top level from the stack."""53 _local.stack.pop()545538def resolve_color_default(color=None):56def 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 color6364 ctx = get_current_context(silent=True)6566 if ctx is not None:67 return ctx.color6869 return None
modified:src/click/parser.py+90 added-42 removed
19 unmodified lines
20# This code uses parts of optparse written by Gregory P. Ward and21# maintained by the Python Software Foundation.22# Copyright 2001-2006 Gregory P. Ward23# Copyright 2002-2006 Python Software Foundation24import typing as t25from collections import deque26from gettext import gettext as _27from gettext import ngettext28
1 unmodified line
30from .exceptions import BadOptionUsage31from .exceptions import NoSuchOption32from .exceptions import UsageError3334if 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 CoreParameter3940V = t.TypeVar("V")4142# 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()464739def _unpack_args(args, nargs_spec):48def _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 lines
58 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] = None6454 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 lines
72 return None7374 while nargs_spec:75 nargs = _fetch(nargs_spec)7677 if nargs is None:78 continue7980 if nargs == 1:81 rv.append(_fetch(args))82 elif nargs > 1:83 x = [_fetch(args) for _ in range(nargs)]8485 # 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()8990 rv.append(tuple(x))91 elif nargs < 0:92 if spos is not None:93 raise TypeError("Cannot have two nargs < 0")9495 spos = len(rv)96 rv.append(None)9798 # spos is the position of the wildcard (star). If it's not `None`,
5 unmodified lines
104105 return tuple(rv), list(args)10610790def split_opt(opt):108def 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:]11511699def normalize_opt(opt, ctx):117def 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)}"122123106def split_arg_string(string):124def 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 lines
155 return out156157158class 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 lines
189 self.const = const190 self.obj = obj191192 @property167 def takes_value(self):193 def takes_value(self) -> bool:194 return self.action in ("store", "append")195170 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)210211212class 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 = obj217192 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 lines
234235 if self.nargs == -1 and self.obj.envvar is not None:236 value = None237207 state.opts[self.dest] = value238 state.opts[self.dest] = value # type: ignore239 state.order.append(self.obj)240241242class 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"] = []248249250class OptionParser:251 """The option parser is an internal class that is ultimately used to
8 unmodified lines
260 :param ctx: optionally the :class:`~click.Context` where this parser261 should go with.262 """263233 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 lines
274 #: 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 = False278279 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 = {}282283 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] = []287255 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``.301302 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] = option312274 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.317318 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))322284 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 they
7 unmodified lines
337 if self.ctx is None or not self.ctx.resilient_parsing:338 raise339 return state.opts, state.largs, state.order340300 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 lines
348349 state.largs = args350 state.rargs = []351311 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 what
27 unmodified lines
384 # 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!387347 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_matches393394 possibilities = get_close_matches(opt, self._long_opt)
19 unmodified lines
414 value = None415416 option.process(value, state)417375 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 lines
454 # 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)}")457415 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.nargs462463 if len(state.rargs) < nargs:464 if option.obj._flag_needs_value:
27 unmodified lines
492 del state.rargs[:nargs]493494 return value495451 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 lines
516 # (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 return522523 if not self.ignore_unknown_options:524 raise525526 state.largs.append(arg)
added:src/click/py.typed
modified:src/click/shell_completion.py+65 added-36 removed
2 unmodified lines
3import typing as t4from gettext import gettext as _56from .core import Argument7from .core import BaseCommand8from .core import Context9from .core import MultiCommand10from .core import Option11from .core import Parameter12from .core import ParameterSource13from .parser import split_arg_string14from .utils import echo151614def shell_complete(cli, ctx_args, prog_name, complete_var, instruction):17def 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.2526 :param cli: Command being called.27 :param ctx_args: Extra arguments to pass to
44 unmodified lines
72 """7374 __slots__ = ("value", "type", "help", "_info")7567 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 = kwargs8773 def __getattr__(self, name):88 def __getattr__(self, name: str) -> t.Any:89 return self._info.get(name)909192# Only Bash >= 4.4 has the nosort option.
106 unmodified lines
199200 .. versionadded:: 8.0201 """202188 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 """208193 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 """213198 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_var225226 @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"233212 def source_vars(self):234 def source_vars(self) -> t.Dict[str, t.Any]:235 """Vars for formatting :attr:`source_template`.236237 By default this provides ``complete_func``, ``complete_var``,238 and ``prog_name``.
3 unmodified lines
242 "complete_var": self.complete_var,243 "prog_name": self.prog_name,244 }245224 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()253232 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 NotImplementedError260239 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.267268 :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)248249 if ctx is None:250 return []251272 obj, incomplete = _resolve_incomplete(ctx, args, incomplete)273 return obj.shell_complete(ctx, incomplete)274255 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.278279 :param item: Completion item to format.280 """281 raise NotImplementedError282263 def complete(self):283 def complete(self) -> str:284 """Produce the completion data to send back to the shell.285286 By default this calls :meth:`get_completion_args`, gets the287 completions, then calls :meth:`format_completion` for each
10 unmodified lines
298299 name = "bash"300 source_template = _SOURCE_BASH301282 def _check_version(self):302 def _check_version(self) -> None:303 import subprocess304305 output = subprocess.run(["bash", "--version"], stdout=subprocess.PIPE)306 match = re.search(r"version (\d)\.(\d)\.\d", output.stdout.decode())
12 unmodified lines
319 raise RuntimeError(320 _("Couldn't detect Bash version, shell completion is not supported.")321 )322303 def source(self):323 def source(self) -> str:324 self._check_version()325 return super().source()326307 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 lines
345346 name = "zsh"347 source_template = _SOURCE_ZSH348329 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 lines
367368 name = "fish"369 source_template = _SOURCE_FISH370351 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 lines
386387 return f"{item.type},{item.value}"388389370_available_shells = {390_available_shells: t.Dict[str, t.Type[ShellComplete]] = {391 "bash": BashComplete,392 "fish": FishComplete,393 "zsh": ZshComplete,394}395396377def add_completion_class(cls, name=None):397def 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 lines
411412 _available_shells[name] = cls413414393def get_completion_class(shell):415def 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 line
421 """422 return _available_shells.get(shell)423424403def _is_incomplete_argument(ctx, param):425def _is_incomplete_argument(ctx: Context, param: Parameter) -> bool:426 """Determine if the given parameter is an argument that can still427 accept values.428429 :param ctx: Invocation context for the command represented by the
2 unmodified lines
432 """433 if not isinstance(param, Argument):434 return False435436 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.COMMANDLINE
4 unmodified lines
445 )446 )447448426def _start_of_option(value):449def _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 False452453431def _is_incomplete_option(args, param):454def _is_incomplete_option(args: t.List[str], param: Parameter) -> bool:455 """Determine if the given parameter is an option that needs a value.456457 :param args: List of complete args before the incomplete value.458 :param param: Option object being checked.
15 unmodified lines
474475 return last_option is not None and last_option in param.opts476477455def _resolve_context(cli, ctx_args, prog_name, args):478def _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 lines
490 ctx = cli.make_context(prog_name, args.copy(), **ctx_args)491 args = ctx.protected_args + ctx.args492493 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.command495496 if isinstance(command, MultiCommand):497 if not command.chain:498 name, cmd, args = command.resolve_command(ctx, args)499500 if cmd is None:501 return ctx502503 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)508509 if cmd is None:510 return ctx511
7 unmodified lines
519 )520 args = sub_ctx.args521522 ctx = sub_ctx496 args = sub_ctx.protected_args + sub_ctx.args523 args = [*sub_ctx.protected_args, *sub_ctx.args]524 else:525 break526527 return ctx528529503def _resolve_incomplete(ctx, args, incomplete):530def _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.535536 :param ctx: Invocation context for the command represented by
38 unmodified lines
modified:src/click/termui.py+117 added-78 removed
1 unmodified line
2import io3import itertools4import os5import sys6import typing7import typing as t8from gettext import gettext as _99from ._compat import is_bytes10from ._compat import isatty11from ._compat import strip_ansi12from ._compat import WIN13from .exceptions import Abort14from .exceptions import UsageError15from .globals import resolve_color_default16from .types import Choice17from .types import convert_type18from .types import ParamType19from .utils import echo20from .utils import LazyFile2122if t.TYPE_CHECKING:23 from ._termui_impl import ProgressBar2425V = t.TypeVar("V")2627# The prompt functions to use. The doc tools currently override these28# functions to customize how they work.23visible_prompt_func = input29visible_prompt_func: t.Callable[[str], str] = input3031_ansi_colors = {32 "black": 30,33 "red": 31,
15 unmodified lines
49}50_ansi_reset_all = "\033[0m"515247def hidden_prompt_func(prompt):53def hidden_prompt_func(prompt: str) -> str:54 import getpass5556 return getpass.getpass(prompt)575859def _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}"737464def _format_default(default):75def _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: ignore7879 return default808182def 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.9697 If the user aborts the input by sending a interrupt signal, this
32 unmodified lines
130 .. versionadded:: 4.0131 Added the `err` parameter.132133 """123 result = None134125 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 Windows
19 unmodified lines
159 if confirmation_prompt:160 if confirmation_prompt is True:161 confirmation_prompt = _("Repeat for confirmation")162163 confirmation_prompt = t.cast(str, confirmation_prompt)164 confirmation_prompt = _build_prompt(confirmation_prompt, prompt_suffix)165155 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 lines
180 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 line
191 echo(_("Error: The two entered values do not match."), err=err)192193194def 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).203204 If the user aborts the input by sending a interrupt signal this205 function will catch it and raise a :exc:`Abort` exception.
20 unmodified lines
226 show_default,227 "y/n" if default is None else ("Y/n" if default else "y/N"),228 )229213 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 lines
249 raise Abort()250 return rv251252236def get_terminal_size():253def 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.256257 .. deprecated:: 8.0
11 unmodified lines
269 )270 return shutil.get_terminal_size()271272256def echo_via_pager(text_or_generator, color=None):273def 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.279280 .. versionchanged:: 3.0
6 unmodified lines
287 """288 color = resolve_color_default(color)289290 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))296297 # 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 lines
302 return pager(itertools.chain(text_generator, "\n"), color)303304305def 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 rendered
127 unmodified lines
453 update_min_steps=update_min_steps,454 )455456437def clear():457def 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 lines
468 else:469 sys.stdout.write("\033[2J\033[1;1H")470471452def _interpret_color(color, offset=0):472def _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}"477478 if isinstance(color, (tuple, list)):
3 unmodified lines
482 return str(_ansi_colors[color] + offset)483484485def 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 lines
610 bits.append(_ansi_reset_all)611 return "".join(bits)612613592def unstyle(text):614def 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 lines
622 """623 return strip_ansi(text)624625604def secho(message=None, file=None, nl=True, err=False, color=None, **styles):626def 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::636637 click.secho('Hello World!', fg='green')
12 unmodified lines
650 passed through without style applied.651652 .. 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)656657 return echo(message, file=file, nl=nl, err=err, color=color)658659660def 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 be
21 unmodified lines
693 file as an indirection in that case.694 """695 from ._termui_impl import Editor696663 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)698699 if filename is None:667 return editor.edit(text)668 editor.edit_file(filename)700 return ed.edit(text)701702 ed.edit_file(filename)703 return None704671def launch(url, wait=False, locate=False):705706def 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`` indicates
25 unmodified lines
736# for unittesting purposes.737_getchar: t.Optional[t.Callable[[bool], str]] = None738739705def getchar(echo=False):740def 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 for
11 unmodified lines
756757 :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 _getchar761762 if _getchar is None:763 from ._termui_impl import getchar as f728 return f(echo)764765 _getchar = f766731def raw_terminal():767 return _getchar(echo)768769770def raw_terminal() -> t.ContextManager[int]:771 from ._termui_impl import raw_terminal as f772773 return f()774775737def pause(info=None, err=False):776def 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 lines
modified:src/click/testing.py+102 added-69 removed
3 unmodified lines
4import shlex5import shutil6import sys7import tempfile8import typing as t9from types import TracebackType1011from . import formatting12from . import termui13from . import utils14from ._compat import _find_binary_reader1516if t.TYPE_CHECKING:17 from .core import BaseCommand181920class 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 = False2521 def __getattr__(self, x):26 def __getattr__(self, x: str) -> t.Any:27 return getattr(self._input, x)2824 def _echo(self, rv):29 def _echo(self, rv: bytes) -> bytes:30 if not self._paused:31 self._output.write(rv)3233 return rv3430 def read(self, n=-1):35 def read(self, n: int = -1) -> bytes:36 return self._echo(self._input.read(n))3733 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: ignore4036 def readline(self, n=-1):41 def readline(self, n: int = -1) -> bytes:42 return self._echo(self._input.readline(n))4339 def readlines(self):44 def readlines(self) -> t.List[bytes]:45 return [self._echo(x) for x in self._input.readlines()]4642 def __iter__(self):47 def __iter__(self) -> t.Iterator[bytes]:48 return iter(self._echo(x) for x in self._input)4945 def __repr__(self):50 def __repr__(self) -> str:51 return repr(self._input)525354@contextlib.contextmanager50def _pause_echo(stream):55def _pause_echo(stream: t.Optional[EchoingStdin]) -> t.Iterator[None]:56 if stream is None:57 yield58 else:59 stream._paused = True
1 unmodified line
61 stream._paused = False626364class _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 = mode7172 @property66 def name(self):73 def name(self) -> str:74 return self._name7576 @property70 def mode(self):77 def mode(self) -> str:78 return self._mode798074def make_input_stream(input, charset):81def 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))8788 if rv is not None:89 return rv9091 raise TypeError("Could not find binary reader for input stream.")9293 if input is None:94 input = b""86 elif not isinstance(input, bytes):95 elif isinstance(input, str):96 input = input.encode(charset)9789 return io.BytesIO(input)98 return io.BytesIO(t.cast(bytes, input))99100101class Result:102 """Holds the captured result of an invoked CLI script."""103104 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 lines
130 #: The traceback131 self.exc_info = exc_info132133 @property123 def output(self):134 def output(self) -> str:135 """The (standard) output as unicode string."""136 return self.stdout137138 @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 )144145 @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 )153143 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}>"157158
15 unmodified lines
174 noisy stderr, such that each may be measured175 independently176 """177167 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_stderr189173 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"196180 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 rv205206 @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 the
12 unmodified lines
229230 .. 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 = None235236 old_stdin = sys.stdin237 old_stdout = sys.stdout
5 unmodified lines
243244 bytes_output = io.BytesIO()245246 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 )250225 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 )254255 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: ignore259260 sys.stdout = _NamedTextIOWrapper(261 bytes_output, encoding=self.charset, name="<stdout>", mode="w"262 )
10 unmodified lines
273 mode="w",274 errors="backslashreplace",275 )276251 @_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 val284259 @_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")290265 @_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)294295 if echo:296 sys.stdout.write(char)
2 unmodified lines
299 return char300301 default_color = color302277 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 color309310 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: ignore318319 old_env = {}320 try:321 for key, value in env.items():
20 unmodified lines
342 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_width348349 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 lines
392 """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 = 0398399 if isinstance(args, str):400 args = shlex.split(args)
6 unmodified lines
407 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)412413 if e_code is None:414 e_code = 0415387 if exit_code != 0:416 if e_code != 0:417 exception = e418390 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 = 1423424 exit_code = e_code425426 except Exception as e:427 if not catch_exceptions:428 raise429 exception = e
4 unmodified lines
434 stdout = outstreams[0].getvalue()435 if self.mix_stderr:436 stderr = None437 else:407 stderr = outstreams[1].getvalue()438 stderr = outstreams[1].getvalue() # type: ignore439440 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 )449450 @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 lines
modified:src/click/types.py+159 added-81 removed
5 unmodified lines
6from gettext import ngettext78from ._compat import _get_argv_encoding9from ._compat import get_filesystem_encoding10from ._compat import get_strerror10from ._compat import open_stream11from .exceptions import BadParameter12from .utils import LazyFile13from .utils import safecall1415if t.TYPE_CHECKING:16 import typing_extensions as te17 from .core import Context18 from .core import Parameter19 from .shell_completion import CompletionItem202122class ParamType:23 """Represents the type of a parameter. Validates and converts values24 from the command line or Python into the correct type.25
10 unmodified lines
36 arguments are ``None``. This can occur when converting prompt37 input.38 """3935 is_composite = False40 is_composite: t.ClassVar[bool] = False41 arity: t.ClassVar[int] = 14243 #: the descriptive name of this type38 name: t.Optional[str] = None44 name: str4546 #: if a list of this type is expected and the value is pulled from a47 #: string environment variable, this is what splits it up. `None`48 #: means any whitespace. For all parameters the general rule is that
1 unmodified line
50 #: are split by ``os.path.pathsep`` by default (":" on Unix and ";" on51 #: Windows).52 envvar_list_splitter: t.ClassVar[t.Optional[str]] = None5348 def to_info_dict(self):54 def to_info_dict(self) -> t.Dict[str, t.Any]:55 """Gather information that could be useful for a tool generating56 user-facing documentation.5758 Use :meth:`click.Context.to_info_dict` to traverse the entire
5 unmodified lines
64 param_type = type(self).__name__.partition("ParamType")[0]65 param_type = param_type.partition("ParameterType")[0]66 return {"param_type": param_type, "name": self.name}6762 def __call__(self, value, param=None, ctx=None):68 def __call__(69 self,70 value: t.Any,71 param: t.Optional["Parameter"] = None,72 ctx: t.Optional["Context"] = None,73 ) -> t.Any:74 if value is not None:75 return self.convert(value, param, ctx)7666 def get_metavar(self, param):77 def get_metavar(self, param: "Parameter") -> t.Optional[str]:78 """Returns the metavar default for this param if it provides one."""7969 def get_missing_message(self, param):80 def get_missing_message(self, param: "Parameter") -> t.Optional[str]:81 """Optionally might return extra information about a missing82 parameter.8384 .. versionadded:: 2.085 """8676 def convert(self, value, param, ctx):87 def convert(88 self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]89 ) -> t.Any:90 """Convert the value to the correct type. This is not called if91 the value is ``None`` (the missing value).9293 This must accept string values from the command line, as well as
13 unmodified lines
107 be ``None``.108 """109 return value11098 def split_envvar_value(self, rv):111 def split_envvar_value(self, rv: str) -> t.Sequence[str]:112 """Given a value from an environment variable this splits it up113 into small chunks depending on the defined envvar list splitter.114115 If the splitter is set to `None`, which means that whitespace splits,
1 unmodified line
117 and trailing splitters usually lead to empty items being included.118 """119 return (rv or "").split(self.envvar_list_splitter)120108 def fail(self, message, param=None, ctx=None):121 def fail(122 self,123 message: str,124 param: t.Optional["Parameter"] = None,125 ctx: t.Optional["Context"] = None,126 ) -> t.NoReturn:127 """Helper method to fail with an invalid value message."""128 raise BadParameter(message, ctx=ctx, param=param)129112 def shell_complete(self, ctx, param, incomplete):130 def shell_complete(131 self, ctx: "Context", param: "Parameter", incomplete: str132 ) -> t.List["CompletionItem"]:133 """Return a list of134 :class:`~click.shell_completion.CompletionItem` objects for the135 incomplete value. Most types do not provide completions, but136 some do, and this allows custom types to provide custom
11 unmodified lines
148class CompositeParamType(ParamType):149 is_composite = True150151 @property132 def arity(self):152 def arity(self) -> int: # type: ignore153 raise NotImplementedError()154155156class FuncParamType(ParamType):137 def __init__(self, func):157 def __init__(self, func: t.Callable[[t.Any], t.Any]) -> None:158 self.name = func.__name__159 self.func = func160141 def to_info_dict(self):161 def to_info_dict(self) -> t.Dict[str, t.Any]:162 info_dict = super().to_info_dict()163 info_dict["func"] = self.func164 return info_dict165146 def convert(self, value, param, ctx):166 def convert(167 self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]168 ) -> t.Any:169 try:170 return self.func(value)171 except ValueError:172 try:
6 unmodified lines
179180class UnprocessedParamType(ParamType):181 name = "text"182161 def convert(self, value, param, ctx):183 def convert(184 self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]185 ) -> t.Any:186 return value187164 def __repr__(self):188 def __repr__(self) -> str:189 return "UNPROCESSED"190191192class StringParamType(ParamType):193 name = "text"194171 def convert(self, value, param, ctx):195 def convert(196 self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]197 ) -> t.Any:198 if isinstance(value, bytes):199 enc = _get_argv_encoding()200 try:201 value = value.decode(enc)
8 unmodified lines
210 value = value.decode("utf-8", "replace")211 return value212 return str(value)213188 def __repr__(self):214 def __repr__(self) -> str:215 return "STRING"216217218class Choice(ParamType):
14 unmodified lines
233 """234235 name = "choice"236211 def __init__(self, choices, case_sensitive=True):237 def __init__(self, choices: t.Sequence[str], case_sensitive: bool = True) -> None:238 self.choices = choices239 self.case_sensitive = case_sensitive240215 def to_info_dict(self):241 def to_info_dict(self) -> t.Dict[str, t.Any]:242 info_dict = super().to_info_dict()243 info_dict["choices"] = self.choices244 info_dict["case_sensitive"] = self.case_sensitive245 return info_dict246221 def get_metavar(self, param):247 def get_metavar(self, param: "Parameter") -> str:248 choices_str = "|".join(self.choices)249250 # Use curly braces to indicate a required argument.251 if param.required and param.param_type_name == "argument":
1 unmodified line
253254 # Use square braces to indicate an option or optional argument.255 return f"[{choices_str}]"256231 def get_missing_message(self, param):257 def get_missing_message(self, param: "Parameter") -> str:258 return _("Choose from:\n\t{choices}").format(choices=",\n\t".join(self.choices))259234 def convert(self, value, param, ctx):260 def convert(261 self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]262 ) -> t.Any:263 # Match through normalization and case sensitivity264 # first do token_normalize_func, then lowercase265 # preserve original `value` to produce an accurate message in266 # `self.fail`
27 unmodified lines
294 param,295 ctx,296 )297270 def __repr__(self):298 def __repr__(self) -> str:299 return f"Choice({list(self.choices)})"300273 def shell_complete(self, ctx, param, incomplete):301 def shell_complete(302 self, ctx: "Context", param: "Parameter", incomplete: str303 ) -> t.List["CompletionItem"]:304 """Complete choices that start with the incomplete value.305306 :param ctx: Invocation context for this command.307 :param param: The parameter that is requesting completion.
36 unmodified lines
344 """345346 name = "datetime"347318 def __init__(self, formats=None):348 def __init__(self, formats: t.Optional[t.Sequence[str]] = None):349 self.formats = formats or ["%Y-%m-%d", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%d %H:%M:%S"]350321 def to_info_dict(self):351 def to_info_dict(self) -> t.Dict[str, t.Any]:352 info_dict = super().to_info_dict()353 info_dict["formats"] = self.formats354 return info_dict355326 def get_metavar(self, param):356 def get_metavar(self, param: "Parameter") -> str:357 return f"[{'|'.join(self.formats)}]"358329 def _try_to_convert_date(self, value, format):359 def _try_to_convert_date(self, value: t.Any, format: str) -> t.Optional[datetime]:360 try:361 return datetime.strptime(value, format)362 except ValueError:363 return None364335 def convert(self, value, param, ctx):365 def convert(366 self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]367 ) -> t.Any:368 if isinstance(value, datetime):369 return value370371 for format in self.formats:
12 unmodified lines
384 param,385 ctx,386 )387356 def __repr__(self):388 def __repr__(self) -> str:389 return "DateTime"390391392class _NumberParamTypeBase(ParamType):361 _number_class: t.ClassVar[t.Optional[t.Type]] = None393 _number_class: t.ClassVar[t.Type]394363 def convert(self, value, param, ctx):395 def convert(396 self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]397 ) -> t.Any:398 try:399 return self._number_class(value)400 except ValueError:401 self.fail(
5 unmodified lines
407 )408409410class _NumberRangeBase(_NumberParamTypeBase):377 def __init__(self, min=None, max=None, min_open=False, max_open=False, clamp=False):411 def __init__(412 self,413 min: t.Optional[float] = None,414 max: t.Optional[float] = None,415 min_open: bool = False,416 max_open: bool = False,417 clamp: bool = False,418 ) -> None:419 self.min = min420 self.max = max421 self.min_open = min_open422 self.max_open = max_open423 self.clamp = clamp424384 def to_info_dict(self):425 def to_info_dict(self) -> t.Dict[str, t.Any]:426 info_dict = super().to_info_dict()427 info_dict.update(428 min=self.min,429 max=self.max,
2 unmodified lines
432 clamp=self.clamp,433 )434 return info_dict435395 def convert(self, value, param, ctx):436 def convert(437 self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]438 ) -> t.Any:439 import operator440441 rv = super().convert(value, param, ctx)399 lt_min = self.min is not None and (442 lt_min: bool = self.min is not None and (443 operator.le if self.min_open else operator.lt444 )(rv, self.min)402 gt_max = self.max is not None and (445 gt_max: bool = self.max is not None and (446 operator.ge if self.max_open else operator.gt447 )(rv, self.max)448449 if self.clamp:450 if lt_min:408 return self._clamp(self.min, 1, self.min_open)451 return self._clamp(self.min, 1, self.min_open) # type: ignore452453 if gt_max:411 return self._clamp(self.max, -1, self.max_open)454 return self._clamp(self.max, -1, self.max_open) # type: ignore455456 if lt_min or gt_max:457 self.fail(458 _("{value} is not in the range {range}.").format(
4 unmodified lines
463 )464465 return rv466424 def _clamp(self, bound, dir, open):467 def _clamp(self, bound: float, dir: "te.Literal[1, -1]", open: bool) -> float:468 """Find the valid value to clamp to bound in the given469 direction.470471 :param bound: The boundary value.
1 unmodified line
473 :param open: If true, the range does not include the bound.474 """475 raise NotImplementedError476434 def _describe_range(self):477 def _describe_range(self) -> str:478 """Describe the range for use in help text."""479 if self.min is None:480 op = "<" if self.max_open else "<="481 return f"x{op}{self.max}"
5 unmodified lines
487 lop = "<" if self.min_open else "<="488 rop = "<" if self.max_open else "<="489 return f"{self.min}{lop}x{rop}{self.max}"490448 def __repr__(self):491 def __repr__(self) -> str:492 clamp = " clamped" if self.clamp else ""493 return f"<{type(self).__name__} {self._describe_range()}{clamp}>"494495496class IntParamType(_NumberParamTypeBase):497 name = "integer"498 _number_class = int499457 def __repr__(self):500 def __repr__(self) -> str:501 return "INT"502503504class IntRange(_NumberRangeBase, IntParamType):
12 unmodified lines
517 """518519 name = "integer range"520478 def _clamp(self, bound, dir, open):521 def _clamp( # type: ignore522 self, bound: int, dir: "te.Literal[1, -1]", open: bool523 ) -> int:524 if not open:525 return bound526527 return bound + dir
2 unmodified lines
530class FloatParamType(_NumberParamTypeBase):531 name = "float"532 _number_class = float533489 def __repr__(self):534 def __repr__(self) -> str:535 return "FLOAT"536537538class FloatRange(_NumberRangeBase, FloatParamType):
13 unmodified lines
552 """553554 name = "float range"555511 def __init__(self, min=None, max=None, min_open=False, max_open=False, clamp=False):556 def __init__(557 self,558 min: t.Optional[float] = None,559 max: t.Optional[float] = None,560 min_open: bool = False,561 max_open: bool = False,562 clamp: bool = False,563 ) -> None:564 super().__init__(565 min=min, max=max, min_open=min_open, max_open=max_open, clamp=clamp566 )567568 if (min_open or max_open) and clamp:569 raise TypeError("Clamping is not supported for open bounds.")570519 def _clamp(self, bound, dir, open):571 def _clamp(self, bound: float, dir: "te.Literal[1, -1]", open: bool) -> float:572 if not open:573 return bound574575 # Could use Python 3.9's math.nextafter here, but clamping an
4 unmodified lines
580581class BoolParamType(ParamType):582 name = "boolean"583532 def convert(self, value, param, ctx):584 def convert(585 self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]586 ) -> t.Any:587 if value in {False, True}:588 return bool(value)589590 norm = value.strip().lower()
7 unmodified lines
598 self.fail(599 _("{value!r} is not a valid boolean.").format(value=value), param, ctx600 )601548 def __repr__(self):602 def __repr__(self) -> str:603 return "BOOL"604605606class UUIDParameterType(ParamType):607 name = "uuid"608555 def convert(self, value, param, ctx):609 def convert(610 self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]611 ) -> t.Any:612 import uuid613614 if isinstance(value, uuid.UUID):615 return value
6 unmodified lines
622 self.fail(623 _("{value!r} is not a valid UUID.").format(value=value), param, ctx624 )625570 def __repr__(self):626 def __repr__(self) -> str:627 return "UUID"628629630class File(ParamType):
26 unmodified lines
657 name = "filename"658 envvar_list_splitter = os.path.pathsep659660 def __init__(605 self, mode="r", encoding=None, errors="strict", lazy=None, atomic=False606 ):661 self,662 mode: str = "r",663 encoding: t.Optional[str] = None,664 errors: t.Optional[str] = "strict",665 lazy: t.Optional[bool] = None,666 atomic: bool = False,667 ) -> None:668 self.mode = mode669 self.encoding = encoding670 self.errors = errors671 self.lazy = lazy672 self.atomic = atomic673613 def to_info_dict(self):674 def to_info_dict(self) -> t.Dict[str, t.Any]:675 info_dict = super().to_info_dict()676 info_dict.update(mode=self.mode, encoding=self.encoding)677 return info_dict678618 def resolve_lazy_flag(self, value):679 def resolve_lazy_flag(self, value: t.Any) -> bool:680 if self.lazy is not None:681 return self.lazy682 if value == "-":683 return False684 elif "w" in self.mode:685 return True686 return False687627 def convert(self, value, param, ctx):688 def convert(689 self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]690 ) -> t.Any:691 try:692 if hasattr(value, "read") or hasattr(value, "write"):693 return value694695 lazy = self.resolve_lazy_flag(value)696697 if lazy:698 f: t.IO = t.cast(699 t.IO,635 f = LazyFile(636 value, self.mode, self.encoding, self.errors, atomic=self.atomic700 LazyFile(701 value, self.mode, self.encoding, self.errors, atomic=self.atomic702 ),703 )704705 if ctx is not None:639 ctx.call_on_close(f.close_intelligently)706 ctx.call_on_close(f.close_intelligently) # type: ignore707708 return f709710 f, should_close = open_stream(711 value, self.mode, self.encoding, self.errors, atomic=self.atomic712 )713714 # If a context is provided, we automatically close the file715 # at the end of the context execution (or flush out). If a716 # context does not exist, it's the caller's responsibility to717 # properly close the file. This for instance happens when the
2 unmodified lines
720 if should_close:721 ctx.call_on_close(safecall(f.close))722 else:723 ctx.call_on_close(safecall(f.flush))724725 return f726 except OSError as e: # noqa: B014657 self.fail(f"{os.fsdecode(value)!r}: {get_strerror(e)}", param, ctx)727 self.fail(f"{os.fsdecode(value)!r}: {e.strerror}", param, ctx)728659 def shell_complete(self, ctx, param, incomplete):729 def shell_complete(730 self, ctx: "Context", param: "Parameter", incomplete: str731 ) -> t.List["CompletionItem"]:732 """Return a special completion marker that tells the completion733 system to use the shell to provide file path completions.734735 :param ctx: Invocation context for this command.
42 unmodified lines
778 envvar_list_splitter = os.path.pathsep779780 def __init__(781 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,782 exists: bool = False,783 file_okay: bool = True,784 dir_okay: bool = True,785 writable: bool = False,786 readable: bool = True,787 resolve_path: bool = False,788 allow_dash: bool = False,789 path_type: t.Optional[t.Type] = None,790 ):791 self.exists = exists792 self.file_okay = file_okay793 self.dir_okay = dir_okay
9 unmodified lines
803 self.name = _("directory")804 else:805 self.name = _("path")806735 def to_info_dict(self):807 def to_info_dict(self) -> t.Dict[str, t.Any]:808 info_dict = super().to_info_dict()809 info_dict.update(810 exists=self.exists,811 file_okay=self.file_okay,
3 unmodified lines
815 allow_dash=self.allow_dash,816 )817 return info_dict818747 def coerce_path_result(self, rv):819 def coerce_path_result(self, rv: t.Any) -> t.Any:820 if self.type is not None and not isinstance(rv, self.type):821 if self.type is str:822 rv = os.fsdecode(rv)823 elif self.type is bytes:
2 unmodified lines
826 rv = self.type(rv)827828 return rv829758 def convert(self, value, param, ctx):830 def convert(831 self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]832 ) -> t.Any:833 rv = value834835 is_dash = self.file_okay and self.allow_dash and rv in (b"-", "-")836
52 unmodified lines
889 )890891 return self.coerce_path_result(rv)892819 def shell_complete(self, ctx, param, incomplete):893 def shell_complete(894 self, ctx: "Context", param: "Parameter", incomplete: str895 ) -> t.List["CompletionItem"]:896 """Return a special completion marker that tells the completion897 system to use the shell to provide path completions for only898 directories or any paths.899
22 unmodified lines
922923 :param types: a list of types that should be used for the tuple items.924 """925850 def __init__(self, types):926 def __init__(self, types: t.Sequence[t.Union[t.Type, ParamType]]) -> None:927 self.types = [convert_type(ty) for ty in types]928853 def to_info_dict(self):929 def to_info_dict(self) -> t.Dict[str, t.Any]:930 info_dict = super().to_info_dict()931 info_dict["types"] = [t.to_info_dict() for t in self.types]932 return info_dict933934 @property859 def name(self):935 def name(self) -> str: # type: ignore936 return f"<{' '.join(ty.name for ty in self.types)}>"937938 @property863 def arity(self):939 def arity(self) -> int: # type: ignore940 return len(self.types)941866 def convert(self, value, param, ctx):942 def convert(943 self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]944 ) -> t.Any:945 len_type = len(self.types)946 len_value = len(value)947948 if len_value != len_type:
9 unmodified lines
958959 return tuple(ty(x, param, ctx) for ty, x in zip(self.types, value))960961884def convert_type(ty, default=None):962def convert_type(ty: t.Optional[t.Any], default: t.Optional[t.Any] = None) -> ParamType:963 """Find the most appropriate :class:`ParamType` for the given Python964 type. If the type isn't provided, it can be inferred from a default965 value.966 """
89 unmodified lines
modified:src/click/utils.py+90 added-60 removed
1import os2import sys3import typing as t4from functools import update_wrapper5from types import ModuleType67from ._compat import _default_text_stderr8from ._compat import _default_text_stdout9from ._compat import _find_binary_writer10from ._compat import auto_wrap_for_ansi11from ._compat import binary_streams12from ._compat import get_filesystem_encoding11from ._compat import get_strerror12from ._compat import is_bytes13from ._compat import open_stream14from ._compat import should_strip_ansi15from ._compat import strip_ansi16from ._compat import text_streams17from ._compat import WIN18from .globals import resolve_color_default1920if t.TYPE_CHECKING:21 import typing_extensions as te2221echo_native_types = (str, bytes, bytearray)23F = t.TypeVar("F", bound=t.Callable[..., t.Any])242524def _posixify(name):26def _posixify(name: str) -> str:27 return "-".join(name.split()).lower()282928def safecall(func):30def safecall(func: F) -> F:31 """Wraps a function so that it swallows exceptions."""3231 def wrapper(*args, **kwargs):33 def wrapper(*args, **kwargs): # type: ignore34 try:35 return func(*args, **kwargs)36 except Exception:37 pass3837 return wrapper39 return update_wrapper(t.cast(F, wrapper), func)404140def make_str(value):42def make_str(value: t.Any) -> str:43 """Converts a value into a valid string."""44 if isinstance(value, bytes):45 try:46 return value.decode(get_filesystem_encoding())
59 unmodified lines
106 files for writing.107 """108109 def __init__(108 self, filename, mode="r", encoding=None, errors="strict", atomic=False110 self,111 filename: str,112 mode: str = "r",113 encoding: t.Optional[str] = None,114 errors: t.Optional[str] = "strict",115 atomic: bool = False,116 ):117 self.name = filename118 self.mode = mode119 self.encoding = encoding120 self.errors = errors121 self.atomic = atomic122 self._f: t.Optional[t.IO]123124 if filename == "-":125 self._f, self.should_close = open_stream(filename, mode, encoding, errors)126 else:
4 unmodified lines
131 open(filename, mode).close()132 self._f = None133 self.should_close = True134127 def __getattr__(self, name):135 def __getattr__(self, name: str) -> t.Any:136 return getattr(self.open(), name)137130 def __repr__(self):138 def __repr__(self) -> str:139 if self._f is not None:140 return repr(self._f)141 return f"<unopened file '{self.name}' {self.mode}>"142135 def open(self):143 def open(self) -> t.IO:144 """Opens the file if it's not yet open. This call might fail with145 a :exc:`FileError`. Not handling this error will produce an error146 that Click shows.147 """
5 unmodified lines
153 )154 except OSError as e: # noqa: E402155 from .exceptions import FileError156149 raise FileError(self.name, hint=get_strerror(e))157 raise FileError(self.name, hint=e.strerror)158 self._f = rv159 return rv160153 def close(self):161 def close(self) -> None:162 """Closes the underlying file, no matter what."""163 if self._f is not None:164 self._f.close()165158 def close_intelligently(self):166 def close_intelligently(self) -> None:167 """This function only closes the file if it was opened by the lazy168 file wrapper. For instance this will never close stdin.169 """170 if self.should_close:171 self.close()172165 def __enter__(self):173 def __enter__(self) -> "LazyFile":174 return self175168 def __exit__(self, exc_type, exc_value, tb):176 def __exit__(self, exc_type, exc_value, tb): # type: ignore177 self.close_intelligently()178171 def __iter__(self):179 def __iter__(self) -> t.Iterator[t.AnyStr]:180 self.open()173 return iter(self._f)181 return iter(self._f) # type: ignore182183184class KeepOpenFile:177 def __init__(self, file):185 def __init__(self, file: t.IO) -> None:186 self._file = file187180 def __getattr__(self, name):188 def __getattr__(self, name: str) -> t.Any:189 return getattr(self._file, name)190183 def __enter__(self):191 def __enter__(self) -> "KeepOpenFile":192 return self193186 def __exit__(self, exc_type, exc_value, tb):194 def __exit__(self, exc_type, exc_value, tb): # type: ignore195 pass196189 def __repr__(self):197 def __repr__(self) -> str:198 return repr(self._file)199192 def __iter__(self):200 def __iter__(self) -> t.Iterator[t.AnyStr]:201 return iter(self._file)202203196def echo(message=None, file=None, nl=True, err=False, color=None):204def echo(205 message: t.Optional[t.Any] = None,206 file: t.Optional[t.IO] = None,207 nl: bool = True,208 err: bool = False,209 color: t.Optional[bool] = None,210) -> None:211 """Print a message and newline to stdout or a file. This should be212 used instead of :func:`print` because it provides better support213 for different data, files, and environments.214
37 unmodified lines
252 else:253 file = _default_text_stdout()254255 # Convert non bytes/text into the native string type.242 if message is not None and not isinstance(message, echo_native_types):243 message = str(message)256 if message is not None and not isinstance(message, (str, bytes, bytearray)):257 out: t.Optional[t.Union[str, bytes]] = str(message)258 else:259 out = message260261 if nl:246 message = message or ""247 if isinstance(message, str):248 message += "\n"262 out = out or ""263 if isinstance(out, str):264 out += "\n"265 else:250 message += b"\n"266 out += b"\n"267268 if not out:269 file.flush()270 return271272 # If there is a message and the value looks like bytes, we manually273 # need to find the binary stream and write the message in there.274 # This is done separately so that most stream types will work as you275 # would expect. Eg: you can write to StringIO for other cases.256 if message and is_bytes(message):276 if isinstance(out, (bytes, bytearray)):277 binary_file = _find_binary_writer(file)278279 if binary_file is not None:280 file.flush()260 binary_file.write(message)281 binary_file.write(out)282 binary_file.flush()283 return284285 # ANSI style code support. For no message or bytes, nothing happens.286 # When outputting to a file instead of a terminal, strip codes.266 if message and not is_bytes(message):287 else:288 color = resolve_color_default(color)289290 if should_strip_ansi(file, color):269 message = strip_ansi(message)291 out = strip_ansi(out)292 elif WIN:293 if auto_wrap_for_ansi is not None:272 file = auto_wrap_for_ansi(file)294 file = auto_wrap_for_ansi(file) # type: ignore295 elif not color:274 message = strip_ansi(message)296 out = strip_ansi(out)297276 if message:277 file.write(message)298 file.write(out) # type: ignore299 file.flush()300301281def get_binary_stream(name):302def get_binary_stream(name: "te.Literal['stdin', 'stdout', 'stderr']") -> t.BinaryIO:303 """Returns a system stream for byte processing.304305 :param name: the name of the stream to open. Valid names are ``'stdin'``,306 ``'stdout'`` and ``'stderr'``
3 unmodified lines
310 raise TypeError(f"Unknown standard stream '{name}'")311 return opener()312313293def get_text_stream(name, encoding=None, errors="strict"):314def get_text_stream(315 name: "te.Literal['stdin', 'stdout', 'stderr']",316 encoding: t.Optional[str] = None,317 errors: t.Optional[str] = "strict",318) -> t.TextIO:319 """Returns a system stream for text processing. This usually returns320 a wrapped stream around a binary stream returned from321 :func:`get_binary_stream` but it also can take shortcuts for already322 correctly configured streams.
9 unmodified lines
332 return opener(encoding, errors)333334335def open_file(311 filename, mode="r", encoding=None, errors="strict", lazy=False, atomic=False312):336 filename: str,337 mode: str = "r",338 encoding: t.Optional[str] = None,339 errors: t.Optional[str] = "strict",340 lazy: bool = False,341 atomic: bool = False,342) -> t.IO:343 """This is similar to how the :class:`File` works but for manual344 usage. Files are opened non lazy by default. This can open regular345 files as well as stdin/stdout if ``'-'`` is passed.346
15 unmodified lines
362 :param atomic: in atomic mode writes go into a temporary file and it's363 moved on close.364 """365 if lazy:336 return LazyFile(filename, mode, encoding, errors, atomic=atomic)366 return t.cast(t.IO, LazyFile(filename, mode, encoding, errors, atomic=atomic))367 f, should_close = open_stream(filename, mode, encoding, errors, atomic=atomic)368 if not should_close:339 f = KeepOpenFile(f)369 f = t.cast(t.IO, KeepOpenFile(f))370 return f371372343def get_os_args():373def get_os_args() -> t.Sequence[str]:374 """Returns the argument part of ``sys.argv``, removing the first375 value which is the name of the script.376377 .. deprecated:: 8.0
10 unmodified lines
388 )389 return sys.argv[1:]390391362def format_filename(filename, shorten=False):392def format_filename(393 filename: t.Union[str, bytes, os.PathLike], shorten: bool = False394) -> str:395 """Formats a filename for user display. The main purpose of this396 function is to ensure that the filename can be displayed at all. This397 will decode the filename to unicode if necessary in a way that it will398 not fail. Optionally, it can shorten the filename to not include the
9 unmodified lines
408409 return os.fsdecode(filename)410411380def get_app_dir(app_name, roaming=True, force_posix=False):412def get_app_dir(app_name: str, roaming: bool = True, force_posix: bool = False) -> str:413 r"""Returns the config folder for the application. The default behavior414 is to return whatever is most appropriate for the operating system.415416 To give you an idea, for an app called ``"Foo Bar"``, something like
6 unmodified lines
423 Unix:424 ``~/.config/foo-bar``425 Unix (POSIX):426 ``~/.foo-bar``395 Win XP (roaming):396 ``C:\Documents and Settings\<user>\Local Settings\Application Data\Foo Bar``397 Win XP (not roaming):398 ``C:\Documents and Settings\<user>\Application Data\Foo Bar``399 Win 7 (roaming):427 Windows (roaming):428 ``C:\Users\<user>\AppData\Roaming\Foo Bar``401 Win 7 (not roaming):429 Windows (not roaming):430 ``C:\Users\<user>\AppData\Local\Foo Bar``431432 .. versionadded:: 2.0433
32 unmodified lines
466 other cleanup code, and the case where the underlying file is not a broken467 pipe, all calls and attributes are proxied.468 """469442 def __init__(self, wrapped):470 def __init__(self, wrapped: t.IO) -> None:471 self.wrapped = wrapped472445 def flush(self):473 def flush(self) -> None:474 try:475 self.wrapped.flush()476 except OSError as e:477 import errno478479 if e.errno != errno.EPIPE:480 raise481454 def __getattr__(self, attr):482 def __getattr__(self, attr: str) -> t.Any:483 return getattr(self.wrapped, attr)484485458def _detect_program_name(path=None, _main=sys.modules["__main__"]):486def _detect_program_name(487 path: t.Optional[str] = None, _main: ModuleType = sys.modules["__main__"]488) -> str:489 """Determine the command used to run the program, for use in help490 text. If a file or entry point was executed, the file name is491 returned. If ``python -m`` was used to execute a module or package,492 ``python -m name`` is returned.
30 unmodified lines
523524 # Executed a module, like "python -m example".525 # Rewritten by Python from "-m script" to "/path/to/script.py".526 # Need to look at main module to determine how it was executed.497 py_module = _main.__package__527 py_module = t.cast(str, _main.__package__)528 name = os.path.splitext(os.path.basename(path))[0]529530 # A submodule like "example.cli".531 if name != "__main__":
48 unmodified lines
modified:tests/test_termui.py+15 added-19 removed
16 unmodified lines
17 def time(self):18 return self.now192021def _create_progress(length=10, length_known=True, **kwargs):21def _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 progress262728def test_progressbar_strip_regression(runner, monkeypatch):
5 unmodified lines
34 for _ in progress:35 pass3637 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 )424344def test_progressbar_length_hint(runner, monkeypatch):45 class Hinted:
66 unmodified lines
112113114@pytest.mark.parametrize("pos, length", [(0, 5), (-1, 1), (5, 5), (6, 5), (4, 0)])115def 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)119120121@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)128def 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() == expected133134135@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)145def 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 lines
modified:tests/test_testing.py+3 added-3 removed
12 unmodified lines
13 @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 lines
31 @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 lines
89 @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 lines
modified:MANIFEST.in+1 added
4 unmodified lines
5graft docs6prune docs/_build7graft examples8graft tests9include src/click/py.typed10global-exclude *.pyc
modified:setup.cfg+3 added-2 removed
77 unmodified lines
78[mypy]79files = src/click80python_version = 3.681disallow_subclassing_any = True82# disallow_untyped_calls = True83# disallow_untyped_defs = True82disallow_untyped_calls = True83disallow_untyped_defs = True84disallow_incomplete_defs = True85check_untyped_defs = True86no_implicit_optional = True87local_partial_types = True88no_implicit_reexport = True89strict_equality = True
14 unmodified lines