Static typing improvements in `click.shell_completion`
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by jorenham · committed by jorenham · parent 648d7c4 · Browse files · 1 file·+40 added−16 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
1 file+40 added−16 removed
- other:+40 added−16 removed
Provenance
- Commit
bb0cd17- Tree
7b6b4e0- Author
jorenham <jhammudoglu@gmail.com>- Committer
jorenham <jhammudoglu@gmail.com>- Parent
648d7c4
1 file changed+40 added−16 removed
modified:src/click/shell_completion.py+40 added-16 removed
20 unmodified lines21 ctx_args: cabc.MutableMapping[str, t.Any],22 prog_name: str,23 complete_var: str,24 instruction: str,25-) -> int:25+) -> t.Literal[0, 1]:26 """Perform shell completion for the given CLI program.27 28 :param cli: Command being called.29 :param ctx_args: Extra arguments to pass to24 unmodified lines54 55 return 156 57 58-class CompletionItem:58+if t.TYPE_CHECKING:59+ from typing_extensions import TypeVar60+61+ # `Any` is used as default for backwards compatibility (instead of e.g. `str`)62+ _ValueT_co = TypeVar("_ValueT_co", covariant=True, default=t.Any)63+else:64+ _ValueT_co = t.TypeVar("_ValueT_co", covariant=True)65+66+67+class CompletionItem(t.Generic[_ValueT_co]):68 """Represents a completion value and metadata about the value. The69 default metadata is ``type`` to indicate special shell handling,70 and ``help`` if a shell supports showing a help string next to the71 value.14 unmodified lines86 __slots__ = ("value", "type", "help", "_info")87 88 def __init__(89 self,81- value: t.Any,90+ value: _ValueT_co,91 type: str = "plain",92 help: str | None = None,93 **kwargs: t.Any,94 ) -> None:86- self.value: t.Any = value95+ self.value: _ValueT_co = value96 self.type: str = type97 self.help: str | None = help98 self._info = kwargs99 106 unmodified lines206 "(%(complete_func)s)";207 """208 209 210+class _SourceVarsDict(t.TypedDict):211+ complete_func: str212+ complete_var: str213+ prog_name: str214+215+216 class ShellComplete:217 """Base class for providing shell completion support. A subclass for218 a given shell will override attributes and methods to implement the219 completion instructions (``source`` and ``complete``).36 unmodified lines256 """257 safe_name = re.sub(r"\W*", "", self.prog_name.replace("-", "_"), flags=re.ASCII)258 return f"_{safe_name}_completion"259 245- def source_vars(self) -> dict[str, t.Any]:260+ def source_vars(self) -> _SourceVarsDict:261 """Vars for formatting :attr:`source_template`.262 263 By default this provides ``complete_func``, ``complete_var``,264 and ``prog_name``.18 unmodified lines283 subclasses.284 """285 raise NotImplementedError286 272- def get_completions(self, args: list[str], incomplete: str) -> list[CompletionItem]:287+ def get_completions(288+ self, args: list[str], incomplete: str289+ ) -> list[CompletionItem[str]]:290 """Determine the context and last complete command or parameter291 from the complete args. Call that object's ``shell_complete``292 method to get the completions for the incomplete value.293 3 unmodified lines297 ctx = _resolve_context(self.cli, self.ctx_args, self.prog_name, args)298 obj, incomplete = _resolve_incomplete(ctx, args, incomplete)299 return obj.shell_complete(ctx, incomplete)300 284- def format_completion(self, item: CompletionItem) -> str:301+ def format_completion(self, item: CompletionItem[str]) -> str:302 """Format a completion item into the form recognized by the303 shell script. This must be implemented by subclasses.304 305 :param item: Completion item to format.67 unmodified lines373 incomplete = ""374 375 return args, incomplete376 360- def format_completion(self, item: CompletionItem) -> str:377+ def format_completion(self, item: CompletionItem[t.Any]) -> str:378 return f"{item.type},{item.value}"379 380 381 class ZshComplete(ShellComplete):13 unmodified lines395 incomplete = ""396 397 return args, incomplete398 382- def format_completion(self, item: CompletionItem) -> str:399+ def format_completion(self, item: CompletionItem[str]) -> str:400 help_ = item.help or "_"401 # The zsh completion script uses `_describe` on items with help402 # texts (which splits the item help from the item value at the403 # first unescaped colon) and `compadd` on items without help29 unmodified lines433 args.pop()434 435 return args, incomplete436 420- def format_completion(self, item: CompletionItem) -> str:437+ def format_completion(self, item: CompletionItem[str]) -> str:438 """439 .. versionchanged:: 8.4.2440 Escape newlines and replace tabs with spaces in the help text to441 fix completion errors with multi-line help strings.8 unmodified lines450 451 return f"{item.type},{item.value}"452 453 437-ShellCompleteType = t.TypeVar("ShellCompleteType", bound="type[ShellComplete]")438-439-440-_available_shells: dict[str, type[ShellComplete]] = {454+_available_shells: t.Final[dict[str, type[ShellComplete]]] = {455 "bash": BashComplete,456 "fish": FishComplete,457 "zsh": ZshComplete,458 }459 460+_ShellCompleteT = t.TypeVar("_ShellCompleteT", bound="ShellComplete")461 462+463 def add_completion_class(448- cls: ShellCompleteType, name: str | None = None449-) -> ShellCompleteType:464+ cls: type[_ShellCompleteT], name: str | None = None465+) -> type[_ShellCompleteT]:466 """Register a :class:`ShellComplete` subclass under the given name.467 The name will be provided by the completion instruction environment468 variable during completion.469 9 unmodified lines479 480 return cls481 482 483+@t.overload484+def get_completion_class(shell: t.Literal["bash"]) -> type[BashComplete]: ...485+@t.overload486+def get_completion_class(shell: t.Literal["fish"]) -> type[FishComplete]: ...487+@t.overload488+def get_completion_class(shell: t.Literal["zsh"]) -> type[ZshComplete]: ...489+@t.overload490+def get_completion_class(shell: str) -> type[ShellComplete] | None: ...491 def get_completion_class(shell: str) -> type[ShellComplete] | None:492 """Look up a registered :class:`ShellComplete` subclass by the name493 provided by the completion instruction environment variable. If the494 name isn't registered, returns ``None``.206 unmodified lines