From 958026806bb7a6288461cd983d436b95288656f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 18 Jan 2022 18:47:35 +0100 Subject: [PATCH] =?UTF-8?q?=E2=9A=A1=EF=B8=8F=20Improve=20performance=20of?= =?UTF-8?q?=20cli=20commands?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/octoprint/cli/__init__.py | 64 ++++++++++++++++++++++++------- src/octoprint/cli/analysis.py | 9 +---- src/octoprint/cli/client.py | 25 +++++------- src/octoprint/cli/common.py | 67 +++++++++++++++++++++++++++++++++ src/octoprint/cli/config.py | 21 ++++------- src/octoprint/cli/dev.py | 9 +---- src/octoprint/cli/plugins.py | 9 +---- src/octoprint/cli/server.py | 8 ++-- src/octoprint/cli/systeminfo.py | 4 +- src/octoprint/cli/user.py | 19 ++++------ 10 files changed, 154 insertions(+), 81 deletions(-) create mode 100644 src/octoprint/cli/common.py diff --git a/src/octoprint/cli/__init__.py b/src/octoprint/cli/__init__.py index 2dc21ae62..eeaad2d38 100644 --- a/src/octoprint/cli/__init__.py +++ b/src/octoprint/cli/__init__.py @@ -10,6 +10,7 @@ import sys import click import octoprint +from octoprint.cli.common import LazyGroup click.disable_unicode_literals_warning = True @@ -277,16 +278,56 @@ legacy_options = bulk_options( Kept available for reasons of backwards compatibility, but hidden from the generated help pages.""" +# ~~ command groups from sub modules + + +@click.group() +def subcommands(): + pass + + +@subcommands.group( + name="analysis", cls=LazyGroup, import_name="octoprint.cli.analysis:cli" +) +def analysis(): + """Analysis tools.""" + pass + + +@subcommands.group(name="client", cls=LazyGroup, import_name="octoprint.cli.client:cli") +def client(): + """Basic API client.""" + pass + + +@subcommands.group(name="config", cls=LazyGroup, import_name="octoprint.cli.config:cli") +def config(): + """Basic config manipulation.""" + pass + + +@subcommands.group(name="dev", cls=LazyGroup, import_name="octoprint.cli.dev:cli") +def dev(): + """Additional commands for development tasks.""" + pass + + +@subcommands.group(name="plugins", cls=LazyGroup, import_name="octoprint.cli.plugins:cli") +def plugins(): + """Additional commands provided by plugins.""" + pass + + +@subcommands.group(name="user", cls=LazyGroup, import_name="octoprint.cli.user:cli") +def user(): + """User management.""" + pass + + # ~~ "octoprint" command, merges server_commands and plugin_commands groups -from .analysis import analysis_commands # noqa: E402 -from .client import client_commands # noqa: E402 -from .config import config_commands # noqa: E402 -from .dev import dev_commands # noqa: E402 -from .plugins import plugin_commands # noqa: E402 -from .server import server_commands # noqa: E402 -from .systeminfo import systeminfo_commands # noqa: E402 -from .user import user_commands # noqa: E402 +from .server import cli as server_commands # noqa: E402 +from .systeminfo import cli as systeminfo_commands # noqa: E402 @click.group( @@ -294,13 +335,8 @@ from .user import user_commands # noqa: E402 invoke_without_command=True, cls=click.CommandCollection, sources=[ + subcommands, server_commands, - plugin_commands, - dev_commands, - client_commands, - config_commands, - analysis_commands, - user_commands, systeminfo_commands, ], ) diff --git a/src/octoprint/cli/analysis.py b/src/octoprint/cli/analysis.py index aaaaf5762..5e8f8f436 100644 --- a/src/octoprint/cli/analysis.py +++ b/src/octoprint/cli/analysis.py @@ -58,17 +58,12 @@ def validate_result(result): @click.group() -def analysis_commands(): - pass - - -@analysis_commands.group(name="analysis") -def util(): +def cli(): """Analysis tools.""" pass -@util.command(name="gcode") +@cli.command(name="gcode") @click.option("--throttle", "throttle", type=float, default=None) @click.option("--throttle-lines", "throttle_lines", type=int, default=None) @click.option("--speed-x", "speedx", type=float, default=6000) diff --git a/src/octoprint/cli/client.py b/src/octoprint/cli/client.py index 98d21d37d..51dcbcbd3 100644 --- a/src/octoprint/cli/client.py +++ b/src/octoprint/cli/client.py @@ -77,15 +77,10 @@ client_options = bulk_options( """Common options to configure an API client.""" -@click.group() -def client_commands(): - pass - - -@client_commands.group("client", context_settings={"ignore_unknown_options": True}) +@click.group(context_settings={"ignore_unknown_options": True}) @client_options @click.pass_context -def client(ctx, apikey, host, port, httpuser, httppass, https, prefix): +def cli(ctx, apikey, host, port, httpuser, httppass, https, prefix): """Basic API client.""" try: settings = None @@ -123,7 +118,7 @@ def log_response(response, status_code=True, body=True, headers=False): click.echo(response.text) -@client.command("get") +@cli.command("get") @click.argument("path") @click.option("--timeout", type=float, default=None) @click.pass_context @@ -133,7 +128,7 @@ def get(ctx, path, timeout): log_response(r) -@client.command("post_json") +@cli.command("post_json") @click.argument("path") @click.argument("data", type=JsonStringParamType()) @click.option("--timeout", type=float, default=None) @@ -144,7 +139,7 @@ def post_json(ctx, path, data, timeout): log_response(r) -@client.command("patch_json") +@cli.command("patch_json") @click.argument("path") @click.argument("data", type=JsonStringParamType()) @click.option("--timeout", type=float, default=None, help="Request timeout in seconds") @@ -155,7 +150,7 @@ def patch_json(ctx, path, data, timeout): log_response(r) -@client.command("post_from_file") +@cli.command("post_from_file") @click.argument("path") @click.argument( "file_path", type=click.Path(exists=True, dir_okay=False, resolve_path=True) @@ -183,7 +178,7 @@ def post_from_file(ctx, path, file_path, json_flag, yaml_flag, timeout): log_response(r) -@client.command("command") +@cli.command("command") @click.argument("path") @click.argument("command") @click.option( @@ -227,7 +222,7 @@ def command( log_response(r, body=False) -@client.command("upload") +@cli.command("upload") @click.argument("path") @click.argument( "file_path", type=click.Path(exists=True, dir_okay=False, resolve_path=True) @@ -261,7 +256,7 @@ def upload(ctx, path, file_path, params, file_name, content_type, timeout): log_response(r) -@client.command("delete") +@cli.command("delete") @click.argument("path") @click.option("--timeout", type=float, default=None, help="Request timeout in seconds") @click.pass_context @@ -271,7 +266,7 @@ def delete(ctx, path, timeout): log_response(r) -@client.command("listen") +@cli.command("listen") @click.pass_context def listen(ctx): def on_connect(ws): diff --git a/src/octoprint/cli/common.py b/src/octoprint/cli/common.py new file mode 100644 index 000000000..ae37e1372 --- /dev/null +++ b/src/octoprint/cli/common.py @@ -0,0 +1,67 @@ +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals + +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" +__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" + + +from importlib import import_module + +import click +from werkzeug.utils import cached_property + +# shared by https://github.com/indico/indico in pallets/click#945 + + +class LazyGroup(click.Group): + """ + A click Group that imports the actual implementation only when + needed. This allows for more resilient CLIs where the top-level + command does not fail when a subcommand is broken enough to fail + at import time. + """ + + def __init__(self, import_name, **kwargs): + self._import_name = import_name + super().__init__(**kwargs) + + @cached_property + def _impl(self): + module, name = self._import_name.split(":", 1) + return getattr(import_module(module), name) + + def get_command(self, ctx, cmd_name): + return self._impl.get_command(ctx, cmd_name) + + def list_commands(self, ctx): + return self._impl.list_commands(ctx) + + def invoke(self, ctx): + return self._impl.invoke(ctx) + + def get_usage(self, ctx): + return self._impl.get_usage(ctx) + + def get_params(self, ctx): + return self._impl.get_params(ctx) + + +class LazyCommandCollection(click.CommandCollection): + def __init__(self, **kwargs): + super().__init__(**kwargs) + + def get_command(self, ctx, cmd_name): + pass + + def list_commands(self, ctx): + pass + + def group(self, *args, **kwargs): + from click.decorators import group + + def decorator(f): + cmd = group(*args, **kwargs)(f) + self.add_command(cmd) + return cmd + + return decorator diff --git a/src/octoprint/cli/config.py b/src/octoprint/cli/config.py index c2b79994a..01f92fd85 100644 --- a/src/octoprint/cli/config.py +++ b/src/octoprint/cli/config.py @@ -48,13 +48,8 @@ def _set_helper(settings, path, value, data_type=None): @click.group() -def config_commands(): - pass - - -@config_commands.group(name="config") @click.pass_context -def config(ctx): +def cli(ctx): """Basic config manipulation.""" logging.basicConfig( level=logging.DEBUG @@ -73,7 +68,7 @@ def config(ctx): ctx.exit(-1) -@config.command(name="set") +@cli.command(name="set") @standard_options(hidden=True) @click.argument("path", type=click.STRING) @click.argument("value", type=click.STRING) @@ -102,7 +97,7 @@ def set_command(ctx, path, value, as_bool, as_float, as_int, as_json): _set_helper(ctx.obj.settings, path, value, data_type=data_type) -@config.command(name="remove") +@cli.command(name="remove") @standard_options(hidden=True) @click.argument("path", type=click.STRING) @click.pass_context @@ -111,7 +106,7 @@ def remove_command(ctx, path): _set_helper(ctx.obj.settings, path, None) -@config.command(name="append_value") +@cli.command(name="append_value") @standard_options(hidden=True) @click.argument("path", type=click.STRING) @click.argument("value", type=click.STRING) @@ -139,7 +134,7 @@ def append_value_command(ctx, path, value, as_json=False): _set_helper(ctx.obj.settings, path, current) -@config.command(name="insert_value") +@cli.command(name="insert_value") @standard_options(hidden=True) @click.argument("path", type=click.STRING) @click.argument("index", type=click.INT) @@ -168,7 +163,7 @@ def insert_value_command(ctx, path, index, value, as_json=False): _set_helper(ctx.obj.settings, path, current) -@config.command(name="remove_value") +@cli.command(name="remove_value") @standard_options(hidden=True) @click.argument("path", type=click.STRING) @click.argument("value", type=click.STRING) @@ -200,7 +195,7 @@ def remove_value_command(ctx, path, value, as_json=False): _set_helper(ctx.obj.settings, path, current) -@config.command(name="get") +@cli.command(name="get") @click.argument("path", type=click.STRING) @click.option("--json", "as_json", is_flag=True, help="Output value formatted as JSON") @click.option("--yaml", "as_yaml", is_flag=True, help="Output value formatted as YAML") @@ -226,7 +221,7 @@ def get_command(ctx, path, as_json=False, as_yaml=False, as_raw=False): click.echo(output) -@config.command(name="effective") +@cli.command(name="effective") @click.option("--json", "as_json", is_flag=True, help="Output value formatted as JSON") @click.option("--yaml", "as_yaml", is_flag=True, help="Output value formatted as YAML") @click.option( diff --git a/src/octoprint/cli/dev.py b/src/octoprint/cli/dev.py index 51f85bd9c..46f39f8f4 100644 --- a/src/octoprint/cli/dev.py +++ b/src/octoprint/cli/dev.py @@ -257,12 +257,7 @@ class OctoPrintDevelCommands(click.MultiCommand): return command -@click.group() -def dev_commands(): - pass - - -@dev_commands.group(name="dev", cls=OctoPrintDevelCommands) -def dev(): +@click.group(cls=OctoPrintDevelCommands) +def cli(): """Additional commands for development tasks.""" pass diff --git a/src/octoprint/cli/plugins.py b/src/octoprint/cli/plugins.py index 09b86c06e..c7f91f5eb 100644 --- a/src/octoprint/cli/plugins.py +++ b/src/octoprint/cli/plugins.py @@ -141,13 +141,8 @@ class OctoPrintPluginCommands(click.MultiCommand): return result -@click.group() +@click.group(cls=OctoPrintPluginCommands) @pass_octoprint_ctx -def plugin_commands(obj): - pass - - -@plugin_commands.group(name="plugins", cls=OctoPrintPluginCommands) -def plugins(): +def cli(obj): """Additional commands provided by plugins.""" pass diff --git a/src/octoprint/cli/server.py b/src/octoprint/cli/server.py index 2788cd5fc..3ee8312c8 100644 --- a/src/octoprint/cli/server.py +++ b/src/octoprint/cli/server.py @@ -251,11 +251,11 @@ daemon_options = bulk_options( @click.group() -def server_commands(): +def cli(): pass -@server_commands.command(name="safemode") +@cli.command(name="safemode") @standard_options() @click.pass_context def enable_safemode(ctx, **kwargs): @@ -286,7 +286,7 @@ def enable_safemode(ctx, **kwargs): ) -@server_commands.command(name="serve") +@cli.command(name="serve") @standard_options() @server_options @click.pass_context @@ -333,7 +333,7 @@ def serve_command(ctx, **kwargs): if sys.platform != "win32" and sys.platform != "darwin": # we do not support daemon mode under windows or macosx - @server_commands.command(name="daemon") + @cli.command(name="daemon") @standard_options() @server_options @daemon_options diff --git a/src/octoprint/cli/systeminfo.py b/src/octoprint/cli/systeminfo.py index a5c906a0a..efef5d172 100644 --- a/src/octoprint/cli/systeminfo.py +++ b/src/octoprint/cli/systeminfo.py @@ -152,11 +152,11 @@ def get_systeminfo_bundle_name(): @click.group() -def systeminfo_commands(): +def cli(): pass -@systeminfo_commands.command(name="systeminfo") +@cli.command(name="systeminfo") @standard_options() @click.argument( "path", diff --git a/src/octoprint/cli/user.py b/src/octoprint/cli/user.py index 724d9cf60..ef32dc41e 100644 --- a/src/octoprint/cli/user.py +++ b/src/octoprint/cli/user.py @@ -26,13 +26,8 @@ click.disable_unicode_literals_warning = True @click.group() -def user_commands(): - pass - - -@user_commands.group(name="user") @click.pass_context -def user(ctx): +def cli(ctx): """ User management. @@ -87,7 +82,7 @@ def user(ctx): ctx.exit(-1) -@user.command(name="list") +@cli.command(name="list") @click.pass_context def list_users_command(ctx): """Lists user information""" @@ -95,7 +90,7 @@ def list_users_command(ctx): _print_list(users) -@user.command(name="add") +@cli.command(name="add") @click.argument("username", type=click.STRING, required=True) @click.password_option("--password", "password", help="Password for the user") @click.option("-g", "--group", "groups", multiple=True, help="Groups to set on the user") @@ -138,7 +133,7 @@ def add_user_command(ctx, username, password, groups, permissions, is_admin): ) -@user.command(name="remove") +@cli.command(name="remove") @click.argument("username", type=click.STRING) @click.pass_context def remove_user_command(ctx, username): @@ -155,7 +150,7 @@ def remove_user_command(ctx, username): click.echo("User {} not removed.".format(username)) -@user.command(name="password") +@cli.command(name="password") @click.argument("username", type=click.STRING) @click.password_option("--password", "password", help="New password for user") @click.pass_context @@ -168,7 +163,7 @@ def change_password_command(ctx, username, password): click.echo("User {} does not exist!".format(username), err=True) -@user.command(name="activate") +@cli.command(name="activate") @click.argument("username", type=click.STRING) @click.pass_context def activate_command(ctx, username): @@ -185,7 +180,7 @@ def activate_command(ctx, username): click.echo("User {} does not exist!".format(username), err=True) -@user.command(name="deactivate") +@cli.command(name="deactivate") @click.argument("username", type=click.STRING) @click.pass_context def deactivate_command(ctx, username):