File: completer.py

package info (click to toggle)
python-softlayer 6.2.5-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 7,508 kB
  • sloc: python: 57,195; makefile: 133; xml: 97; sh: 59
file content (74 lines) | stat: -rw-r--r-- 2,306 bytes parent folder | download | duplicates (3)
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
"""
    SoftLayer.CLI.shell.completer
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Click completer for prompt_toolkit

    :license: MIT, see LICENSE for more details.
"""
import itertools
import shlex

import click
from prompt_toolkit import completion as completion


class ShellCompleter(completion.Completer):
    """Completer for the shell."""

    def __init__(self, click_root):
        self.root = click_root

    def get_completions(self, document, complete_event):
        """Returns an iterator of completions for the shell."""

        return _click_autocomplete(self.root, document.text_before_cursor)


def _click_autocomplete(root, text):
    """Completer generator for click applications."""
    try:
        parts = shlex.split(text)
    except ValueError:
        return

    location, incomplete = _click_resolve_command(root, parts)

    if not text.endswith(' ') and not incomplete and text:
        return

    if incomplete and not incomplete[0:2].isalnum():
        for param in location.params:
            if not isinstance(param, click.Option):
                continue
            for opt in itertools.chain(param.opts, param.secondary_opts):
                if opt.startswith(incomplete):
                    yield completion.Completion(opt, -len(incomplete), display_meta=param.help)

    elif isinstance(location, (click.MultiCommand, click.core.Group)):
        ctx = click.Context(location)
        commands = location.list_commands(ctx)
        for command in commands:
            if command.startswith(incomplete):
                cmd = location.get_command(ctx, command)
                yield completion.Completion(command, -len(incomplete), display_meta=cmd.short_help)


def _click_resolve_command(root, parts):
    """Return the click command and the left over text given some vargs."""
    location = root
    incomplete = ''
    for part in parts:
        incomplete = part

        if not part[0:2].isalnum():
            continue

        try:
            next_location = location.get_command(click.Context(location),
                                                 part)
            if next_location is not None:
                location = next_location
                incomplete = ''
        except AttributeError:
            break
    return location, incomplete