import yaml import platformdirs from pathlib import Path import constants from log_setup import logger class DBConfig: def __init__(self, db_name: str, db_user: str, db_pass: str): self.db_name = db_name self.db_user = db_user self.db_pass = db_pass def read_db_config() -> DBConfig: config_dir = Path(platformdirs.user_config_dir(constants.APP_NAME, ensure_exists=True)) config_path = config_dir / constants.DB_CONFIG_FILE_NAME logger.verbose("DB Configuration read from file {}".format(config_path)) if config_path.exists(): with open(config_path, "r") as f: config = yaml.safe_load(f) db_name = config.get('dbname', None) db_user = config.get('dbuser', None) db_pass = config.get('dbpass', None) if db_name is None: logger.debug("Falling back to default DB name {}".format(constants.DEFAULT_DB_NAME)) db_name = constants.DEFAULT_DB_NAME if db_user is None: logger.debug("Falling back to default DB user {}".format(constants.DEFAULT_DB_USER)) db_user = constants.DEFAULT_DB_USER if db_pass is None: logger.debug("Falling back to default DB pass {}".format(constants.DEFAULT_DB_PASS)) db_pass = constants.DEFAULT_DB_PASS logger.debug("Read config values (dbname={}, dbuser={}, dbpass={})".format(db_name, db_user, db_pass)) return DBConfig(db_name, db_user, db_pass) else: logger.info( "No configuration file for database connection found, falling back to default values " "(dbname={}, dbuser={}, dbpass={}).".format( constants.DEFAULT_DB_NAME, constants.DEFAULT_DB_USER, constants.DEFAULT_DB_PASS ) ) logger.info( "Note: To turn off this message, create a config file at {}".format(config_path) ) return DBConfig(constants.DEFAULT_DB_NAME, constants.DEFAULT_DB_USER, constants.DEFAULT_DB_PASS)