Skip to content
Myr

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

1 file+40 added−16 removed

modified:src/click/shell_completion.py+40 added-16 removed
20 unmodified lines
21 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.2728 :param cli: Command being called.29 :param ctx_args: Extra arguments to pass to
24 unmodified lines
5455 return 1565758class CompletionItem:58if t.TYPE_CHECKING:59 from typing_extensions import TypeVar6061 # `Any` is used as default for backwards compatibility (instead of e.g. `str`)62 _ValueT_co = TypeVar("_ValueT_co", covariant=True, default=t.Any)63else:64 _ValueT_co = t.TypeVar("_ValueT_co", covariant=True)656667class 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 lines
86 __slots__ = ("value", "type", "help", "_info")8788 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 lines
206"(%(complete_func)s)";207"""208209210class _SourceVarsDict(t.TypedDict):211 complete_func: str212 complete_var: str213 prog_name: str214215216class 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 lines
256 """257 safe_name = re.sub(r"\W*", "", self.prog_name.replace("-", "_"), flags=re.ASCII)258 return f"_{safe_name}_completion"259245 def source_vars(self) -> dict[str, t.Any]:260 def source_vars(self) -> _SourceVarsDict:261 """Vars for formatting :attr:`source_template`.262263 By default this provides ``complete_func``, ``complete_var``,264 and ``prog_name``.
18 unmodified lines
283 subclasses.284 """285 raise NotImplementedError286272 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 lines
297 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)300284 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.304305 :param item: Completion item to format.
67 unmodified lines
373 incomplete = ""374375 return args, incomplete376360 def format_completion(self, item: CompletionItem) -> str:377 def format_completion(self, item: CompletionItem[t.Any]) -> str:378 return f"{item.type},{item.value}"379380381class ZshComplete(ShellComplete):
13 unmodified lines
395 incomplete = ""396397 return args, incomplete398382 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 help
29 unmodified lines
433 args.pop()434435 return args, incomplete436420 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 lines
450451 return f"{item.type},{item.value}"452453437ShellCompleteType = t.TypeVar("ShellCompleteType", bound="type[ShellComplete]")438439440_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}459460_ShellCompleteT = t.TypeVar("_ShellCompleteT", bound="ShellComplete")461462463def 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 lines
479480 return cls481482483@t.overload484def get_completion_class(shell: t.Literal["bash"]) -> type[BashComplete]: ...485@t.overload486def get_completion_class(shell: t.Literal["fish"]) -> type[FishComplete]: ...487@t.overload488def get_completion_class(shell: t.Literal["zsh"]) -> type[ZshComplete]: ...489@t.overload490def get_completion_class(shell: str) -> type[ShellComplete] | None: ...491def 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