cli: Add the generic completer function and validator function

The patch adds the generic completer and validator, Further patches use
them as completer/validator. The completer won't add already specified
options to the list.

Signed-off-by: Lin Ma <lma@suse.com>
This commit is contained in:
Lin Ma 2018-12-07 16:28:48 +08:00 committed by Cole Robinson
parent a8d4c7cb79
commit d68f0f8867
2 changed files with 40 additions and 0 deletions

View File

@ -35,6 +35,7 @@ Minimum version requirements of major components:
- libvirt-python >= 0.6.0
- pygobject3 >= 3.14
- libosinfo >= 0.2.10
- python3-argcomplete >= 1.0.0
On Debian or Ubuntu based distributions, you need to install the
`gobject-introspection` bindings for some dependencies like `libvirt-glib`

View File

@ -18,6 +18,7 @@ import subprocess
import sys
import traceback
import argcomplete
import libvirt
from virtcli import CLIConfig
@ -454,6 +455,44 @@ def get_meter():
return util.make_meter(quiet=quiet)
###########################
# bash completion helpers #
###########################
def _completer(prefix, **kwargs):
sub_options = []
for parserclass in VIRT_PARSERS:
if kwargs['action'].dest == parserclass.cli_arg_name:
# pylint: disable=protected-access
for arg in sorted(parserclass._virtargs, key=lambda p: p.cliname):
sub_options.append(arg.cliname + "=")
entered_options = prefix.split(",")
for option in entered_options:
pos = option.find("=")
if pos > 0 and option[: pos + 1] in sub_options:
sub_options.remove(option[: pos + 1])
return sub_options
def _completer_validator(current_input, keyword_to_check_against):
entered_options = keyword_to_check_against.split(",")
# e.g. for: --disk <TAB><TAB>
if keyword_to_check_against == "":
return True
# e.g. for: --disk bu<TAB><TAB> or --disk bus=ide,<TAB><TAB>
# or --disk bus=ide,pa<TAB><TAB>
if (len(entered_options) >= 1 and "=" not in entered_options[-1]):
if entered_options[-1] == "":
return True
else:
return current_input.startswith(entered_options[-1])
def autocomplete(parser):
argcomplete.autocomplete(parser, validator=_completer_validator)
###########################
# Common CLI option/group #
###########################