Coverage for typer / _click / shell_completion.py: 100%
118 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-11-18 11:12 +0000
« prev ^ index » next coverage.py v7.13.1, created at 2026-11-18 11:12 +0000
1import re 1adefbghcij
2from abc import ABC, abstractmethod 1adefbghcij
3from collections.abc import MutableMapping 1adefbghcij
4from typing import Any, ClassVar, TypeVar 1adefbghcij
6from .core import Command, Context, Parameter, ParameterSource 1adefbghcij
9class CompletionItem: 1adefbghcij
10 """Represents a completion value and metadata about the value. The
11 default metadata is ``type`` to indicate special shell handling,
12 and ``help`` if a shell supports showing a help string next to the
13 value.
15 Arbitrary parameters can be passed when creating the object, and
16 accessed using ``item.attr``. If an attribute wasn't passed,
17 accessing it returns ``None``.
18 """
20 __slots__ = ("value", "type", "help", "_info") 1adefbghcij
22 def __init__( 1adefbghcij
23 self,
24 value: Any,
25 type: str = "plain",
26 help: str | None = None,
27 **kwargs: Any,
28 ) -> None:
29 self.value: Any = value 1adefbghcij
30 self.type: str = type 1adefbghcij
31 self.help: str | None = help 1adefbghcij
32 self._info = kwargs 1adefbghcij
34 def __getattr__(self, name: str) -> Any: 1adefbghcij
35 return self._info.get(name) 1adefbghcij
38class ShellComplete(ABC): 1adefbghcij
39 """Base class for providing shell completion support. A subclass for
40 a given shell will override attributes and methods to implement the
41 completion instructions (``source`` and ``complete``).
42 """
44 name: ClassVar[str] 1abc
45 """Name to register the shell as with `add_completion_class`. 1adefbghcij
46 This is used in completion instructions (``{name}_source`` and
47 ``{name}_complete``).
48 """
50 source_template: ClassVar[str] 1abc
51 """Completion script template formatted by `source`. This must 1adefbghcij
52 be provided by subclasses.
53 """
55 def __init__( 1adefbghcij
56 self,
57 cli: Command,
58 ctx_args: MutableMapping[str, Any],
59 prog_name: str,
60 complete_var: str,
61 ) -> None:
62 self.cli = cli 1adefbghcij
63 self.ctx_args = ctx_args 1adefbghcij
64 self.prog_name = prog_name 1adefbghcij
65 self.complete_var = complete_var 1adefbghcij
67 @property 1adefbghcij
68 def func_name(self) -> str: 1adefbghcij
69 """The name of the shell function defined by the completion
70 script.
71 """
72 safe_name = re.sub(r"\W*", "", self.prog_name.replace("-", "_"), flags=re.ASCII) 1adefbghcij
73 return f"_{safe_name}_completion" 1adefbghcij
75 @abstractmethod 1adefbghcij
76 def source_vars(self) -> dict[str, Any]: 1adefbghcij
77 """Vars for formatting `source_template`."""
78 pass # pragma: no cover
80 def source(self) -> str: 1adefbghcij
81 """Produce the shell script that defines the completion
82 function. By default this ``%``-style formats
83 `source_template` with the dict returned by `source_vars`.
84 """
85 return self.source_template % self.source_vars() 1adefbghcij
87 @abstractmethod 1adefbghcij
88 def get_completion_args(self) -> tuple[list[str], str]: 1adefbghcij
89 """Use the env vars defined by the shell script to return a
90 tuple of ``args, incomplete``. This must be implemented by
91 subclasses.
92 """
93 pass # pragma: no cover
95 def get_completions(self, args: list[str], incomplete: str) -> list[CompletionItem]: 1adefbghcij
96 """Determine the context and last complete command or parameter
97 from the complete args. Call that object's ``shell_complete``
98 method to get the completions for the incomplete value.
99 """
100 ctx = _resolve_context(self.cli, self.ctx_args, self.prog_name, args) 1adefbghcij
101 obj, incomplete = _resolve_incomplete(ctx, args, incomplete) 1adefbghcij
102 return obj.shell_complete(ctx, incomplete) 1adefbghcij
104 @abstractmethod 1adefbghcij
105 def format_completion(self, item: CompletionItem) -> str: 1adefbghcij
106 """Format a completion item into the form recognized by the
107 shell script. This must be implemented by subclasses.
108 """
109 pass # pragma: no cover
111 def complete(self) -> str: 1adefbghcij
112 """Produce the completion data to send back to the shell.
114 By default this calls `get_completion_args`, gets the
115 completions, then calls `format_completion` for each
116 completion.
117 """
118 args, incomplete = self.get_completion_args() 1adefbghcij
119 completions = self.get_completions(args, incomplete) 1adefbghcij
120 out = [self.format_completion(item) for item in completions] 1adefbghcij
121 return "\n".join(out) 1adefbghcij
124ShellCompleteType = TypeVar("ShellCompleteType", bound="type[ShellComplete]") 1adefbghcij
127_available_shells: dict[str, type[ShellComplete]] = {} 1adefbghcij
130def add_completion_class(cls: ShellCompleteType, name: str) -> ShellCompleteType: 1adefbghcij
131 """Register a `ShellComplete` subclass under the given name.
132 The name will be provided by the completion instruction environment
133 variable during completion.
134 """
135 _available_shells[name] = cls 1adefbghcij
137 return cls 1adefbghcij
140def get_completion_class(shell: str) -> type[ShellComplete] | None: 1adefbghcij
141 """Look up a registered `ShellComplete` subclass by the name
142 provided by the completion instruction environment variable. If the
143 name isn't registered, returns ``None``.
144 """
145 return _available_shells.get(shell) 1adefbghcij
148def split_arg_string(string: str) -> list[str]: 1adefbghcij
149 """Split an argument string as with `shlex.split`, but don't
150 fail if the string is incomplete. Ignores a missing closing quote or
151 incomplete escape sequence and uses the partial token as-is.
152 """
153 import shlex 1adefbghcij
155 lex = shlex.shlex(string, posix=True) 1adefbghcij
156 lex.whitespace_split = True 1adefbghcij
157 lex.commenters = "" 1adefbghcij
158 out = [] 1adefbghcij
160 try: 1adefbghcij
161 for token in lex: 1adefbghcij
162 out.append(token) 1adefbghcij
163 except ValueError: # pragma: no cover
164 # Raised when end-of-string is reached in an invalid state. Use
165 # the partial token as-is. The quote or escape character is in
166 # lex.state, not lex.token.
167 out.append(lex.token)
169 return out 1adefbghcij
172def _is_incomplete_argument(ctx: Context, param: Parameter) -> bool: 1adefbghcij
173 """Determine if the given parameter is an argument that can still
174 accept values.
175 """
176 # avoid circular imports
177 from ..core import TyperArgument 1adefbghcij
179 if not isinstance(param, TyperArgument): 1adefbghcij
180 return False 1adefbghcij
182 value = ctx.params.get(param.name) 1adefbghcij
183 return ( 1adefbghcij
184 param.nargs == -1
185 or ctx.get_parameter_source(param.name) is not ParameterSource.COMMANDLINE
186 or (
187 param.nargs > 1
188 and isinstance(value, (tuple, list))
189 and len(value) < param.nargs
190 )
191 )
194def _start_of_option(ctx: Context, value: str) -> bool: 1adefbghcij
195 """Check if the value looks like the start of an option."""
196 if not value: 1adefbghcij
197 return False 1adefbghcij
199 c = value[0] 1adefbghcij
200 return c in ctx._opt_prefixes 1adefbghcij
203def _is_incomplete_option(ctx: Context, args: list[str], param: Parameter) -> bool: 1adefbghcij
204 """Determine if the given parameter is an option that needs a value."""
205 # avoid circular imports
206 from ..core import TyperOption 1adefbghcij
208 if not isinstance(param, TyperOption): 1adefbghcij
209 return False 1adefbghcij
211 if param.is_flag or param.count: 1adefbghcij
212 return False 1adefbghcij
214 last_option = None 1adefbghcij
216 for index, arg in enumerate(reversed(args)): 1adefbghcij
217 if index + 1 > param.nargs: 1adefbghcij
218 break 1adefbghcij
220 if _start_of_option(ctx, arg): 1adefbghcij
221 last_option = arg 1adefbghcij
222 break 1adefbghcij
224 return last_option is not None and last_option in param.opts 1adefbghcij
227def _resolve_context( 1adefbghcij
228 cli: Command,
229 ctx_args: MutableMapping[str, Any],
230 prog_name: str,
231 args: list[str],
232) -> Context:
233 """Produce the context hierarchy starting with the command and
234 traversing the complete arguments. This only follows the commands,
235 it doesn't trigger input prompts or callbacks.
236 """
237 # avoid circular imports
238 from ..core import TyperGroup 1adefbghcij
240 ctx_args["resilient_parsing"] = True 1adefbghcij
241 with cli.make_context(prog_name, args.copy(), **ctx_args) as ctx: 1adefbghcij
242 args = ctx._protected_args + ctx.args 1adefbghcij
244 while args: 1adefbghcij
245 command = ctx.command 1adefbghcij
247 if isinstance(command, TyperGroup): 1adefbghcij
248 # if not command.chain:
249 name, cmd, args = command.resolve_command(ctx, args) 1adefbghcij
251 if cmd is None: 1adefbghcij
252 return ctx 1adefbghcij
254 with cmd.make_context( 1adefbghcij
255 name, args, parent=ctx, resilient_parsing=True
256 ) as sub_ctx:
257 ctx = sub_ctx 1adefbghcij
258 args = ctx._protected_args + ctx.args 1adefbghcij
259 else: # pragma: no cover
260 break
262 return ctx 1adefbghcij
265def _resolve_incomplete( 1adefbghcij
266 ctx: Context, args: list[str], incomplete: str
267) -> tuple[Command | Parameter, str]:
268 """Find the Click object that will handle the completion of the
269 incomplete value. Return the object and the incomplete value.
270 """
271 # Different shells treat an "=" between a long option name and
272 # value differently. Might keep the value joined, return the "="
273 # as a separate item, or return the split name and value. Always
274 # split and discard the "=" to make completion easier.
275 if incomplete == "=": 1adefbghcij
276 incomplete = "" 1adefbghcij
277 elif "=" in incomplete and _start_of_option(ctx, incomplete): 1adefbghcij
278 name, _, incomplete = incomplete.partition("=") 1adefbghcij
279 args.append(name) 1adefbghcij
281 # The "--" marker tells Click to stop treating values as options
282 # even if they start with the option character. If it hasn't been
283 # given and the incomplete arg looks like an option, the current
284 # command will provide option name completions.
285 if "--" not in args and _start_of_option(ctx, incomplete): 1adefbghcij
286 return ctx.command, incomplete 1adefbghcij
288 params = ctx.command.get_params(ctx) 1adefbghcij
290 # If the last complete arg is an option name with an incomplete
291 # value, the option will provide value completions.
292 for param in params: 1adefbghcij
293 if _is_incomplete_option(ctx, args, param): 1adefbghcij
294 return param, incomplete 1adefbghcij
296 # It's not an option name or value. The first argument without a
297 # parsed value will provide value completions.
298 for param in params: 1adefbghcij
299 if _is_incomplete_argument(ctx, param): 1adefbghcij
300 return param, incomplete 1adefbghcij
302 # There were no unparsed arguments, the command may be a group that
303 # will provide command name completions.
304 return ctx.command, incomplete 1adefbghcij