Refactor cli command loading

This commit is contained in:
Tim Van Baak 2020-01-15 19:30:03 -08:00
parent db83c99b95
commit 173b306c5b
4 changed files with 61 additions and 16 deletions

View File

@ -46,14 +46,9 @@ def repl(args):
traceback.print_exc() traceback.print_exc()
def get_parser(valid_commands): def get_parser(valid_commands):
# Pull out the command functions' docstrings to describe them.
command_descs = "\n".join([
"- {0}: {1}".format(name, func.__doc__)
for name, func in valid_commands.items()])
# Set up the top-level parser. # Set up the top-level parser.
parser = argparse.ArgumentParser( parser = argparse.ArgumentParser(
description="Available commands:\n{}\n".format(command_descs), description=cli.describe_commands(),
formatter_class=argparse.RawDescriptionHelpFormatter) formatter_class=argparse.RawDescriptionHelpFormatter)
# The config directory. # The config directory.
parser.add_argument("--config-dir", parser.add_argument("--config-dir",
@ -105,10 +100,7 @@ def get_parser(valid_commands):
def main(argv): def main(argv):
# Enumerate valid commands from the CLI module. # Enumerate valid commands from the CLI module.
commands = { commands = cli.get_commands()
name[8:].replace("_", "-") : func
for name, func in vars(cli).items()
if name.startswith("command_")}
args = get_parser(commands).parse_args(argv) args = get_parser(commands).parse_args(argv)

View File

@ -8,5 +8,53 @@
# run after commandline parsing has already occurred. # run after commandline parsing has already occurred.
# #
from cli.server import * def server_commands(commands={}):
from cli.user import * if commands: return commands
import cli.server
for name, func in vars(cli.server).items():
if name.startswith("command_"):
name = name[8:].replace("_", "-")
commands[name] = func
return commands
def lexicon_commands(commands={}):
if commands: return commands
import cli.lexicon
for name, func in vars(cli.lexicon).items():
if name.startswith("command_"):
name = name[8:].replace("_", "-")
commands["lexicon-" + name] = func
return commands
def user_commands(commands={}):
if commands: return commands
import cli.user
for name, func in vars(cli.user).items():
if name.startswith("command_"):
name = name[8:].replace("_", "-")
commands["user-" + name] = func
return commands
def get_commands():
return {**server_commands(), **lexicon_commands(), **user_commands()}
def describe_commands():
longest = max(map(len, server_commands().keys()))
server_desc = "General commands:\n{}\n".format("\n".join([
" {1:<{0}} : {2}".format(longest, name, func.__doc__ or "")
for name, func in server_commands().items()
]))
longest = max(map(len, lexicon_commands().keys()))
lexicon_desc = "Lexicon commands:\n{}\n".format("\n".join([
" {1:<{0}} : {2}".format(longest, name, func.__doc__ or "")
for name, func in lexicon_commands().items()
]))
longest = max(map(len, user_commands().keys()))
user_desc = "User commands:\n{}\n".format("\n".join([
" {1:<{0}} : {2}".format(longest, name, func.__doc__ or "")
for name, func in user_commands().items()
]))
return "\n".join([server_desc, lexicon_desc, user_desc])

View File

@ -1 +1,6 @@
from cli.helpers import add_argument, no_argument from cli.helpers import add_argument, no_argument
@no_argument
def command_noop(args):
"""noop"""
pass

View File

@ -3,7 +3,7 @@ from cli.helpers import add_argument, no_argument
@add_argument("--username", help="User's login handle") @add_argument("--username", help="User's login handle")
@add_argument("--displayname", help="User's publicly displayed name") @add_argument("--displayname", help="User's publicly displayed name")
@add_argument("--email", help="User's email") @add_argument("--email", help="User's email")
def command_user_add(args): def command_add(args):
"""Creates a user""" """Creates a user"""
import json import json
@ -33,7 +33,7 @@ def command_user_add(args):
print("Username: {}\nUser ID: {}\nPassword: {}".format(args.username, new_user.uid, tmp_pw)) print("Username: {}\nUser ID: {}\nPassword: {}".format(args.username, new_user.uid, tmp_pw))
@add_argument("--id", help="id of user to delete") @add_argument("--id", help="id of user to delete")
def command_user_delete(args): def command_delete(args):
import os import os
import config import config
@ -49,7 +49,7 @@ def command_user_delete(args):
del j[uid] del j[uid]
@no_argument @no_argument
def command_user_list(args): def command_list(args):
"""Lists users""" """Lists users"""
import os import os
@ -66,7 +66,7 @@ def command_user_list(args):
print("{0} {1} ({2})".format(user['uid'], user['displayname'], user['username'])) print("{0} {1} ({2})".format(user['uid'], user['displayname'], user['username']))
@add_argument("--username", help="The user to change password for") @add_argument("--username", help="The user to change password for")
def command_user_passwd(args): def command_passwd(args):
"""Set a user's password""" """Set a user's password"""
import getpass import getpass
import os import os