From 1e70b955480c185379adabfe35526c3f335305fa Mon Sep 17 00:00:00 2001 From: Tim Van Baak Date: Tue, 28 Jan 2020 13:24:01 -0800 Subject: [PATCH] Refactor lexicon loading into wrapper --- amanuensis/__main__.py | 8 +++----- amanuensis/cli/helpers.py | 25 +++++++++++++++---------- 2 files changed, 18 insertions(+), 15 deletions(-) diff --git a/amanuensis/__main__.py b/amanuensis/__main__.py index e88eea4..dbd3ce7 100644 --- a/amanuensis/__main__.py +++ b/amanuensis/__main__.py @@ -5,7 +5,8 @@ import traceback # Module imports import amanuensis.cli as cli -from amanuensis.cli.helpers import USER_ARGS, USER_KWARGS +from amanuensis.cli.helpers import ( + USER_ARGS, USER_KWARGS, LEXICON_ARGS, LEXICON_KWARGS) import amanuensis.config as config @@ -80,10 +81,7 @@ def get_parser(valid_commands): default=os.environ.get(config.ENV_LOG_FILE_NUM), help="Maximum rolling file count") # Lexicon settings. - parser.add_argument("-n", - metavar="LEXICON", - dest="tl_lexicon", - help="Specify a lexicon to operate on") + parser.add_argument(*LEXICON_ARGS, **LEXICON_KWARGS) parser.add_argument(*USER_ARGS, **USER_KWARGS) parser.set_defaults( func=lambda args: repl(args) diff --git a/amanuensis/cli/helpers.py b/amanuensis/cli/helpers.py index f925c4a..83230da 100644 --- a/amanuensis/cli/helpers.py +++ b/amanuensis/cli/helpers.py @@ -49,14 +49,17 @@ def no_argument(command): # Wrappers for commands requiring lexicon or username options +LEXICON_ARGS = ['--lexicon'] +LEXICON_KWARGS = { + 'metavar': 'LEXICON', + 'dest': 'lexicon', + 'help': 'Specify a user to operate on'} def requires_lexicon(command): @wraps(command) def augmented_command(cmd_args): # Add lexicon argument in parser pass if isinstance(cmd_args, ArgumentParser): - cmd_args.add_argument( - "-n", metavar="LEXICON", dest="lexicon", - help="Specify a lexicon to operate on") + cmd_args.add_argument(*LEXICON_ARGS, **LEXICON_KWARGS) # If there are more command wrappers, pass through to them if command.__dict__.get('wrapper', False): command(cmd_args) @@ -64,17 +67,19 @@ def requires_lexicon(command): return None # Verify lexicon argument in execute pass - base_val = (hasattr(cmd_args, "tl_lexicon") - and getattr(cmd_args, "tl_lexicon")) - subp_val = (hasattr(cmd_args, "lexicon") - and getattr(cmd_args, "lexicon")) - val = subp_val or base_val or None + val = ((hasattr(cmd_args, 'lexicon') + and getattr(cmd_args, 'lexicon')) + or None) if not val: from amanuensis.config import logger logger.error("This command requires specifying a lexicon") return -1 - # from amanuensis.lexicon import LexiconModel - cmd_args.lexicon = val#LexiconModel.by(name=val).name TODO + from amanuensis.lexicon import LexiconModel + cmd_args.lexicon = LexiconModel.by(name=val) #TODO catch specific exceptions + if cmd_args.lexicon is None: + from amanuensis.config import logger + logger.error('Could not find lexicon "{}"'.format(val)) + return -1 return command(cmd_args) augmented_command.__dict__['wrapper'] = True