File: completer.py

package info (click to toggle)
zabbix-cli 3.5.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,860 kB
  • sloc: python: 18,557; makefile: 3
file content (375 lines) | stat: -rw-r--r-- 12,761 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
"""Completer functionality for Click commands in the REPL."""

from __future__ import annotations

import os
import shlex
from collections.abc import Generator
from glob import iglob
from typing import Any
from typing import Optional

import click
from prompt_toolkit.completion import CompleteEvent
from prompt_toolkit.completion import Completer
from prompt_toolkit.completion import Completion
from prompt_toolkit.document import Document

from zabbix_cli.commands.common.args import CommandParam

__all__ = ["ClickCompleter"]

IS_WINDOWS = os.name == "nt"


AUTO_COMPLETION_PARAM = "shell_complete"


def split_arg_string(string: str, *, posix: bool = True) -> list[str]:
    r"""Split an argument in a shlex-like way, but don't fail if the string is incomplete.

    Args:
        string (str): String to split
        posix (bool, optional): Posix-like parsing. Defaults to True.

    Returns:
        list[str]: String split into tokens.

    Examples:
        >>> split_arg_string("example 'my file")
        ["example", "my file"]
        >>> split_arg_string("example my\\")
        ["example", "my"]
    """
    lex = shlex.shlex(string, posix=posix)
    lex.whitespace_split = True
    lex.commenters = ""
    out: list[str] = []

    try:
        for token in lex:
            out.append(token)
    except ValueError:
        # Raised when end-of-string is reached in an invalid state. Use
        # the partial token as-is. The quote or escape character is in
        # lex.state, not lex.token.
        out.append(lex.token)

    return out


def _resolve_context(args: list[Any], ctx: click.Context) -> click.Context:
    """Resolve context and return the last context in the chain.

    Produce the context hierarchy starting with the command and
    traversing the complete arguments. This only follows the commands,
    it doesn't trigger input prompts or callbacks.


    Args:
        args (list[Any]): List of complete args before the incomplete value.
        ctx (click.Context): `click.Context` object of the CLI group

    Returns:
        click.Context: Resolved context.
    """
    while args:
        command = ctx.command

        if isinstance(command, click.MultiCommand):
            if not command.chain:
                name, cmd, args = command.resolve_command(ctx, args)

                if cmd is None:
                    return ctx

                ctx = cmd.make_context(name, args, parent=ctx, resilient_parsing=True)
                args = ctx.protected_args + ctx.args
            else:
                sub_ctx = ctx
                while args:
                    name, cmd, args = command.resolve_command(ctx, args)

                    if cmd is None:
                        return ctx

                    sub_ctx = cmd.make_context(
                        name,
                        args,
                        parent=ctx,
                        allow_extra_args=True,
                        allow_interspersed_args=False,
                        resilient_parsing=True,
                    )
                    args = sub_ctx.args
                ctx = sub_ctx
                args = [*sub_ctx.protected_args, *sub_ctx.args]
        else:
            break

    return ctx


