Introduce hack to color all click.echo instances at once.

This commit is contained in:
Sebastian Lenzlinger 2024-06-28 22:11:20 +02:00
parent 5ccb9daca0
commit a5d4390f37
6 changed files with 96 additions and 7 deletions

View File

@ -1,6 +1,9 @@
from iottb import definitions from iottb import definitions
import logging import logging
from iottb.utils.user_interaction import tb_echo
import click
click.echo = tb_echo # This is very hacky
logging.basicConfig(level=definitions.LOGLEVEL) logging.basicConfig(level=definitions.LOGLEVEL)
log_dir = definitions.LOGDIR log_dir = definitions.LOGDIR
# Ensure logs dir exists before new handlers are registered in main.py # Ensure logs dir exists before new handlers are registered in main.py

View File

@ -8,7 +8,7 @@ import re
from iottb import definitions from iottb import definitions
from iottb.models.device_metadata import DeviceMetadata from iottb.models.device_metadata import DeviceMetadata
from iottb.models.iottb_config import IottbConfig from iottb.models.iottb_config import IottbConfig
from iottb.definitions import CFG_FILE_PATH from iottb.definitions import CFG_FILE_PATH, TB_ECHO_STYLES
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)

View File

@ -8,6 +8,11 @@ from iottb.models.iottb_config import IottbConfig
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@click.group('util')
def tb():
pass
@click.command() @click.command()
@click.option('--file', default=DB_NAME) @click.option('--file', default=DB_NAME)
@click.option('--table', type=str, default='DefaultDatabase') @click.option('--table', type=str, default='DefaultDatabase')
@ -78,3 +83,41 @@ def show_cfg(ctx, cfg_file, pp):
click.echo(content) click.echo(content)
else: else:
click.echo(f"Configuration file not found at {cfg_file}") click.echo(f"Configuration file not found at {cfg_file}")
@click.command('show-all', help='Show everything: configuration, databases, and device metadata')
@click.pass_context
def show_everything(ctx):
"""Show everything that can be recursively found based on config except file contents."""
config = ctx.obj['CONFIG']
click.echo("Configuration Context:")
click.echo(f"Default Database: {config.default_database}")
click.echo(f"Default Database Path: {config.default_db_location}")
click.echo("Database Locations:")
for db_name, db_path in config.db_path_dict.items():
full_db_path = Path(db_path) / db_name
click.echo(f" - {db_name}: {full_db_path}")
if full_db_path.is_dir():
click.echo(f"Contents of {db_name} at {full_db_path}:")
for item in full_db_path.iterdir():
if item.is_file():
click.echo(f" - {item.name}")
try:
with item.open('r', encoding='utf-8') as file:
content = file.read()
click.echo(f" Content:\n{content}")
except UnicodeDecodeError:
click.echo(" Content is not readable as text")
elif item.is_dir():
click.echo(f" - {item.name}/")
for subitem in item.iterdir():
if subitem.is_file():
click.echo(f" - {subitem.name}")
elif subitem.is_dir():
click.echo(f" - {subitem.name}/")
else:
click.echo(f" {full_db_path} is not a directory")
warnstyle = {'fg': 'red', 'bold': True}
click.secho('Developer command used', **warnstyle)

View File

@ -34,3 +34,11 @@ ERROR_SET_CANONICAL_DEVICE_NAMES = {',', '!', '@', '#', '$', '%', '^', '&', '*',
'\\', ':', ';', '"', "'", '<', '>', '?', '/', '`', '~'} '\\', ':', ';', '"', "'", '<', '>', '?', '/', '`', '~'}
DEVICE_METADATA_FILE_NAME = 'device_metadata.json' DEVICE_METADATA_FILE_NAME = 'device_metadata.json'
TB_ECHO_STYLES = {
'w': {'fg': 'yellow', 'bold': True},
'i': {'fg': 'blue', 'italic': True},
's': {'fg': 'green', 'bold': True},
'e': {'fg': 'red', 'bold': True},
'header': {'fg': 'bright_cyan', 'bold': True, 'italic': True}
}

View File

@ -3,7 +3,7 @@ from pathlib import Path
import logging import logging
from iottb.commands.sniff import sniff from iottb.commands.sniff import sniff
from iottb.commands.developer import set_key_in_table_to, rm_cfg, rm_dbs, show_cfg from iottb.commands.developer import set_key_in_table_to, rm_cfg, rm_dbs, show_cfg, show_everything
################################################## ##################################################
# Import package modules # Import package modules
################################################# #################################################
@ -57,6 +57,6 @@ cli.add_command(rm_dbs)
cli.add_command(add_device) cli.add_command(add_device)
cli.add_command(show_cfg) cli.add_command(show_cfg)
cli.add_command(sniff) cli.add_command(sniff)
cli.add_command(show_everything)
if __name__ == '__main__': if __name__ == '__main__':
cli(auto_envvar_prefix='IOTTB', show_default=True, show_envvars=True) cli(auto_envvar_prefix='IOTTB', show_default=True, show_envvars=True)

View File

@ -1,7 +1,42 @@
# iottb/utils/user_interaction.py
import click import click
import logging from iottb.definitions import TB_ECHO_STYLES
from iottb import definitions import sys
import os
class IottbPrompt: def tb_echo2(msg: str, lvl='i', log=True):
pass style = TB_ECHO_STYLES.get(lvl, {})
click.secho(f'[IOTTB]', **style)
click.secho(f'[IOTTB] \t {msg}', **style)
last_prefix = None
def tb_echo(msg: str, lvl='i', log=True):
global last_prefix
prefix = f'Testbed [{lvl.upper()}]\n'
if last_prefix != prefix:
click.secho(prefix, nl=False, **TB_ECHO_STYLES['header'])
last_prefix = prefix
click.secho(f' {msg}', **TB_ECHO_STYLES[lvl])
def main():
tb_echo('Info message', 'i')
tb_echo('Warning message', 'w')
tb_echo('Error message', 'e')
tb_echo('Success message', 's')
if __name__ == '__main__':
# arrrgggg hacky
current_dir = os.path.dirname(os.path.abspath(__file__))
project_root = os.path.abspath(os.path.join(current_dir, '../../'))
sys.path.insert(0, project_root)
main()