Add config loading in main and a project test folder.

This commit is contained in:
Sebastian Lenzlinger 2024-06-27 13:40:20 +02:00
parent 8dc7d892e6
commit f024d6dec6
3 changed files with 47 additions and 20 deletions

View File

@ -1,13 +1,15 @@
import json
import subprocess import subprocess
import click import click
from pathlib import PurePath from pathlib import PurePath, Path
import configparser import configparser
import logging import logging
from logging.handlers import RotatingFileHandler from logging.handlers import RotatingFileHandler
import sys import sys
APP_NAME = 'iottb' APP_NAME = 'iottb'
DB_NAME = 'iottb.db'
CONSOLE_LOG_FORMATS = { CONSOLE_LOG_FORMATS = {
0: '%(levelname)s - %(message)s', 0: '%(levelname)s - %(message)s',
@ -23,11 +25,13 @@ LOGFILE_LOG_FORMAT = {
MAX_VERBOSITY = len(CONSOLE_LOG_FORMATS) - 1 MAX_VERBOSITY = len(CONSOLE_LOG_FORMATS) - 1
assert len(LOGFILE_LOG_FORMAT) == len(CONSOLE_LOG_FORMATS), 'Log formats must be same size' assert len(LOGFILE_LOG_FORMAT) == len(CONSOLE_LOG_FORMATS), 'Log formats must be same size'
logger = logging.getLogger(__name__)
def setup_logging(verbosity, debug): def setup_logging(verbosity, debug):
""" Setup root logger for iottb """ """ Setup root logger for iottb """
log_level = logging.ERROR log_level = logging.ERROR
logger = logging.getLogger() handlers = []
date_format = '%Y-%m-%d %H:%M:%S' date_format = '%Y-%m-%d %H:%M:%S'
if verbosity > 0: if verbosity > 0:
log_level = logging.WARNING log_level = logging.WARNING
@ -38,7 +42,7 @@ def setup_logging(verbosity, debug):
console_handler = logging.StreamHandler(sys.stdout) console_handler = logging.StreamHandler(sys.stdout)
console_handler.setFormatter(logging.Formatter(CONSOLE_LOG_FORMATS[verbosity], datefmt=date_format)) console_handler.setFormatter(logging.Formatter(CONSOLE_LOG_FORMATS[verbosity], datefmt=date_format))
console_handler.setLevel(logging.DEBUG) # can keep at debug since it depends on global level? console_handler.setLevel(logging.DEBUG) # can keep at debug since it depends on global level?
logger.addHandler(console_handler) handlers.append(console_handler)
if debug: if debug:
log_level = logging.DEBUG log_level = logging.DEBUG
@ -49,31 +53,54 @@ def setup_logging(verbosity, debug):
file_handler.setLevel(logging.INFO) file_handler.setLevel(logging.INFO)
# finnish root logger setup # finnish root logger setup
logger.addHandler(file_handler) handlers.append(file_handler)
logger.setLevel(log_level) # Force this config to be applied to root logger
return logger logging.basicConfig(level=log_level, handlers=handlers, force=True)
class Environment: def create_default_config(cfg_file):
def __init__(self, cfg=None, db=None, device=None): """Create default iottb config file."""
self.cfg = cfg assert logger is not None, 'Logger must be initialized'
self.db = db logger.info(f'Creating default config file at {cfg_file}')
self.device = device # By default, create iottb.db in user home
pass defaults = {
'DefaultDatabase': DB_NAME,
'DatabaseLocations': {
DB_NAME: str(Path.home() / DB_NAME)
}
}
with open(cfg_file, 'w') as config_file:
json.dump(defaults, config_file)
return defaults
def load_config(cfg_file_path): def load_config(ctx, param, value):
cfg_file = PurePath(click.get_app_dir(APP_NAME)).joinpath('iottb.cfg') """ Try to load iottb config file.
If the file does not exist, it will be created with default values.`
Try to load the iottb config file from the given path.
If the file does not exist, it will be created with default values.
The only value set is the path to the iottb.db file.
"""
logger.info(f'Loading config from {value}')
cfg_file = value
if not cfg_file.is_file():
defaults = create_default_config(cfg_file)
else:
defaults = json.load(cfg_file)
ctx.obj['path']['cfg'] = cfg_file
ctx.obj['path']['db'] = defaults['DatabaseLocations'][defaults['DefaultDatabase']]
@click.group() @click.group()
@click.option('-v', '--verbosity', type=click.IntRange(0, MAX_VERBOSITY), default=0, @click.option('-v', '--verbosity', type=click.IntRange(0, MAX_VERBOSITY), default=0,
help='Verbosity level') help='Set verbosity')
@click.option('-d', '--debug', is_flag=True, default=False, help='Debug mode') @click.option('-d', '--debug', is_flag=True, default=False, help='Enable debug mode')
@click.option('--cfg-file', type=click.Path(), default=PurePath(click.get_app_dir(APP_NAME)).joinpath('iottb.cfg'), @click.option('--cfg-file', type=click.Path(), default=Path(click.get_app_dir(APP_NAME)).joinpath('iottb.cfg'),
envvar='IOTTB_CONF_HOME',) envvar='IOTTB_CONF_HOME', is_eager=True, callback=load_config, help='Path to iottb config file')
def main(debug, verbose): @click.pass_context
setup_logging(verbose, debug) def main(verbosity, debug):
setup_logging(verbosity, debug)
if __name__ == '__main__': if __name__ == '__main__':

0
tests/__init__.py Normal file
View File

0
tests/test_main.py Normal file
View File