Debian Codegraph @

src/asyncclick/shell_completion.py

raw
1 from __future__ import annotations
2
3 import collections.abc as cabc
4 import os
5 import re
6 import typing as t
7 from gettext import gettext as _
8
9 from .core import Argument
10 from .core import Command
11 from .core import Context
12 from .core import Group
13 from .core import Option
14 from .core import Parameter
15 from .core import ParameterSource
16 from .utils import echo
17
18
19 async def shell_complete(
20 cli: Command,
21 ctx_args: cabc.MutableMapping[str, t.Any],
22 prog_name: str,
23 complete_var: str,
24 instruction: str,
25 ) -> int:
26 """Perform shell completion for the given CLI program.
27
28 :param cli: Command being called.
29 :param ctx_args: Extra arguments to pass to
30 ``cli.make_context``.
31 :param prog_name: Name of the executable in the shell.
32 :param complete_var: Name of the environment variable that holds
33 the completion instruction.
34 :param instruction: Value of ``complete_var`` with the completion
35 instruction and shell, in the form ``instruction_shell``.
36 :return: Status code to exit with.
37 """
38 shell, _, instruction = instruction.partition("_")
39 comp_cls = get_completion_class(shell)
40
41 if comp_cls is None:
42 return 1
43
44 comp = comp_cls(cli, ctx_args, prog_name, complete_var)
45
46 if instruction == "source":
47 echo(comp.source())
48 return 0
49
50 if instruction == "complete":
51 echo(await comp.complete())
52 return 0
53
54 return 1
55
56
57 class CompletionItem:
58 """Represents a completion value and metadata about the value. The
59 default metadata is ``type`` to indicate special shell handling,
60 and ``help`` if a shell supports showing a help string next to the
61 value.
62
63 Arbitrary parameters can be passed when creating the object, and
64 accessed using ``item.attr``. If an attribute wasn't passed,
65 accessing it returns ``None``.
66
67 :param value: The completion suggestion.
68 :param type: Tells the shell script to provide special completion
69 support for the type. Click uses ``"dir"`` and ``"file"``.
70 :param help: String shown next to the value if supported.
71 :param kwargs: Arbitrary metadata. The built-in implementations
72 don't use this, but custom type completions paired with custom
73 shell support could use it.
74 """
75
76 __slots__ = ("value", "type", "help", "_info")
77
78 def __init__(
79 self,
80 value: t.Any,
81 type: str = "plain",
82 help: str | None = None,
83 **kwargs: t.Any,
84 ) -> None:
85 self.value: t.Any = value
86 self.type: str = type
87 self.help: str | None = help
88 self._info = kwargs
89
90 def __getattr__(self, name: str) -> t.Any:
91 return self._info.get(name)
92
93
94 # Only Bash >= 4.4 has the nosort option.
95 _SOURCE_BASH = """\
96 %(complete_func)s() {
97 local IFS=$'\\n'
98 local response
99
100 response=$(env COMP_WORDS="${COMP_WORDS[*]}" COMP_CWORD=$COMP_CWORD \
101 %(complete_var)s=bash_complete $1)
102
103 for completion in $response; do
104 IFS=',' read type value <<< "$completion"
105
106 if [[ $type == 'dir' ]]; then
107 COMPREPLY=()
108 compopt -o dirnames
109 elif [[ $type == 'file' ]]; then
110 COMPREPLY=()
111 compopt -o default
112 elif [[ $type == 'plain' ]]; then
113 COMPREPLY+=($value)
114 fi
115 done
116
117 return 0
118 }
119
120 %(complete_func)s_setup() {
121 complete -o nosort -F %(complete_func)s %(prog_name)s
122 }
123
124 %(complete_func)s_setup;
125 """
126
127 # See ZshComplete.format_completion below, and issue #2703, before
128 # changing this script.
129 #
130 # (TL;DR: _describe is picky about the format, but this Zsh script snippet
131 # is already widely deployed. So freeze this script, and use clever-ish
132 # handling of colons in ZshComplet.format_completion.)
133 _SOURCE_ZSH = """\
134 #compdef %(prog_name)s
135
136 %(complete_func)s() {
137 local -a completions
138 local -a completions_with_descriptions
139 local -a response
140 (( ! $+commands[%(prog_name)s] )) && return 1
141
142 response=("${(@f)$(env COMP_WORDS="${words[*]}" COMP_CWORD=$((CURRENT-1)) \
143 %(complete_var)s=zsh_complete %(prog_name)s)}")
144
145 for type key descr in ${response}; do
146 if [[ "$type" == "plain" ]]; then
147 if [[ "$descr" == "_" ]]; then
148 completions+=("$key")
149 else
150 completions_with_descriptions+=("$key":"$descr")
151 fi
152 elif [[ "$type" == "dir" ]]; then
153 _path_files -/
154 elif [[ "$type" == "file" ]]; then
155 _path_files -f
156 fi
157 done
158
159 if [ -n "$completions_with_descriptions" ]; then
160 _describe -V unsorted completions_with_descriptions -U
161 fi
162
163 if [ -n "$completions" ]; then
164 compadd -U -V unsorted -a completions
165 fi
166 }
167
168 if [[ $zsh_eval_context[-1] == loadautofunc ]]; then
169 # autoload from fpath, call function directly
170 %(complete_func)s "$@"
171 else
172 # eval/source/. command, register function for later
173 compdef %(complete_func)s %(prog_name)s
174 fi
175 """
176
177 _SOURCE_FISH = """\
178 function %(complete_func)s;
179 set -l response (env %(complete_var)s=fish_complete COMP_WORDS=(commandline -cp) \
180 COMP_CWORD=(commandline -t) %(prog_name)s);
181
182 for completion in $response;
183 set -l metadata (string split "," $completion);
184
185 if test $metadata[1] = "dir";
186 __fish_complete_directories $metadata[2];
187 else if test $metadata[1] = "file";
188 __fish_complete_path $metadata[2];
189 else if test $metadata[1] = "plain";
190 echo $metadata[2];
191 end;
192 end;
193 end;
194
195 complete --no-files --command %(prog_name)s --arguments \
196 "(%(complete_func)s)";
197 """
198
199
200 class ShellComplete:
201 """Base class for providing shell completion support. A subclass for
202 a given shell will override attributes and methods to implement the
203 completion instructions (``source`` and ``complete``).
204
205 :param cli: Command being called.
206 :param prog_name: Name of the executable in the shell.
207 :param complete_var: Name of the environment variable that holds
208 the completion instruction.
209
210 .. versionadded:: 8.0
211 """
212
213 name: t.ClassVar[str]
214 """Name to register the shell as with :func:`add_completion_class`.
215 This is used in completion instructions (``{name}_source`` and
216 ``{name}_complete``).
217 """
218
219 source_template: t.ClassVar[str]
220 """Completion script template formatted by :meth:`source`. This must
221 be provided by subclasses.
222 """
223
224 def __init__(
225 self,
226 cli: Command,
227 ctx_args: cabc.MutableMapping[str, t.Any],
228 prog_name: str,
229 complete_var: str,
230 ) -> None:
231 self.cli = cli
232 self.ctx_args = ctx_args
233 self.prog_name = prog_name
234 self.complete_var = complete_var
235
236 @property
237 def func_name(self) -> str:
238 """The name of the shell function defined by the completion
239 script.
240 """
241 safe_name = re.sub(r"\W*", "", self.prog_name.replace("-", "_"), flags=re.ASCII)
242 return f"_{safe_name}_completion"
243
244 def source_vars(self) -> dict[str, t.Any]:
245 """Vars for formatting :attr:`source_template`.
246
247 By default this provides ``complete_func``, ``complete_var``,
248 and ``prog_name``.
249 """
250 return {
251 "complete_func": self.func_name,
252 "complete_var": self.complete_var,
253 "prog_name": self.prog_name,
254 }
255
256 def source(self) -> str:
257 """Produce the shell script that defines the completion
258 function. By default this ``%``-style formats
259 :attr:`source_template` with the dict returned by
260 :meth:`source_vars`.
261 """
262 return self.source_template % self.source_vars()
263
264 def get_completion_args(self) -> tuple[list[str], str]:
265 """Use the env vars defined by the shell script to return a
266 tuple of ``args, incomplete``. This must be implemented by
267 subclasses.
268 """
269 raise NotImplementedError
270
271 async def get_completions(
272 self, args: list[str], incomplete: str
273 ) -> list[CompletionItem]:
274 """Determine the context and last complete command or parameter
275 from the complete args. Call that object's ``shell_complete``
276 method to get the completions for the incomplete value.
277
278 :param args: List of complete args before the incomplete value.
279 :param incomplete: Value being completed. May be empty.
280 """
281 ctx = await _resolve_context(self.cli, self.ctx_args, self.prog_name, args)
282 obj, incomplete = _resolve_incomplete(ctx, args, incomplete)
283 return obj.shell_complete(ctx, incomplete)
284
285 def format_completion(self, item: CompletionItem) -> str:
286 """Format a completion item into the form recognized by the
287 shell script. This must be implemented by subclasses.
288
289 :param item: Completion item to format.
290 """
291 raise NotImplementedError
292
293 async def complete(self) -> str:
294 """Produce the completion data to send back to the shell.
295
296 By default this calls :meth:`get_completion_args`, gets the
297 completions, then calls :meth:`format_completion` for each
298 completion.
299 """
300 args, incomplete = self.get_completion_args()
301 completions = await self.get_completions(args, incomplete)
302 out = [self.format_completion(item) for item in completions]
303 return "\n".join(out)
304
305
306 class BashComplete(ShellComplete):
307 """Shell completion for Bash."""
308
309 name = "bash"
310 source_template = _SOURCE_BASH
311
312 @staticmethod
313 def _check_version() -> None:
314 import shutil
315 import subprocess
316
317 bash_exe = shutil.which("bash")
318
319 if bash_exe is None:
320 match = None
321 else:
322 output = subprocess.run(
323 [bash_exe, "--norc", "-c", 'echo "${BASH_VERSION}"'],
324 stdout=subprocess.PIPE,
325 )
326 match = re.search(r"^(\d+)\.(\d+)\.\d+", output.stdout.decode())
327
328 if match is not None:
329 major, minor = match.groups()
330
331 if major < "4" or major == "4" and minor < "4":
332 echo(
333 _(
334 "Shell completion is not supported for Bash"
335 " versions older than 4.4."
336 ),
337 err=True,
338 )
339 else:
340 echo(
341 _("Couldn't detect Bash version, shell completion is not supported."),
342 err=True,
343 )
344
345 def source(self) -> str:
346 self._check_version()
347 return super().source()
348
349 def get_completion_args(self) -> tuple[list[str], str]:
350 cwords = split_arg_string(os.environ["COMP_WORDS"])
351 cword = int(os.environ["COMP_CWORD"])
352 args = cwords[1:cword]
353
354 try:
355 incomplete = cwords[cword]
356 except IndexError:
357 incomplete = ""
358
359 return args, incomplete
360
361 def format_completion(self, item: CompletionItem) -> str:
362 return f"{item.type},{item.value}"
363
364
365 class ZshComplete(ShellComplete):
366 """Shell completion for Zsh."""
367
368 name = "zsh"
369 source_template = _SOURCE_ZSH
370
371 def get_completion_args(self) -> tuple[list[str], str]:
372 cwords = split_arg_string(os.environ["COMP_WORDS"])
373 cword = int(os.environ["COMP_CWORD"])
374 args = cwords[1:cword]
375
376 try:
377 incomplete = cwords[cword]
378 except IndexError:
379 incomplete = ""
380
381 return args, incomplete
382
383 def format_completion(self, item: CompletionItem) -> str:
384 help_ = item.help or "_"
385 # The zsh completion script uses `_describe` on items with help
386 # texts (which splits the item help from the item value at the
387 # first unescaped colon) and `compadd` on items without help
388 # text (which uses the item value as-is and does not support
389 # colon escaping). So escape colons in the item value if and
390 # only if the item help is not the sentinel "_" value, as used
391 # by the completion script.
392 #
393 # (The zsh completion script is potentially widely deployed, and
394 # thus harder to fix than this method.)
395 #
396 # See issue #1812 and issue #2703 for further context.
397 value = item.value.replace(":", r"\:") if help_ != "_" else item.value
398 return f"{item.type}\n{value}\n{help_}"
399
400
401 class FishComplete(ShellComplete):
402 """Shell completion for Fish."""
403
404 name = "fish"
405 source_template = _SOURCE_FISH
406
407 def get_completion_args(self) -> tuple[list[str], str]:
408 cwords = split_arg_string(os.environ["COMP_WORDS"])
409 incomplete = os.environ["COMP_CWORD"]
410 if incomplete:
411 incomplete = split_arg_string(incomplete)[0]
412 args = cwords[1:]
413
414 # Fish stores the partial word in both COMP_WORDS and
415 # COMP_CWORD, remove it from complete args.
416 if incomplete and args and args[-1] == incomplete:
417 args.pop()
418
419 return args, incomplete
420
421 def format_completion(self, item: CompletionItem) -> str:
422 if item.help:
423 return f"{item.type},{item.value}\t{item.help}"
424
425 return f"{item.type},{item.value}"
426
427
428 ShellCompleteType = t.TypeVar("ShellCompleteType", bound="type[ShellComplete]")
429
430
431 _available_shells: dict[str, type[ShellComplete]] = {
432 "bash": BashComplete,
433 "fish": FishComplete,
434 "zsh": ZshComplete,
435 }
436
437
438 def add_completion_class(
439 cls: ShellCompleteType, name: str | None = None
440 ) -> ShellCompleteType:
441 """Register a :class:`ShellComplete` subclass under the given name.
442 The name will be provided by the completion instruction environment
443 variable during completion.
444
445 :param cls: The completion class that will handle completion for the
446 shell.
447 :param name: Name to register the class under. Defaults to the
448 class's ``name`` attribute.
449 """
450 if name is None:
451 name = cls.name
452
453 _available_shells[name] = cls
454
455 return cls
456
457
458 def get_completion_class(shell: str) -> type[ShellComplete] | None:
459 """Look up a registered :class:`ShellComplete` subclass by the name
460 provided by the completion instruction environment variable. If the
461 name isn't registered, returns ``None``.
462
463 :param shell: Name the class is registered under.
464 """
465 return _available_shells.get(shell)
466
467
468 def split_arg_string(string: str) -> list[str]:
469 """Split an argument string as with :func:`shlex.split`, but don't
470 fail if the string is incomplete. Ignores a missing closing quote or
471 incomplete escape sequence and uses the partial token as-is.
472
473 .. code-block:: python
474
475 split_arg_string("example 'my file")
476 ["example", "my file"]
477
478 split_arg_string("example my\\")
479 ["example", "my"]
480
481 :param string: String to split.
482
483 .. versionchanged:: 8.2
484 Moved to ``shell_completion`` from ``parser``.
485 """
486 import shlex
487
488 lex = shlex.shlex(string, posix=True)
489 lex.whitespace_split = True
490 lex.commenters = ""
491 out = []
492
493 try:
494 for token in lex:
495 out.append(token)
496 except ValueError:
497 # Raised when end-of-string is reached in an invalid state. Use
498 # the partial token as-is. The quote or escape character is in
499 # lex.state, not lex.token.
500 out.append(lex.token)
501
502 return out
503
504
505 def _is_incomplete_argument(ctx: Context, param: Parameter) -> bool:
506 """Determine if the given parameter is an argument that can still
507 accept values.
508
509 :param ctx: Invocation context for the command represented by the
510 parsed complete args.
511 :param param: Argument object being checked.
512 """
513 if not isinstance(param, Argument):
514 return False
515
516 assert param.name is not None
517 # Will be None if expose_value is False.
518 value = ctx.params.get(param.name)
519 return (
520 param.nargs == -1
521 or ctx.get_parameter_source(param.name) is not ParameterSource.COMMANDLINE
522 or (
523 param.nargs > 1
524 and isinstance(value, (tuple, list))
525 and len(value) < param.nargs
526 )
527 )
528
529
530 def _start_of_option(ctx: Context, value: str) -> bool:
531 """Check if the value looks like the start of an option."""
532 if not value:
533 return False
534
535 c = value[0]
536 return c in ctx._opt_prefixes
537
538
539 def _is_incomplete_option(ctx: Context, args: list[str], param: Parameter) -> bool:
540 """Determine if the given parameter is an option that needs a value.
541
542 :param args: List of complete args before the incomplete value.
543 :param param: Option object being checked.
544 """
545 if not isinstance(param, Option):
546 return False
547
548 if param.is_flag or param.count:
549 return False
550
551 last_option = None
552
553 for index, arg in enumerate(reversed(args)):
554 if index + 1 > param.nargs:
555 break
556
557 if _start_of_option(ctx, arg):
558 last_option = arg
559 break
560
561 return last_option is not None and last_option in param.opts
562
563
564 async def _resolve_context(
565 cli: Command,
566 ctx_args: cabc.MutableMapping[str, t.Any],
567 prog_name: str,
568 args: list[str],
569 ) -> Context:
570 """Produce the context hierarchy starting with the command and
571 traversing the complete arguments. This only follows the commands,
572 it doesn't trigger input prompts or callbacks.
573
574 :param cli: Command being called.
575 :param prog_name: Name of the executable in the shell.
576 :param args: List of complete args before the incomplete value.
577 """
578 ctx_args["resilient_parsing"] = True
579 async with await cli.make_context(prog_name, args.copy(), **ctx_args) as ctx:
580 args = ctx._protected_args + ctx.args
581
582 while args:
583 command = ctx.command
584
585 if isinstance(command, Group):
586 if not command.chain:
587 name, cmd, args = await command.resolve_command(ctx, args)
588
589 if cmd is None:
590 return ctx
591
592 async with await cmd.make_context(
593 name, args, parent=ctx, resilient_parsing=True
594 ) as sub_ctx:
595 ctx = sub_ctx
596 args = ctx._protected_args + ctx.args
597 else:
598 sub_ctx = ctx
599
600 while args:
601 name, cmd, args = await command.resolve_command(ctx, args)
602
603 if cmd is None:
604 return ctx
605
606 async with await cmd.make_context(
607 name,
608 args,
609 parent=ctx,
610 allow_extra_args=True,
611 allow_interspersed_args=False,
612 resilient_parsing=True,
613 ) as sub_sub_ctx:
614 sub_ctx = sub_sub_ctx
615 args = sub_ctx.args
616
617 ctx = sub_ctx
618 args = [*sub_ctx._protected_args, *sub_ctx.args]
619 else:
620 break
621
622 return ctx
623
624
625 def _resolve_incomplete(
626 ctx: Context, args: list[str], incomplete: str
627 ) -> tuple[Command | Parameter, str]:
628 """Find the Click object that will handle the completion of the
629 incomplete value. Return the object and the incomplete value.
630
631 :param ctx: Invocation context for the command represented by
632 the parsed complete args.
633 :param args: List of complete args before the incomplete value.
634 :param incomplete: Value being completed. May be empty.
635 """
636 # Different shells treat an "=" between a long option name and
637 # value differently. Might keep the value joined, return the "="
638 # as a separate item, or return the split name and value. Always
639 # split and discard the "=" to make completion easier.
640 if incomplete == "=":
641 incomplete = ""
642 elif "=" in incomplete and _start_of_option(ctx, incomplete):
643 name, _, incomplete = incomplete.partition("=")
644 args.append(name)
645
646 # The "--" marker tells Click to stop treating values as options
647 # even if they start with the option character. If it hasn't been
648 # given and the incomplete arg looks like an option, the current
649 # command will provide option name completions.
650 if "--" not in args and _start_of_option(ctx, incomplete):
651 return ctx.command, incomplete
652
653 params = ctx.command.get_params(ctx)
654
655 # If the last complete arg is an option name with an incomplete
656 # value, the option will provide value completions.
657 for param in params:
658 if _is_incomplete_option(ctx, args, param):
659 return param, incomplete
660
661 # It's not an option name or value. The first argument without a
662 # parsed value will provide value completions.
663 for param in params:
664 if _is_incomplete_argument(ctx, param):
665 return param, incomplete
666
667 # There were no unparsed arguments, the command may be a group that
668 # will provide command name completions.
669 return ctx.command, incomplete