Skip to content
Myr

enable deferred evaluation of annotations

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

authored by Brian Grohe · committed by David Lord · parent 988c683 · Browse files · 18 files+176 added−140 removed
This commit

State

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

Diff stats

18 files+176 added−140 removed

  • tests:+1 added−0 removed
  • other:+175 added−140 removed

18 files+176 added−140 removed

modified:src/click/__init__.py+2 added
2 unmodified lines
3writing command line scripts fun. Unlike other modules, it's based4around a simple API that does not come with too much magic and is5composable.6"""7from __future__ import annotations89from .core import Argument as Argument10from .core import Command as Command11from .core import CommandCollection as CommandCollection12from .core import Context as Context
99 unmodified lines
modified:src/click/_compat.py+5 added-3 removed
1from __future__ import annotations23import codecs4import io5import os6import re
352 unmodified lines
359 return _force_correct_text_writer(sys.stderr, encoding, errors, force_writable=True)360361362def _wrap_io_open(361 file: t.Union[str, "os.PathLike[str]", int],363 file: t.Union[str, os.PathLike[str], int],364 mode: str,365 encoding: t.Optional[str],366 errors: t.Optional[str],367) -> t.IO[t.Any]:
4 unmodified lines
372 return open(file, mode, encoding=encoding, errors=errors)373374375def open_stream(374 filename: "t.Union[str, os.PathLike[str]]",376 filename: t.Union[str, os.PathLike[str]],377 mode: str = "r",378 encoding: t.Optional[str] = None,379 errors: t.Optional[str] = "strict",380 atomic: bool = False,
92 unmodified lines
473474 def __getattr__(self, name: str) -> t.Any:475 return getattr(self._f, name)476475 def __enter__(self) -> "_AtomicFile":477 def __enter__(self) -> _AtomicFile:478 return self479480 def __exit__(self, exc_type: t.Optional[t.Type[BaseException]], *_: t.Any) -> None:481 self.close(delete=exc_type is not None)
144 unmodified lines
modified:src/click/_termui_impl.py+3 added-1 removed
1 unmodified line
2This module contains implementations for the termui module. To keep the3import time of Click down, some infrequently used functionality is4placed in this module and only imported as needed.5"""6from __future__ import annotations78import contextlib9import math10import os11import sys
93 unmodified lines
105 self.current_item: t.Optional[V] = None106 self.is_hidden: bool = not isatty(self.file)107 self._last_line: t.Optional[str] = None108107 def __enter__(self) -> "ProgressBar[V]":109 def __enter__(self) -> ProgressBar[V]:110 self.entered = True111 self.render_progress()112 return self113
628 unmodified lines
modified:src/click/_textwrap.py+2 added
1from __future__ import annotations23import textwrap4import typing as t5from contextlib import contextmanager6
45 unmodified lines
modified:src/click/_winconsole.py+2 added
4 unmodified lines
5# There are some general differences in regards to how this works6# compared to the original patches as we do not need to patch7# the entire interpreter but just work in our little world of8# echo and prompt.9from __future__ import annotations1011import io12import sys13import time14import typing as t
267 unmodified lines
modified:src/click/core.py+49 added-47 removed
1from __future__ import annotations23import enum4import errno5import inspect6import os
40 unmodified lines
47V = t.TypeVar("V")484950def _complete_visible_commands(49 ctx: "Context", incomplete: str50) -> t.Iterator[t.Tuple[str, "Command"]]:51 ctx: Context, incomplete: str52) -> t.Iterator[t.Tuple[str, Command]]:53 """List all the subcommands of a group that start with the54 incomplete value and aren't hidden.5556 :param ctx: Invocation context for the group.
9 unmodified lines
66 yield name, command676869def _check_nested_chain(68 base_command: "Group", cmd_name: str, cmd: "Command", register: bool = False70 base_command: Group, cmd_name: str, cmd: Command, register: bool = False71) -> None:72 if not base_command.chain or not isinstance(cmd, Group):73 return74
16 unmodified lines
919293@contextmanager94def augment_usage_errors(93 ctx: "Context", param: t.Optional["Parameter"] = None95 ctx: Context, param: t.Optional[Parameter] = None96) -> t.Iterator[None]:97 """Context manager that attaches extra information to exceptions."""98 try:99 yield
9 unmodified lines
109 raise110111112def iter_params_for_processing(111 invocation_order: t.Sequence["Parameter"],112 declaration_order: t.Sequence["Parameter"],113) -> t.List["Parameter"]:113 invocation_order: t.Sequence[Parameter],114 declaration_order: t.Sequence[Parameter],115) -> t.List[Parameter]:116 """Given a sequence of parameters in the order as should be considered117 for processing and an iterable of parameters that exist, this returns118 a list in the correct order as they should be processed.119 """120119 def sort_key(item: "Parameter") -> t.Tuple[bool, float]:121 def sort_key(item: Parameter) -> t.Tuple[bool, float]:122 try:123 idx: float = invocation_order.index(item)124 except ValueError:125 idx = float("inf")
130 unmodified lines
256257 #: The formatter class to create with :meth:`make_formatter`.258 #:259 #: .. versionadded:: 8.0258 formatter_class: t.Type["HelpFormatter"] = HelpFormatter260 formatter_class: t.Type[HelpFormatter] = HelpFormatter261262 def __init__(263 self,262 command: "Command",263 parent: t.Optional["Context"] = None,264 command: Command,265 parent: t.Optional[Context] = None,266 info_name: t.Optional[str] = None,267 obj: t.Optional[t.Any] = None,268 auto_envvar_prefix: t.Optional[str] = None,269 default_map: t.Optional[t.MutableMapping[str, t.Any]] = None,
193 unmodified lines
463 "ignore_unknown_options": self.ignore_unknown_options,464 "auto_envvar_prefix": self.auto_envvar_prefix,465 }466465 def __enter__(self) -> "Context":467 def __enter__(self) -> Context:468 self._depth += 1469 push_context(self)470 return self471
8 unmodified lines
480 self.close()481 pop_context()482483 @contextmanager482 def scope(self, cleanup: bool = True) -> t.Iterator["Context"]:484 def scope(self, cleanup: bool = True) -> t.Iterator[Context]:485 """This helper method can be used with the context object to promote486 it to the current thread local (see :func:`get_current_context`).487 The default behavior of this is to invoke the cleanup functions which488 can be disabled by setting `cleanup` to `False`. The cleanup
139 unmodified lines
628629 rv = f"{' '.join(parent_command_path)} {rv}"630 return rv.lstrip()631630 def find_root(self) -> "Context":632 def find_root(self) -> Context:633 """Finds the outermost context."""634 node = self635 while node.parent is not None:636 node = node.parent637 return node638639 def find_object(self, object_type: t.Type[V]) -> t.Optional[V]:640 """Finds the closest object of a given type."""639 node: t.Optional["Context"] = self641 node: t.Optional[Context] = self642643 while node is not None:644 if isinstance(node.obj, object_type):645 return node.obj
12 unmodified lines
658 return rv659660 @t.overload661 def lookup_default(660 self, name: str, call: "te.Literal[True]" = True662 self, name: str, call: te.Literal[True] = True663 ) -> t.Optional[t.Any]:664 ...665666 @t.overload667 def lookup_default(666 self, name: str, call: "te.Literal[False]" = ...668 self, name: str, call: te.Literal[False] = ...669 ) -> t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]]:670 ...671672 def lookup_default(self, name: str, call: bool = True) -> t.Optional[t.Any]:
15 unmodified lines
688 return value689690 return None691690 def fail(self, message: str) -> "te.NoReturn":692 def fail(self, message: str) -> te.NoReturn:693 """Aborts the execution of the program with a specific error694 message.695696 :param message: the error message to fail with.697 """698 raise UsageError(message, self)699698 def abort(self) -> "te.NoReturn":700 def abort(self) -> te.NoReturn:701 """Aborts the script."""702 raise Abort()703702 def exit(self, code: int = 0) -> "te.NoReturn":704 def exit(self, code: int = 0) -> te.NoReturn:705 """Exits the application with a given exit code."""706 raise Exit(code)707708 def get_usage(self) -> str:
7 unmodified lines
716 context and command.717 """718 return self.command.get_help(self)719718 def _make_sub_context(self, command: "Command") -> "Context":720 def _make_sub_context(self, command: Command) -> Context:721 """Create a new context of the same type as this context, but722 for a new command.723724 :meta private:
2 unmodified lines
727728 @t.overload729 def invoke(730 __self, # noqa: B902729 __callback: "t.Callable[..., V]",731 __callback: t.Callable[..., V],732 *args: t.Any,733 **kwargs: t.Any,734 ) -> V:735 ...736737 @t.overload738 def invoke(739 __self, # noqa: B902738 __callback: "Command",740 __callback: Command,741 *args: t.Any,742 **kwargs: t.Any,743 ) -> t.Any:744 ...745746 def invoke(747 __self, # noqa: B902746 __callback: t.Union["Command", "t.Callable[..., V]"],748 __callback: t.Union[Command, t.Callable[..., V]],749 *args: t.Any,750 **kwargs: t.Any,751 ) -> t.Union[t.Any, V]:752 """Invokes a command callback in exactly the way it expects. There
43 unmodified lines
796 with ctx:797 return __callback(*args, **kwargs)798799 def forward(798 __self, __cmd: "Command", *args: t.Any, **kwargs: t.Any # noqa: B902800 __self, __cmd: Command, *args: t.Any, **kwargs: t.Any # noqa: B902801 ) -> t.Any:802 """Similar to :meth:`invoke` but fills in default keyword803 arguments from the current context if the other command expects804 it. This cannot invoke callbacks directly, only other commands.
103 unmodified lines
908 self,909 name: t.Optional[str],910 context_settings: t.Optional[t.MutableMapping[str, t.Any]] = None,911 callback: t.Optional[t.Callable[..., t.Any]] = None,910 params: t.Optional[t.List["Parameter"]] = None,912 params: t.Optional[t.List[Parameter]] = None,913 help: t.Optional[str] = None,914 epilog: t.Optional[str] = None,915 short_help: t.Optional[str] = None,916 options_metavar: t.Optional[str] = "[OPTIONS]",
19 unmodified lines
936 self.callback = callback937 #: the list of parameters for this command in the order they938 #: should show up in the help page and execute. Eager parameters939 #: will automatically be handled before non eager ones.938 self.params: t.List["Parameter"] = params or []940 self.params: t.List[Parameter] = params or []941 self.help = help942 self.epilog = epilog943 self.options_metavar = options_metavar944 self.short_help = short_help
24 unmodified lines
969 formatter = ctx.make_formatter()970 self.format_usage(ctx, formatter)971 return formatter.getvalue().rstrip("\n")972971 def get_params(self, ctx: Context) -> t.List["Parameter"]:973 def get_params(self, ctx: Context) -> t.List[Parameter]:974 rv = self.params975 help_option = self.get_help_option(ctx)976977 if help_option is not None:
27 unmodified lines
1005 all_names.difference_update(param.opts)1006 all_names.difference_update(param.secondary_opts)1007 return list(all_names)10081007 def get_help_option(self, ctx: Context) -> t.Optional["Option"]:1009 def get_help_option(self, ctx: Context) -> t.Optional[Option]:1010 """Returns the help option object."""1011 help_options = self.get_help_option_names(ctx)10121013 if not help_options or not self.add_help_option:1014 return None10151014 def show_help(ctx: Context, param: "Parameter", value: str) -> None:1016 def show_help(ctx: Context, param: Parameter, value: str) -> None:1017 if value and not ctx.resilient_parsing:1018 echo(ctx.get_help(), color=ctx.color)1019 ctx.exit()1020
166 unmodified lines
11871188 if self.callback is not None:1189 return ctx.invoke(self.callback, **ctx.params)11901189 def shell_complete(self, ctx: Context, incomplete: str) -> t.List["CompletionItem"]:1191 def shell_complete(self, ctx: Context, incomplete: str) -> t.List[CompletionItem]:1192 """Return a list of completions for the incomplete value. Looks1193 at the names of options and chained multi-commands.11941195 Any command could be part of a chained multi-command, so sibling
5 unmodified lines
1201 .. versionadded:: 8.01202 """1203 from click.shell_completion import CompletionItem12041203 results: t.List["CompletionItem"] = []1205 results: t.List[CompletionItem] = []12061207 if incomplete and not incomplete[0].isalnum():1208 for param in self.get_params(ctx):1209 if (
30 unmodified lines
1240 self,1241 args: t.Optional[t.Sequence[str]] = None,1242 prog_name: t.Optional[str] = None,1243 complete_var: t.Optional[str] = None,1242 standalone_mode: "te.Literal[True]" = True,1244 standalone_mode: t.Literal[True] = True,1245 **extra: t.Any,1244 ) -> "te.NoReturn":1246 ) -> t.NoReturn:1247 ...12481249 @t.overload1250 def main(
220 unmodified lines
1471 #: default class. This makes a custom group class continue to make1472 #: custom groups.1473 #:1474 #: .. versionadded:: 8.01473 group_class: t.Optional[t.Union[t.Type["Group"], t.Type[type]]] = None1475 group_class: t.Optional[t.Union[t.Type[Group], t.Type[type]]] = None1476 # Literal[type] isn't valid, so use Type[type]14771478 def __init__(1479 self,
122 unmodified lines
16021603 return decorator16041605 @t.overload1604 def group(self, __func: t.Callable[..., t.Any]) -> "Group":1606 def group(self, __func: t.Callable[..., t.Any]) -> Group:1607 ...16081609 @t.overload1610 def group(1611 self, *args: t.Any, **kwargs: t.Any1610 ) -> t.Callable[[t.Callable[..., t.Any]], "Group"]:1612 ) -> t.Callable[[t.Callable[..., t.Any]], Group]:1613 ...16141615 def group(1616 self, *args: t.Any, **kwargs: t.Any1615 ) -> t.Union[t.Callable[[t.Callable[..., t.Any]], "Group"], "Group"]:1617 ) -> t.Union[t.Callable[[t.Callable[..., t.Any]], Group], Group]:1618 """A shortcut decorator for declaring and attaching a group to1619 the group. This takes the same arguments as :func:`group` and1620 immediately registers the created group with this group by1621 calling :meth:`add_command`.
23 unmodified lines
1645 kwargs["cls"] = type(self)1646 else:1647 kwargs["cls"] = self.group_class16481647 def decorator(f: t.Callable[..., t.Any]) -> "Group":1649 def decorator(f: t.Callable[..., t.Any]) -> Group:1650 cmd: Group = group(*args, **kwargs)(f)1651 self.add_command(cmd)1652 return cmd1653
203 unmodified lines
1857 self.parse_args(ctx, ctx.args)1858 ctx.fail(_("No such command {name!r}.").format(name=original_cmd_name))1859 return cmd_name if cmd else None, cmd, args[1:]18601859 def shell_complete(self, ctx: Context, incomplete: str) -> t.List["CompletionItem"]:1861 def shell_complete(self, ctx: Context, incomplete: str) -> t.List[CompletionItem]:1862 """Return a list of completions for the incomplete value. Looks1863 at the names of options, subcommands, and chained1864 multi-commands.1865
166 unmodified lines
2032 param_decls: t.Optional[t.Sequence[str]] = None,2033 type: t.Optional[t.Union[types.ParamType, t.Any]] = None,2034 required: bool = False,2035 default: t.Optional[t.Union[t.Any, t.Callable[[], t.Any]]] = None,2034 callback: t.Optional[t.Callable[[Context, "Parameter", t.Any], t.Any]] = None,2036 callback: t.Optional[t.Callable[[Context, Parameter, t.Any], t.Any]] = None,2037 nargs: t.Optional[int] = None,2038 multiple: bool = False,2039 metavar: t.Optional[str] = None,2040 expose_value: bool = True,2041 is_eager: bool = False,2042 envvar: t.Optional[t.Union[str, t.Sequence[str]]] = None,2043 shell_complete: t.Optional[2044 t.Callable[2043 [Context, "Parameter", str],2044 t.Union[t.List["CompletionItem"], t.List[str]],2045 [Context, Parameter, str],2046 t.Union[t.List[CompletionItem], t.List[str]],2047 ]2048 ] = None,2049 ) -> None:2050 self.name: t.Optional[str]
116 unmodified lines
2167 return metavar21682169 @t.overload2170 def get_default(2169 self, ctx: Context, call: "te.Literal[True]" = True2171 self, ctx: Context, call: te.Literal[True] = True2172 ) -> t.Optional[t.Any]:2173 ...21742175 @t.overload
187 unmodified lines
2363 """2364 hint_list = self.opts or [self.human_readable_name]2365 return " / ".join(f"'{x}'" for x in hint_list)23662365 def shell_complete(self, ctx: Context, incomplete: str) -> t.List["CompletionItem"]:2367 def shell_complete(self, ctx: Context, incomplete: str) -> t.List[CompletionItem]:2368 """Return a list of completions for the incomplete value. If a2369 ``shell_complete`` function was given during init, it is used.2370 Otherwise, the :attr:`type`2371 :meth:`~click.types.ParamType.shell_complete` function is used.
410 unmodified lines
2782 return ("; " if any_prefix_is_slash else " / ").join(rv), help27832784 @t.overload2785 def get_default(2784 self, ctx: Context, call: "te.Literal[True]" = True2786 self, ctx: Context, call: te.Literal[True] = True2787 ) -> t.Optional[t.Any]:2788 ...27892790 @t.overload
79 unmodified lines
28702871 return rv28722873 def consume_value(2872 self, ctx: Context, opts: t.Mapping[str, "Parameter"]2874 self, ctx: Context, opts: t.Mapping[str, Parameter]2875 ) -> t.Tuple[t.Any, ParameterSource]:2876 value, source = super().consume_value(ctx, opts)28772878 # The parser will emit a sentinel value if the option can be
130 unmodified lines
modified:src/click/decorators.py+12 added-10 removed
1from __future__ import annotations23import inspect4import typing as t5from functools import update_wrapper6from gettext import gettext as _
17 unmodified lines
24_AnyCallable = t.Callable[..., t.Any]25FC = t.TypeVar("FC", bound=t.Union[_AnyCallable, Command])262726def pass_context(f: "t.Callable[te.Concatenate[Context, P], R]") -> "t.Callable[P, R]":28def pass_context(f: t.Callable[te.Concatenate[Context, P], R]) -> t.Callable[P, R]:29 """Marks a callback as wanting to receive the current context30 object as first argument.31 """3231 def new_func(*args: "P.args", **kwargs: "P.kwargs") -> "R":33 def new_func(*args: P.args, **kwargs: P.kwargs) -> R:34 return f(get_current_context(), *args, **kwargs)3536 return update_wrapper(new_func, f)373837def pass_obj(f: "t.Callable[te.Concatenate[t.Any, P], R]") -> "t.Callable[P, R]":39def pass_obj(f: t.Callable[te.Concatenate[t.Any, P], R]) -> t.Callable[P, R]:40 """Similar to :func:`pass_context`, but only pass the object on the41 context onwards (:attr:`Context.obj`). This is useful if that object42 represents the state of a nested system.43 """4443 def new_func(*args: "P.args", **kwargs: "P.kwargs") -> "R":45 def new_func(*args: P.args, **kwargs: P.kwargs) -> R:46 return f(get_current_context().obj, *args, **kwargs)4748 return update_wrapper(new_func, f)495051def make_pass_decorator(52 object_type: t.Type[T], ensure: bool = False51) -> t.Callable[["t.Callable[te.Concatenate[T, P], R]"], "t.Callable[P, R]"]:53) -> t.Callable[[t.Callable[te.Concatenate[T, P], R]], t.Callable[P, R]]:54 """Given an object type this creates a decorator that will work55 similar to :func:`pass_obj` but instead of passing the object of the56 current context, it will find the innermost context of type57 :func:`object_type`.
14 unmodified lines
72 :param ensure: if set to `True`, a new object will be created and73 remembered on the context if it's not there yet.74 """7574 def decorator(f: "t.Callable[te.Concatenate[T, P], R]") -> "t.Callable[P, R]":75 def new_func(*args: "P.args", **kwargs: "P.kwargs") -> "R":76 def decorator(f: t.Callable[te.Concatenate[T, P], R]) -> t.Callable[P, R]:77 def new_func(*args: P.args, **kwargs: P.kwargs) -> R:78 ctx = get_current_context()7980 obj: t.Optional[T]81 if ensure:
16 unmodified lines
9899100def pass_meta_key(101 key: str, *, doc_description: t.Optional[str] = None100) -> "t.Callable[[t.Callable[te.Concatenate[t.Any, P], R]], t.Callable[P, R]]":102) -> t.Callable[[t.Callable[te.Concatenate[t.Any, P], R]], t.Callable[P, R]]:103 """Create a decorator that passes a key from104 :attr:`click.Context.meta` as the first argument to the decorated105 function.106
4 unmodified lines
111112 .. versionadded:: 8.0113 """114113 def decorator(f: "t.Callable[te.Concatenate[t.Any, P], R]") -> "t.Callable[P, R]":114 def new_func(*args: "P.args", **kwargs: "P.kwargs") -> R:115 def decorator(f: t.Callable[te.Concatenate[t.Any, P], R]) -> t.Callable[P, R]:116 def new_func(*args: P.args, **kwargs: P.kwargs) -> R:117 ctx = get_current_context()118 obj = ctx.meta[key]119 return ctx.invoke(f, obj, *args, **kwargs)120
435 unmodified lines
modified:src/click/exceptions.py+10 added-8 removed
1from __future__ import annotations23import typing as t4from gettext import gettext as _5from gettext import ngettext6
49 unmodified lines
56 """5758 exit_code = 25958 def __init__(self, message: str, ctx: t.Optional["Context"] = None) -> None:60 def __init__(self, message: str, ctx: t.Optional[Context] = None) -> None:61 super().__init__(message)62 self.ctx = ctx61 self.cmd: t.Optional["Command"] = self.ctx.command if self.ctx else None63 self.cmd: t.Optional[Command] = self.ctx.command if self.ctx else None6465 def show(self, file: t.Optional[t.IO[t.Any]] = None) -> None:66 if file is None:67 file = get_text_stderr()
37 unmodified lines
105106 def __init__(107 self,108 message: str,107 ctx: t.Optional["Context"] = None,108 param: t.Optional["Parameter"] = None,109 ctx: t.Optional[Context] = None,110 param: t.Optional[Parameter] = None,111 param_hint: t.Optional[str] = None,112 ) -> None:113 super().__init__(message, ctx)114 self.param = param
26 unmodified lines
141142 def __init__(143 self,144 message: t.Optional[str] = None,143 ctx: t.Optional["Context"] = None,144 param: t.Optional["Parameter"] = None,145 ctx: t.Optional[Context] = None,146 param: t.Optional[Parameter] = None,147 param_hint: t.Optional[str] = None,148 param_type: t.Optional[str] = None,149 ) -> None:150 super().__init__(message or "", ctx, param, param_hint)
56 unmodified lines
207 self,208 option_name: str,209 message: t.Optional[str] = None,210 possibilities: t.Optional[t.Sequence[str]] = None,209 ctx: t.Optional["Context"] = None,211 ctx: t.Optional[Context] = None,212 ) -> None:213 if message is None:214 message = _("No such option: {name}").format(name=option_name)215
24 unmodified lines
240 :param option_name: the name of the option being used incorrectly.241 """242243 def __init__(242 self, option_name: str, message: str, ctx: t.Optional["Context"] = None244 self, option_name: str, message: str, ctx: t.Optional[Context] = None245 ) -> None:246 super().__init__(message, ctx)247 self.option_name = option_name248
42 unmodified lines
modified:src/click/formatting.py+2 added
1from __future__ import annotations23import typing as t4from contextlib import contextmanager5from gettext import gettext as _6
297 unmodified lines
modified:src/click/globals.py+6 added-4 removed
1from __future__ import annotations23import typing as t4from threading import local56if t.TYPE_CHECKING:
3 unmodified lines
10_local = local()111213@t.overload12def get_current_context(silent: "te.Literal[False]" = False) -> "Context":14def get_current_context(silent: te.Literal[False] = False) -> Context:15 ...161718@t.overload17def get_current_context(silent: bool = ...) -> t.Optional["Context"]:19def get_current_context(silent: bool = ...) -> t.Optional[Context]:20 ...212221def get_current_context(silent: bool = False) -> t.Optional["Context"]:23def get_current_context(silent: bool = False) -> t.Optional[Context]:24 """Returns the current click context. This can be used as a way to25 access the current context object from anywhere. This is a more implicit26 alternative to the :func:`pass_context` decorator. This function is27 primarily useful for helpers such as :func:`echo` which might be
15 unmodified lines
4344 return None454645def push_context(ctx: "Context") -> None:47def push_context(ctx: Context) -> None:48 """Pushes a new context to the current stack."""49 _local.__dict__.setdefault("stack", []).append(ctx)5051
19 unmodified lines
modified:src/click/parser.py+13 added-11 removed
19 unmodified lines
20# This code uses parts of optparse written by Gregory P. Ward and21# maintained by the Python Software Foundation.22# Copyright 2001-2006 Gregory P. Ward23# Copyright 2002-2006 Python Software Foundation24from __future__ import annotations2526import typing as t27from collections import deque28from gettext import gettext as _29from gettext import ngettext
34 unmodified lines
64 nargs_spec = deque(nargs_spec)65 rv: t.List[t.Union[str, t.Tuple[t.Optional[str], ...], None]] = []66 spos: t.Optional[int] = None6766 def _fetch(c: "te.Deque[V]") -> t.Optional[V]:68 def _fetch(c: te.Deque[V]) -> t.Optional[V]:69 try:70 if spos is None:71 return c.popleft()72 else:
43 unmodified lines
116 return opt[:2], opt[2:]117 return first, opt[1:]118119118def _normalize_opt(opt: str, ctx: t.Optional["Context"]) -> str:120def _normalize_opt(opt: str, ctx: t.Optional[Context]) -> str:121 if ctx is None or ctx.token_normalize_func is None:122 return opt123 prefix, opt = _split_opt(opt)124 return f"{prefix}{ctx.token_normalize_func(opt)}"
1 unmodified line
126127class _Option:128 def __init__(129 self,128 obj: "CoreOption",130 obj: CoreOption,131 opts: t.Sequence[str],132 dest: t.Optional[str],133 action: t.Optional[str] = None,134 nargs: int = 1,
26 unmodified lines
161 @property162 def takes_value(self) -> bool:163 return self.action in ("store", "append")164163 def process(self, value: t.Any, state: "_ParsingState") -> None:165 def process(self, value: t.Any, state: _ParsingState) -> None:166 if self.action == "store":167 state.opts[self.dest] = value # type: ignore168 elif self.action == "store_const":169 state.opts[self.dest] = self.const # type: ignore
8 unmodified lines
178 state.order.append(self.obj)179180181class _Argument:180 def __init__(self, obj: "CoreArgument", dest: t.Optional[str], nargs: int = 1):182 def __init__(self, obj: CoreArgument, dest: t.Optional[str], nargs: int = 1):183 self.dest = dest184 self.nargs = nargs185 self.obj = obj186187 def process(188 self,189 value: t.Union[t.Optional[str], t.Sequence[t.Optional[str]]],188 state: "_ParsingState",190 state: _ParsingState,191 ) -> None:192 if self.nargs > 1:193 assert value is not None194 holes = sum(1 for x in value if x is None)
19 unmodified lines
214 def __init__(self, rargs: t.List[str]) -> None:215 self.opts: t.Dict[str, t.Any] = {}216 self.largs: t.List[str] = []217 self.rargs = rargs216 self.order: t.List["CoreParameter"] = []218 self.order: t.List[CoreParameter] = []219220221class _OptionParser:222 """The option parser is an internal class that is ultimately used to
11 unmodified lines
234 .. deprecated:: 8.2235 Will be removed in Click 9.0.236 """237236 def __init__(self, ctx: t.Optional["Context"] = None) -> None:238 def __init__(self, ctx: t.Optional[Context] = None) -> None:239 #: The :class:`~click.Context` for this parser. This might be240 #: `None` for some advanced use cases.241 self.ctx = ctx242 #: This controls how the parser deals with interspersed arguments.
17 unmodified lines
260 self._args: t.List[_Argument] = []261262 def add_option(263 self,262 obj: "CoreOption",264 obj: CoreOption,265 opts: t.Sequence[str],266 dest: t.Optional[str],267 action: t.Optional[str] = None,268 nargs: int = 1,
15 unmodified lines
284 for opt in option._long_opts:285 self._long_opt[opt] = option286287 def add_argument(286 self, obj: "CoreArgument", dest: t.Optional[str], nargs: int = 1288 self, obj: CoreArgument, dest: t.Optional[str], nargs: int = 1289 ) -> None:290 """Adds a positional argument named `dest` to the parser.291292 The `obj` can be used to identify the option in the order list
2 unmodified lines
295 self._args.append(_Argument(obj, dest=dest, nargs=nargs))296297 def parse_args(298 self, args: t.List[str]297 ) -> t.Tuple[t.Dict[str, t.Any], t.List[str], t.List["CoreParameter"]]:299 ) -> t.Tuple[t.Dict[str, t.Any], t.List[str], t.List[CoreParameter]]:300 """Parses positional arguments and returns ``(values, args, order)``301 for the parsed options and arguments as well as the leftover302 arguments if there are any. The order is a list of objects as they303 appear on the command line. If arguments appear multiple times they
228 unmodified lines
modified:src/click/shell_completion.py+2 added
1from __future__ import annotations23import os4import re5import typing as t6from gettext import gettext as _
628 unmodified lines
modified:src/click/termui.py+3 added-1 removed
1from __future__ import annotations23import inspect4import io5import itertools6import sys
290 unmodified lines
297 width: int = 36,298 file: t.Optional[t.TextIO] = None,299 color: t.Optional[bool] = None,300 update_min_steps: int = 1,299) -> "ProgressBar[V]":301) -> ProgressBar[V]:302 """This function creates an iterable context manager that can be used303 to iterate over something while showing a progress bar. It will304 either iterate over the `iterable` or `length` items (that are counted305 up). While iteration happens, this function will print a rendered
481 unmodified lines
modified:src/click/testing.py+6 added-4 removed
1from __future__ import annotations23import contextlib4import io5import os6import shlex
97 unmodified lines
104 """Holds the captured result of an invoked CLI script."""105106 def __init__(107 self,106 runner: "CliRunner",108 runner: CliRunner,109 stdout_bytes: bytes,110 stderr_bytes: t.Optional[bytes],111 return_value: t.Any,112 exit_code: int,
75 unmodified lines
188 self.env: t.Mapping[str, t.Optional[str]] = env or {}189 self.echo_stdin = echo_stdin190 self.mix_stderr = mix_stderr191190 def get_default_prog_name(self, cli: "Command") -> str:192 def get_default_prog_name(self, cli: Command) -> str:193 """Given a command object it will return the default program name194 for it. The default is the `name` attribute or ``"root"`` if not195 set.196 """
152 unmodified lines
349 formatting.FORCED_WIDTH = old_forced_width350351 def invoke(352 self,351 cli: "Command",353 cli: Command,354 args: t.Optional[t.Union[str, t.Sequence[str]]] = None,355 input: t.Optional[t.Union[str, bytes, t.IO[t.Any]]] = None,356 env: t.Optional[t.Mapping[str, t.Optional[str]]] = None,357 catch_exceptions: bool = True,
92 unmodified lines
450 )451452 @contextlib.contextmanager453 def isolated_filesystem(452 self, temp_dir: t.Optional[t.Union[str, "os.PathLike[str]"]] = None454 self, temp_dir: t.Optional[t.Union[str, os.PathLike[str]]] = None455 ) -> t.Iterator[str]:456 """A context manager that creates a temporary directory and457 changes the current working directory to it. This isolates tests458 that affect the contents of the CWD to prevent them from
23 unmodified lines
modified:src/click/types.py+45 added-43 removed
1from __future__ import annotations23import os4import stat5import sys6import typing as t
70 unmodified lines
7778 def __call__(79 self,80 value: t.Any,79 param: t.Optional["Parameter"] = None,80 ctx: t.Optional["Context"] = None,81 param: t.Optional[Parameter] = None,82 ctx: t.Optional[Context] = None,83 ) -> t.Any:84 if value is not None:85 return self.convert(value, param, ctx)8685 def get_metavar(self, param: "Parameter") -> t.Optional[str]:87 def get_metavar(self, param: Parameter) -> t.Optional[str]:88 """Returns the metavar default for this param if it provides one."""8988 def get_missing_message(self, param: "Parameter") -> t.Optional[str]:90 def get_missing_message(self, param: Parameter) -> t.Optional[str]:91 """Optionally might return extra information about a missing92 parameter.9394 .. versionadded:: 2.095 """9697 def convert(96 self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]98 self, value: t.Any, param: t.Optional[Parameter], ctx: t.Optional[Context]99 ) -> t.Any:100 """Convert the value to the correct type. This is not called if101 the value is ``None`` (the missing value).102
27 unmodified lines
130131 def fail(132 self,133 message: str,132 param: t.Optional["Parameter"] = None,133 ctx: t.Optional["Context"] = None,134 ) -> "t.NoReturn":134 param: t.Optional[Parameter] = None,135 ctx: t.Optional[Context] = None,136 ) -> t.NoReturn:137 """Helper method to fail with an invalid value message."""138 raise BadParameter(message, ctx=ctx, param=param)139140 def shell_complete(139 self, ctx: "Context", param: "Parameter", incomplete: str140 ) -> t.List["CompletionItem"]:141 self, ctx: Context, param: Parameter, incomplete: str142 ) -> t.List[CompletionItem]:143 """Return a list of144 :class:`~click.shell_completion.CompletionItem` objects for the145 incomplete value. Most types do not provide completions, but146 some do, and this allows custom types to provide custom
26 unmodified lines
173 info_dict["func"] = self.func174 return info_dict175176 def convert(175 self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]177 self, value: t.Any, param: t.Optional[Parameter], ctx: t.Optional[Context]178 ) -> t.Any:179 try:180 return self.func(value)181 except ValueError:
8 unmodified lines
190class UnprocessedParamType(ParamType):191 name = "text"192193 def convert(192 self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]194 self, value: t.Any, param: t.Optional[Parameter], ctx: t.Optional[Context]195 ) -> t.Any:196 return value197198 def __repr__(self) -> str:
3 unmodified lines
202class StringParamType(ParamType):203 name = "text"204205 def convert(204 self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]206 self, value: t.Any, param: t.Optional[Parameter], ctx: t.Optional[Context]207 ) -> t.Any:208 if isinstance(value, bytes):209 enc = _get_argv_encoding()210 try:
42 unmodified lines
253 info_dict["choices"] = self.choices254 info_dict["case_sensitive"] = self.case_sensitive255 return info_dict256255 def get_metavar(self, param: "Parameter") -> str:257 def get_metavar(self, param: Parameter) -> str:258 choices_str = "|".join(self.choices)259260 # Use curly braces to indicate a required argument.261 if param.required and param.param_type_name == "argument":
1 unmodified line
263264 # Use square braces to indicate an option or optional argument.265 return f"[{choices_str}]"266265 def get_missing_message(self, param: "Parameter") -> str:267 def get_missing_message(self, param: Parameter) -> str:268 return _("Choose from:\n\t{choices}").format(choices=",\n\t".join(self.choices))269270 def convert(269 self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]271 self, value: t.Any, param: t.Optional[Parameter], ctx: t.Optional[Context]272 ) -> t.Any:273 # Match through normalization and case sensitivity274 # first do token_normalize_func, then lowercase275 # preserve original `value` to produce an accurate message in
32 unmodified lines
308 def __repr__(self) -> str:309 return f"Choice({list(self.choices)})"310311 def shell_complete(310 self, ctx: "Context", param: "Parameter", incomplete: str311 ) -> t.List["CompletionItem"]:312 self, ctx: Context, param: Parameter, incomplete: str313 ) -> t.List[CompletionItem]:314 """Complete choices that start with the incomplete value.315316 :param ctx: Invocation context for this command.317 :param param: The parameter that is requesting completion.
48 unmodified lines
366 info_dict = super().to_info_dict()367 info_dict["formats"] = self.formats368 return info_dict369368 def get_metavar(self, param: "Parameter") -> str:370 def get_metavar(self, param: Parameter) -> str:371 return f"[{'|'.join(self.formats)}]"372373 def _try_to_convert_date(self, value: t.Any, format: str) -> t.Optional[datetime]:374 try:
1 unmodified line
376 except ValueError:377 return None378379 def convert(378 self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]380 self, value: t.Any, param: t.Optional[Parameter], ctx: t.Optional[Context]381 ) -> t.Any:382 if isinstance(value, datetime):383 return value384
21 unmodified lines
406class _NumberParamTypeBase(ParamType):407 _number_class: t.ClassVar[t.Type[t.Any]]408409 def convert(408 self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]410 self, value: t.Any, param: t.Optional[Parameter], ctx: t.Optional[Context]411 ) -> t.Any:412 try:413 return self._number_class(value)414 except ValueError:
32 unmodified lines
447 )448 return info_dict449450 def convert(449 self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]451 self, value: t.Any, param: t.Optional[Parameter], ctx: t.Optional[Context]452 ) -> t.Any:453 import operator454455 rv = super().convert(value, param, ctx)
21 unmodified lines
477 )478479 return rv480479 def _clamp(self, bound: float, dir: "te.Literal[1, -1]", open: bool) -> float:481 def _clamp(self, bound: float, dir: te.Literal[1, -1], open: bool) -> float:482 """Find the valid value to clamp to bound in the given483 direction.484485 :param bound: The boundary value.
46 unmodified lines
532533 name = "integer range"534535 def _clamp( # type: ignore534 self, bound: int, dir: "te.Literal[1, -1]", open: bool536 self, bound: int, dir: te.Literal[1, -1], open: bool537 ) -> int:538 if not open:539 return bound540
40 unmodified lines
581582 if (min_open or max_open) and clamp:583 raise TypeError("Clamping is not supported for open bounds.")584583 def _clamp(self, bound: float, dir: "te.Literal[1, -1]", open: bool) -> float:585 def _clamp(self, bound: float, dir: te.Literal[1, -1], open: bool) -> float:586 if not open:587 return bound588589 # Could use Python 3.9's math.nextafter here, but clamping an
5 unmodified lines
595class BoolParamType(ParamType):596 name = "boolean"597598 def convert(597 self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]599 self, value: t.Any, param: t.Optional[Parameter], ctx: t.Optional[Context]600 ) -> t.Any:601 if value in {False, True}:602 return bool(value)603
16 unmodified lines
620class UUIDParameterType(ParamType):621 name = "uuid"622623 def convert(622 self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]624 self, value: t.Any, param: t.Optional[Parameter], ctx: t.Optional[Context]625 ) -> t.Any:626 import uuid627628 if isinstance(value, uuid.UUID):
60 unmodified lines
689 info_dict = super().to_info_dict()690 info_dict.update(mode=self.mode, encoding=self.encoding)691 return info_dict692691 def resolve_lazy_flag(self, value: "t.Union[str, os.PathLike[str]]") -> bool:693 def resolve_lazy_flag(self, value: t.Union[str, os.PathLike[str]]) -> bool:694 if self.lazy is not None:695 return self.lazy696 if os.fspath(value) == "-":697 return False
2 unmodified lines
700 return False701702 def convert(703 self,702 value: t.Union[str, "os.PathLike[str]", t.IO[t.Any]],703 param: t.Optional["Parameter"],704 ctx: t.Optional["Context"],704 value: t.Union[str, os.PathLike[str], t.IO[t.Any]],705 param: t.Optional[Parameter],706 ctx: t.Optional[Context],707 ) -> t.IO[t.Any]:708 if _is_file_like(value):709 return value710
31 unmodified lines
742 except OSError as e: # noqa: B014743 self.fail(f"'{format_filename(value)}': {e.strerror}", param, ctx)744745 def shell_complete(744 self, ctx: "Context", param: "Parameter", incomplete: str745 ) -> t.List["CompletionItem"]:746 self, ctx: Context, param: Parameter, incomplete: str747 ) -> t.List[CompletionItem]:748 """Return a special completion marker that tells the completion749 system to use the shell to provide file path completions.750751 :param ctx: Invocation context for this command.
6 unmodified lines
758759 return [CompletionItem(incomplete, type="file")]760761760def _is_file_like(value: t.Any) -> "te.TypeGuard[t.IO[t.Any]]":762def _is_file_like(value: t.Any) -> te.TypeGuard[t.IO[t.Any]]:763 return hasattr(value, "read") or hasattr(value, "write")764765766class Path(ParamType):
72 unmodified lines
839 )840 return info_dict841842 def coerce_path_result(841 self, value: "t.Union[str, os.PathLike[str]]"842 ) -> "t.Union[str, bytes, os.PathLike[str]]":843 self, value: t.Union[str, os.PathLike[str]]844 ) -> t.Union[str, bytes, os.PathLike[str]]:845 if self.type is not None and not isinstance(value, self.type):846 if self.type is str:847 return os.fsdecode(value)848 elif self.type is bytes:
4 unmodified lines
853 return value854855 def convert(856 self,855 value: "t.Union[str, os.PathLike[str]]",856 param: t.Optional["Parameter"],857 ctx: t.Optional["Context"],858 ) -> "t.Union[str, bytes, os.PathLike[str]]":857 value: t.Union[str, os.PathLike[str]],858 param: t.Optional[Parameter],859 ctx: t.Optional[Context],860 ) -> t.Union[str, bytes, os.PathLike[str]]:861 rv = value862863 is_dash = self.file_okay and self.allow_dash and rv in (b"-", "-")864
60 unmodified lines
925926 return self.coerce_path_result(rv)927928 def shell_complete(927 self, ctx: "Context", param: "Parameter", incomplete: str928 ) -> t.List["CompletionItem"]:929 self, ctx: Context, param: Parameter, incomplete: str930 ) -> t.List[CompletionItem]:931 """Return a special completion marker that tells the completion932 system to use the shell to provide path completions for only933 directories or any paths.934
39 unmodified lines
974 def arity(self) -> int: # type: ignore975 return len(self.types)976977 def convert(976 self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]978 self, value: t.Any, param: t.Optional[Parameter], ctx: t.Optional[Context]979 ) -> t.Any:980 len_type = len(self.types)981 len_value = len(value)982
105 unmodified lines
modified:src/click/utils.py+10 added-8 removed
1from __future__ import annotations23import os4import re5import sys6import typing as t
24 unmodified lines
31def _posixify(name: str) -> str:32 return "-".join(name.split()).lower()333433def safecall(func: "t.Callable[P, R]") -> "t.Callable[P, t.Optional[R]]":35def safecall(func: t.Callable[P, R]) -> t.Callable[P, t.Optional[R]]:36 """Wraps a function so that it swallows exceptions."""3736 def wrapper(*args: "P.args", **kwargs: "P.kwargs") -> t.Optional[R]:38 def wrapper(*args: P.args, **kwargs: P.kwargs) -> t.Optional[R]:39 try:40 return func(*args, **kwargs)41 except Exception:42 pass
70 unmodified lines
113 """114115 def __init__(116 self,115 filename: t.Union[str, "os.PathLike[str]"],117 filename: t.Union[str, os.PathLike[str]],118 mode: str = "r",119 encoding: t.Optional[str] = None,120 errors: t.Optional[str] = "strict",121 atomic: bool = False,
54 unmodified lines
176 """177 if self.should_close:178 self.close()179178 def __enter__(self) -> "LazyFile":180 def __enter__(self) -> LazyFile:181 return self182183 def __exit__(184 self,
14 unmodified lines
199200 def __getattr__(self, name: str) -> t.Any:201 return getattr(self._file, name)202201 def __enter__(self) -> "KeepOpenFile":203 def __enter__(self) -> KeepOpenFile:204 return self205206 def __exit__(207 self,
112 unmodified lines
320 file.write(out) # type: ignore321 file.flush()322323322def get_binary_stream(name: "te.Literal['stdin', 'stdout', 'stderr']") -> t.BinaryIO:324def get_binary_stream(name: te.Literal["stdin", "stdout", "stderr"]) -> t.BinaryIO:325 """Returns a system stream for byte processing.326327 :param name: the name of the stream to open. Valid names are ``'stdin'``,328 ``'stdout'`` and ``'stderr'``
4 unmodified lines
333 return opener()334335336def get_text_stream(335 name: "te.Literal['stdin', 'stdout', 'stderr']",337 name: te.Literal["stdin", "stdout", "stderr"],338 encoding: t.Optional[str] = None,339 errors: t.Optional[str] = "strict",340) -> t.TextIO:341 """Returns a system stream for text processing. This usually returns
61 unmodified lines
403 return f404405406def format_filename(405 filename: "t.Union[str, bytes, os.PathLike[str], os.PathLike[bytes]]",407 filename: t.Union[str, bytes, os.PathLike[str], os.PathLike[bytes]],408 shorten: bool = False,409) -> str:410 """Format a filename as a string for display. Ensures the filename can be411 displayed by replacing any invalid bytes or surrogate escapes in the name
215 unmodified lines
modified:tests/test_imports.py+1 added
25 unmodified lines
26click.echo(json.dumps(rv))27"""2829ALLOWED_IMPORTS = {30 "__future__",31 "weakref",32 "os",33 "struct",34 "collections",
35 unmodified lines
modified:CHANGES.rst+3 added
22 unmodified lines
23 - ``Parameter.add_to_parser`` (on both ``Argument`` and ``Option``) is24 unneeded. Parsing works directly without building a separate parser.25 - ``split_arg_string`` is moved from ``parser`` to ``shell_completion``.2627- Enable deferred evaluation of annotations with28 ``from __future__ import annotations``. :pr:`2270`293031Version 8.1.732-------------3334Released 2023-08-17
1100 unmodified lines