dump-things-pyclient/dump_things_pyclient/commands/dtc.py
2026-01-23 11:12:01 +01:00

60 lines
1.7 KiB
Python

import logging
import importlib
import pkgutil
from pathlib import Path
import rich_click as click
dtc_plugins_dir = Path(__file__).parent / 'dtc_plugins'
# This will add a stream handler
logging.basicConfig(level=logging.WARNING)
def load_subcommands(group):
"""Load all sub-command plugins and register them with the group"""
for module_info in pkgutil.iter_modules([dtc_plugins_dir]):
try:
module = importlib.import_module(
'.' + module_info.name,
package='dump_things_pyclient.commands.dtc_plugins',
)
except:
logging.exception('failed to load plugin module %s', module_info)
exit(1)
# get the plugin attributes
plugin_cli = getattr(module, 'subcommand_name', None)
command_name = getattr(module, 'subcommand_name', None)
# skip non-plugin files
if plugin_cli is None or command_name is None:
continue
group.add_command(cmd=getattr(module, 'cli'), name=command_name)
@click.group()
@click.option('--token', envvar='DTC_TOKEN', default=None, help='provide a token on the command line, NOTE: on multiuser systems you should use the environment variable DTC_TOKEN instead')
@click.option('--debug', envvar='DTC_DEBUG', default=False, is_flag=True, help='show debug output')
@click.pass_context
def cli(ctx, token: str, debug: bool):
initialize_logging(debug)
ctx.obj = token
def initialize_logging(debug: bool):
logging.basicConfig(
level=logging.DEBUG if debug else logging.INFO,
force=True,
)
# Load all command plugins from submodule .dtc_plugins`.
load_subcommands(cli)
if __name__ == '__main__':
cli()