Static typing improvements in `click.shell_completion` (#3460)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Kevin Deldycke · committed by GitHub · parents 8929d39, bb0cd17 · 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
d9ff133- Tree
d030162- Author
Kevin Deldycke <kdeldycke@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent 1
8929d39- Parent 2
bb0cd17
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``).41 unmodified lines261 """262 safe_name = re.sub(r"\W*", "", self.prog_name.replace("-", "_"), flags=re.ASCII)263 return f"_{safe_name}_completion"264 250- def source_vars(self) -> dict[str, t.Any]:265+ def source_vars(self) -> _SourceVarsDict:266 """Vars for formatting :attr:`source_template`.267 268 By default this provides ``complete_func``, ``complete_var``,269 and ``prog_name``.18 unmodified lines288 subclasses.289 """290 raise NotImplementedError291 277- def get_completions(self, args: list[str], incomplete: str) -> list[CompletionItem]:292+ def get_completions(293+ self, args: list[str], incomplete: str294+ ) -> list[CompletionItem[str]]:295 """Determine the context and last complete command or parameter296 from the complete args. Call that object's ``shell_complete``297 method to get the completions for the incomplete value.298 3 unmodified lines302 ctx = _resolve_context(self.cli, self.ctx_args, self.prog_name, args)303 obj, incomplete = _resolve_incomplete(ctx, args, incomplete)304 return obj.shell_complete(ctx, incomplete)305 289- def format_completion(self, item: CompletionItem) -> str:306+ def format_completion(self, item: CompletionItem[str]) -> str:307 """Format a completion item into the form recognized by the308 shell script. This must be implemented by subclasses.309 310 :param item: Completion item to format.67 unmodified lines378 incomplete = ""379 380 return args, incomplete381 365- def format_completion(self, item: CompletionItem) -> str:382+ def format_completion(self, item: CompletionItem[t.Any]) -> str:383 return f"{item.type},{item.value}"384 385 386 class ZshComplete(ShellComplete):13 unmodified lines400 incomplete = ""401 402 return args, incomplete403 387- def format_completion(self, item: CompletionItem) -> str:404+ def format_completion(self, item: CompletionItem[str]) -> str:405 help_ = item.help or "_"406 # The zsh completion script uses `_describe` on items with help407 # texts (which splits the item help from the item value at the408 # first unescaped colon) and `compadd` on items without help29 unmodified lines438 args.pop()439 440 return args, incomplete441 425- def format_completion(self, item: CompletionItem) -> str:442+ def format_completion(self, item: CompletionItem[str]) -> str:443 """444 .. versionchanged:: 8.4.2445 Escape newlines and replace tabs with spaces in the help text to446 fix completion errors with multi-line help strings.8 unmodified lines455 456 return f"{item.type},{item.value}"457 458 442-ShellCompleteType = t.TypeVar("ShellCompleteType", bound="type[ShellComplete]")443-444-445-_available_shells: dict[str, type[ShellComplete]] = {459+_available_shells: t.Final[dict[str, type[ShellComplete]]] = {460 "bash": BashComplete,461 "fish": FishComplete,462 "zsh": ZshComplete,463 }464 465+_ShellCompleteT = t.TypeVar("_ShellCompleteT", bound="ShellComplete")466 467+468 def add_completion_class(453- cls: ShellCompleteType, name: str | None = None454-) -> ShellCompleteType:469+ cls: type[_ShellCompleteT], name: str | None = None470+) -> type[_ShellCompleteT]:471 """Register a :class:`ShellComplete` subclass under the given name.472 The name will be provided by the completion instruction environment473 variable during completion.474 9 unmodified lines484 485 return cls486 487 488+@t.overload489+def get_completion_class(shell: t.Literal["bash"]) -> type[BashComplete]: ...490+@t.overload491+def get_completion_class(shell: t.Literal["fish"]) -> type[FishComplete]: ...492+@t.overload493+def get_completion_class(shell: t.Literal["zsh"]) -> type[ZshComplete]: ...494+@t.overload495+def get_completion_class(shell: str) -> type[ShellComplete] | None: ...496 def get_completion_class(shell: str) -> type[ShellComplete] | None:497 """Look up a registered :class:`ShellComplete` subclass by the name498 provided by the completion instruction environment variable. If the499 name isn't registered, returns ``None``.206 unmodified lines