From 29f76601ba17ae6dac18c3dff450942292363a7d Mon Sep 17 00:00:00 2001 From: Ole Herman Schumacher Elgesem Date: Tue, 22 Feb 2022 15:32:47 +0100 Subject: [PATCH 1/2] Added cache decorator similar to the one in functools From cf-remote, see: https://github.com/cfengine/cf-remote/pull/27 https://github.com/cfengine/cf-remote/commit/3f7a79c815e122fc78fef2c4ad1559cdbab50aee Signed-off-by: Ole Herman Schumacher Elgesem --- cfbs/utils.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/cfbs/utils.py b/cfbs/utils.py index dd9d844b..fb439191 100644 --- a/cfbs/utils.py +++ b/cfbs/utils.py @@ -253,3 +253,17 @@ def find(name, recursive=True, directories=False, files=True, extension=None): yield os.path.join(root, file) if not recursive: return # End iteration after looking through first (top) level + + +def cache(func): + """Memoization decorator similar to functools.cache (Python 3.9+)""" + memo = {} + + def wrapper(*args, **kwargs): + kwargs = OrderedDict(sorted(kwargs.items())) + key = str({"args": args, "kwargs": kwargs}) + if key not in memo: + memo[key] = func(*args, **kwargs) + return memo[key] + + return wrapper From 046d38a9b62cea05cad796963cd1a9270e699af3 Mon Sep 17 00:00:00 2001 From: Ole Herman Schumacher Elgesem Date: Tue, 22 Feb 2022 16:08:01 +0100 Subject: [PATCH 2/2] Added help output when no arguments are given Signed-off-by: Ole Herman Schumacher Elgesem --- cfbs/main.py | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/cfbs/main.py b/cfbs/main.py index ad2de310..c342f4b2 100644 --- a/cfbs/main.py +++ b/cfbs/main.py @@ -8,11 +8,12 @@ import logging as log from cfbs.version import string as version -from cfbs.utils import user_error, is_cfbs_repo +from cfbs.utils import user_error, is_cfbs_repo, cache from cfbs import commands -def get_args(): +@cache +def _get_arg_parser(): command_list = [ cmd.split("_")[0] for cmd in dir(commands) if cmd.endswith("_command") ] @@ -58,10 +59,12 @@ def get_args(): help="Keep order of items in the JSON in 'cfbs pretty'", action="store_true", ) + return parser + +def get_args(): + parser = _get_arg_parser() args = parser.parse_args() - if args.command == "help": - parser.print_help() return args @@ -94,7 +97,9 @@ def main() -> int: return 0 if not args.command: - user_error("Usage: cfbs COMMAND") + _get_arg_parser().print_help() + print("") + user_error("No command given") if args.non_interactive and args.command not in ( "init", @@ -118,6 +123,7 @@ def main() -> int: # Commands you can run outside a cfbs repo: if args.command == "help": + _get_arg_parser().print_help() return 0 if args.command == "init": return commands.init_command( @@ -157,4 +163,5 @@ def main() -> int: if args.command == "update": return commands.update_command(non_interactive=args.non_interactive) + _get_arg_parser().print_help() user_error("Command '%s' not found" % args.command)