From 7666e7394a95491f25726a2263b772f414bb464b Mon Sep 17 00:00:00 2001 From: TheOnePath Date: Sun, 30 Jul 2023 16:06:20 +0100 Subject: [PATCH] Updated commands.py Command@get_command() method now allows for the app to error if a command is unrecognised. This is used by commands such as Help, when a help message cannot be displayed for an unrecognised command. Changed the way help summary messages are accessed from commands. --- soypak/cli/command.py | 28 ++++++++++++++++------------ 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/soypak/cli/command.py b/soypak/cli/command.py index 531241b..c2a4de7 100644 --- a/soypak/cli/command.py +++ b/soypak/cli/command.py @@ -1,5 +1,5 @@ -import argparse import sys +import clog import soypak.cli.parser as parser @@ -11,7 +11,7 @@ class RegisterCommand(type): def __init__(cls, name, bases, _dict): super().__init__(name, bases, _dict) # get the name of the command - name = getattr(cls, "__cmd_name__", None) + name = getattr(cls, "name", None) if name is None: raise Exception("Command has no registered name.") @@ -21,12 +21,10 @@ class RegisterCommand(type): # add the command to the registered list, with `name` and class object Command.registered_cmds[name] = cls - # fetch the documentation for the command - _help = cls.__doc__ - if not _help: + if not cls.__doc__: raise Exception("Command does not provide a __doc__ attribute for usage.") # add the command to the argparse._action_groups list (will appear as a positional in help message) - parser.SoypakParser.add_action_command(cmd=name, help=_help.split('\n')[0]) + parser.SoypakParser.add_action_command(cmd=name, help=cls.__doc__.split('\n')[0]) class Command: @@ -40,15 +38,21 @@ class Command: @staticmethod - def get_command(name, *, args: list[str]) -> RegisterCommand | None: + def get_command(name, *, error: bool = False, args: list[str] | None = None) -> RegisterCommand | None: """Fetch and initialise a registered command, or return `None` is command cannot be found.""" - return ( - Command.registered_cmds[name](data=parser.SoypakParser().namespace, args=args) if name in - Command.registered_cmds else None - ) + if name in Command.registered_cmds: + return Command.registered_cmds[name](data=parser.SoypakParser().namespace, args=args) + + if error: + # Just get the logger for this one statement (:@Note: if more logging occurs, global variable for logger) + clog.Logger.get("runtime_logger").error("Unrecognised command: %s" % name).withConsole() + Command.die() + + return None - def die(self): + @staticmethod + def die(): """System exit with status code 0""" sys.exit(0)