automatically add list completer to argparse with a "choices" kw

This commit is contained in:
n1nj4sec 2015-10-11 16:48:00 +02:00
parent 7dd24fcc6f
commit 20092be17b
2 changed files with 6 additions and 5 deletions

View File

@ -26,7 +26,8 @@ def debug(msg):
def list_completer(l):
def func(text, line, begidx, endidx):
return [x for x in l if text.startswith(x)]
return [x+" " for x in l if x.startswith(text)]
return func
def void_completer(text, line, begidx, endidx):
return []
@ -100,7 +101,6 @@ class PupyModCompleter(object):
def __init__(self):
self.conf= {
"positional_args":[
#TODO
],
"optional_args":[
],
@ -140,7 +140,6 @@ class PupyModCompleter(object):
return None
def get_positional_arg_index(self, text, line, begidx, endidx):
#TODO
tab=shlex.split(line)
positional_index=-1
for i in range(0, len(tab)):
@ -157,6 +156,7 @@ class PupyModCompleter(object):
def get_optional_args_completer(self, name):
return [x[1]["completer"] for x in self.conf["optional_args"] if x[0]==name][0]
def get_positional_args_completer(self, index):
return self.conf["positional_args"][index][1]["completer"]
@ -171,7 +171,6 @@ class PupyModCompleter(object):
return [x+" " for x in self.get_optional_args() if x.startswith(text)]
else:
try:
debug("here")
positional_index=self.get_positional_arg_index(text, line, begidx, endidx)-2 # -2 for "run" + "module_name"
debug("positional index is %s"%positional_index)
return self.get_positional_args_completer(positional_index)(text, line, begidx, endidx)

View File

@ -16,7 +16,7 @@
import argparse
import sys
from .PupyErrors import PupyModuleExit
from .PupyCompleter import PupyModCompleter, void_completer
from .PupyCompleter import PupyModCompleter, void_completer, list_completer
import StringIO
class PupyArgumentParser(argparse.ArgumentParser):
@ -30,6 +30,8 @@ class PupyArgumentParser(argparse.ArgumentParser):
if "completer" in kwargs:
completer_func=kwargs["completer"]
del kwargs["completer"]
elif "choices" in kwargs:
completer_func=list_completer(kwargs["choices"])
else:
completer_func=void_completer
argparse.ArgumentParser.add_argument(self, *args, **kwargs)