From e4e3e452175c43568f8d85b187e2e67bdac9fcb6 Mon Sep 17 00:00:00 2001 From: Tim Van Baak Date: Tue, 31 Dec 2019 13:21:19 -0800 Subject: [PATCH] Add lexicon repl --- amanuensis/__main__.py | 48 +++++++++++++++++++++++++++++++++--------- 1 file changed, 38 insertions(+), 10 deletions(-) diff --git a/amanuensis/__main__.py b/amanuensis/__main__.py index 41052e7..644198f 100644 --- a/amanuensis/__main__.py +++ b/amanuensis/__main__.py @@ -1,11 +1,42 @@ # Standard library imports import argparse +import traceback # Application imports import cli import configs +@cli.no_argument +def repl(args): + """Runs a REPL with the given lexicon""" + commands = { + name[8:]: func.__doc__ for name, func in vars(cli).items() + if name.startswith("command_")} + commands['help'] = "Print this message" + print("Amanuensis running on Lexicon {}".format(args.lexicon)) + while True: + try: + data = input("{}> ".format(args.lexicon)) + except EOFError: + print() + break + tokens = data.strip().split() + if not data.strip(): + pass + elif tokens[0] not in commands: + print("'{}' is not a valid command.".format(tokens[0])) + elif data.strip() == "help": + print("Available commands:") + for name, func in commands.items(): + print(" {}: {}".format(name, func)) + elif data.strip(): + try: + argv = sys.argv[1:] + data.split() + main(argv) + except Exception as e: + traceback.print_exc() + def get_parser(valid_commands): # Pull out the command functions' docstrings to describe them. command_descs = "\n".join([ @@ -16,14 +47,14 @@ def get_parser(valid_commands): parser = argparse.ArgumentParser( description="Available commands:\n{}\n".format(command_descs), formatter_class=argparse.RawDescriptionHelpFormatter) - parser.add_argument("-n", - dest="lexicon", + parser.add_argument("lexicon", + metavar="LEXICON", help="The name of the lexicon to operate on") parser.add_argument("-v", action="store_true", dest="verbose", help="Enable debug logging") - parser.set_defaults(func=lambda a: parser.print_help()) + parser.set_defaults(func=repl) subp = parser.add_subparsers( metavar="COMMAND", help="The command to execute") @@ -36,22 +67,19 @@ def get_parser(valid_commands): cmd = subp.add_parser(name, description=func.__doc__) # Delegate subparser setup. func(cmd) - # Store function for later execution + # Store function for later execution. cmd.set_defaults(func=func) return parser -def no_command(): - print("nothing") - -def main(): +def main(argv): # Enumerate valid commands from the CLI module. commands = { name[8:] : func for name, func in vars(cli).items() if name.startswith("command_")} - args = get_parser(commands).parse_args() + args = get_parser(commands).parse_args(argv) # Configure logging. if args.verbose: @@ -62,4 +90,4 @@ def main(): if __name__ == "__main__": import sys - sys.exit(main()) + sys.exit(main(sys.argv[1:]))