class ClickCompleter(Completer):
    """Completer for Click commands."""

    __slots__ = ("cli", "ctx", "parsed_args", "parsed_ctx", "ctx_command")

    def __init__(
        self,
        cli: click.Group,
        ctx: click.Context,
        *,
        show_only_unused: bool = False,
        shortest_only: bool = False,
    ) -> None:
        self.cli = cli
        self.ctx = ctx
        self.parsed_args = []
        self.parsed_ctx = ctx
        self.ctx_command = ctx.command
        self.show_only_unused = show_only_unused
        self.shortest_only = shortest_only

    def _get_completion_from_autocompletion_functions(
        self,
        param: click.Parameter,
        autocomplete_ctx: click.Context,
        args: list[str],
        incomplete: str,
    ):
        param_choices: list[Completion] = []
        autocompletions = param.shell_complete(autocomplete_ctx, incomplete)
        for autocomplete in autocompletions:
            param_choices.append(Completion(str(autocomplete.value), -len(incomplete)))
        return param_choices

    def _get_completion_for_Path_types(
        self, param: click.Parameter, args: list[str], incomplete: str
    ) -> list[Completion]:
        if "*" in incomplete:
            return []

        choices: list[Completion] = []
        _incomplete = os.path.expandvars(incomplete)
        search_pattern = _incomplete.strip("'\"\t\n\r\v ").replace("\\\\", "\\") + "*"
        quote = ""

        if " " in _incomplete:
            for i in incomplete:
                if i in ("'", '"'):
                    quote = i
                    break

        for path in iglob(search_pattern):
            if " " in path:
                if quote:
                    path = quote + path
                else:
                    if IS_WINDOWS:
                        path = repr(path).replace("\\\\", "\\")
            else:
                if IS_WINDOWS:
                    path = path.replace("\\", "\\\\")

            choices.append(
                Completion(
                    str(path),
                    -len(incomplete),
                    display=str(os.path.basename(path.strip("'\""))),
                )
            )

        return choices

    def _get_completion_for_Boolean_type(self, param: click.Parameter, incomplete: str):
        return [
            Completion(str(k), -len(incomplete), display_meta=str("/".join(v)))
            for k, v in {
                "true": ("1", "true", "t", "yes", "y", "on"),
                "false": ("0", "false", "f", "no", "n", "off"),
            }.items()
            if any(i.startswith(incomplete) for i in v)
        ]

    def _get_completion_from_command_param(
        self, param: click.Parameter, incomplete: str
    ) -> list[Completion]:
        return [
            Completion(command, -len(incomplete))
            for command in self.cli.list_commands(self.parsed_ctx)
            if command.startswith(incomplete)
        ]

    def _get_completion_from_params(
        self,
        autocomplete_ctx: click.Context,
        args: list[str],
        param: click.Parameter,
        incomplete: str,
    ) -> list[Completion]:
        choices: list[Completion] = []
        if isinstance(param.type, click.types.BoolParamType):
            # Only suggest completion if parameter is not a flag
            if isinstance(param, click.Option) and not param.is_flag:
                choices.extend(self._get_completion_for_Boolean_type(param, incomplete))
        elif isinstance(param.type, (click.Path, click.File)):
            choices.extend(self._get_completion_for_Path_types(param, args, incomplete))
        elif isinstance(param.type, CommandParam):
            choices.extend(self._get_completion_from_command_param(param, incomplete))
        elif getattr(param, AUTO_COMPLETION_PARAM, None) is not None:
            choices.extend(
                self._get_completion_from_autocompletion_functions(
                    param,
                    autocomplete_ctx,
                    args,
                    incomplete,
                )
            )

        return choices

    def _get_completion_for_cmd_args(
        self,
        ctx_command: click.Command,
        incomplete: str,
        autocomplete_ctx: click.Context,
        args: list[str],
    ) -> list[Completion]:
        choices: list[Completion] = []
        param_called = False

        for param in ctx_command.params:
            if isinstance(param.type, click.types.UnprocessedParamType):
                return []

            elif getattr(param, "hidden", False):
                continue

            elif isinstance(param, click.Option):
                opts = param.opts + param.secondary_opts
                previous_args = args[: param.nargs * -1]
                current_args = args[param.nargs * -1 :]

                # Show only unused opts
                already_present = any(opt in previous_args for opt in opts)
                hide = self.show_only_unused and already_present and not param.multiple

                # Show only shortest opt
                if (
                    self.shortest_only
                    and not incomplete  # just typed a space
                    # not selecting a value for a longer version of this option
                    and args[-1] not in opts
                ):
                    opts = [min(opts, key=len)]

                for option in opts:
                    # We want to make sure if this parameter was called
                    # If we are inside a parameter that was called, we want to show only
                    # relevant choices
                    if option in current_args:  # noqa: E203
                        param_called = True
                        break

                    elif option.startswith(incomplete) and not hide:
                        choices.append(
                            Completion(
                                str(option),
                                -len(incomplete),
                                display_meta=str(param.help or ""),
                            )
                        )

                if param_called:
                    choices = self._get_completion_from_params(
                        autocomplete_ctx, args, param, incomplete
                    )
                    break

            elif isinstance(param, click.Argument):
                choices.extend(
                    self._get_completion_from_params(
                        autocomplete_ctx, args, param, incomplete
                    )
                )

        return choices

    def get_completions(
        self, document: Document, complete_event: Optional[CompleteEvent] = None
    ) -> Generator[Completion, Any, None]:
        """Generator of completions for the current input.

        Args:
            document (Document): Current prompt_toolkit document.
            complete_event (Optional[CompleteEvent], optional): Event that triggered the completion. Defaults to None.

        Yields:
            Generator[Completion, Any, None]: Completions for the current input.
        """
        # Code analogous to click._bashcomplete.do_complete

        args = split_arg_string(document.text_before_cursor, posix=False)

        choices: list[Completion] = []
        cursor_within_command = (
            document.text_before_cursor.rstrip() == document.text_before_cursor
        )

        if document.text_before_cursor.startswith(("!", ":")):
            return

        if args and cursor_within_command:
            # We've entered some text and no space, give completions for the
            # current word.
            incomplete = args.pop()
        else:
            # We've not entered anything, either at all or for the current
            # command, so give all relevant completions for this context.
            incomplete = ""

        if self.parsed_args != args:
            self.parsed_args = args
            try:
                self.parsed_ctx = _resolve_context(args, self.ctx)
            except Exception:
                return  # autocompletion for nonexistent cmd can throw here
            self.ctx_command = self.parsed_ctx.command

        if getattr(self.ctx_command, "hidden", False):
            return

        try:
            choices.extend(
                self._get_completion_for_cmd_args(
                    self.ctx_command, incomplete, self.parsed_ctx, args
                )
            )

            if isinstance(self.ctx_command, click.MultiCommand):
                incomplete_lower = incomplete.lower()

                for name in self.ctx_command.list_commands(self.parsed_ctx):
                    command = self.ctx_command.get_command(self.parsed_ctx, name)
                    if getattr(command, "hidden", False):
                        continue

                    elif name.lower().startswith(incomplete_lower):
                        choices.append(
                            Completion(
                                str(name),
                                -len(incomplete),
                                display_meta=getattr(command, "short_help", ""),
                            )
                        )

        except Exception as e:
            click.echo(f"{type(e).__name__}: {str(e)}")

        # If we are inside a parameter that was called, we want to show only
        # relevant choices
        # if param_called:
        #     choices = param_choices

        yield from choices