Skip to content

Instantly share code, notes, and snippets.

@gallir
Last active October 25, 2015 10:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gallir/16dc5ca7ec92be4c7998 to your computer and use it in GitHub Desktop.
Save gallir/16dc5ca7ec92be4c7998 to your computer and use it in GitHub Desktop.
A top-down recursive very simple parser
TREE = {
'proxy': {
'': proxy_list,
'list': (proxy_list, ("username", False)),
'info': (proxy_info, ("proxy_name", True)),
},
'auth': {
'': auth_info,
'info': (auth_info, ("token", False)),
'login': (auth_login, ("username", False)),
'logout': auth_logout,
},
'server': {
'': server_url,
'list': [server_url, {"listing": True}],
'set': (server_url, ("url", True)),
'add': (server_url, {"add": True}, ("url", True)),
'remove': (server_url, {"remove": True}, ("url", True)),
}
}
def parse_recursive(casino, tree, commands):
if len(tree) == 0:
print("No more arguments available")
return None
if len(commands) == 0:
commands = ['']
if commands[0] not in tree:
expected = ', '.join([k for k in tree.keys() if k != ''])
# help
if commands[0] == '?' or commands[0] == 'help':
print("Commands: {}".format(expected))
else:
print("Bad arguments, expected: {}".format(expected))
return None
node = tree[commands[0]]
if isinstance(node, dict):
return parse_recursive(casino, node, commands[1:])
if hasattr(node, '__call__'):
node = [node]
if isinstance(node, (list, tuple)):
function = node[0]
accepted = node[1:]
arguments = commands[1:]
kargs = {}
for element in accepted:
# Extra arguments to send to the function
if isinstance(element, dict):
kargs.update(element)
continue
# Arguments that must be specified
argname, required = element
try:
arg = arguments.pop(0)
# help
if arg == '?' or arg == 'help':
print("Argument: {}".format(argname))
return
except (IndexError, AttributeError):
if not required:
break
else:
print("Missing arguments, expected: {}".format(argname))
return False
kargs[argname] = arg
function(casino, **kargs)
return False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment