[virt-tools-list] [virt-manager] [PATCH v2 02/10] cli: Add the generic completer function and validator function

Lin Ma lma at suse.com
Fri Dec 7 08:28:48 UTC 2018


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 at suse.com>
---
 virtinst/cli.py | 46 ++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 46 insertions(+)

diff --git a/virtinst/cli.py b/virtinst/cli.py
index 21467a4d..95e54efc 100644
--- a/virtinst/cli.py
+++ b/virtinst/cli.py
@@ -8,6 +8,7 @@
 # See the COPYING file in the top-level directory.
 
 import argparse
+import argcomplete
 import collections
 import logging
 import logging.handlers
@@ -454,6 +455,51 @@ def get_meter():
     return util.make_meter(quiet=quiet)
 
 
+###########################
+# Common Completer        #
+###########################
+
+def completer(prefix, **kwargs):
+    sub_options = []
+    for parserclass in VIRT_PARSERS:
+        if kwargs['action'].dest == parserclass.cli_arg_name:
+            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
+
+
+###########################
+# Common Validator        #
+###########################
+
+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])
+
+
+############################
+# Wrapper for autocomplete #
+############################
+
+def autocomplete(parser):
+    argcomplete.autocomplete(parser, validator=completer_validator)
+
+
 ###########################
 # Common CLI option/group #
 ###########################
-- 
2.16.2




More information about the virt-tools-list mailing list