~sthagen/muuntaa#2: 
Proposed implementaion for a configuration handler (boolify/load/eject/)

Assuming the configuration file is mooved to resource/config.yml:

"""Handling functions for configuration resources."""
import logging
import pathlib
import pkgutil
from typing import Iterable, Union

import yaml

Pathlike = Union[pathlib.Path, str]
LogLevel = int
ScopedMessage = tuple[LogLevel, str]
ConfigType = dict[str, Union[None, bool, int, float, str]]
BOOLEAN_KEYS = ('force', 'fix_insert_current_version_into_revision_history')
CONFIG_RESOURCE = 'resource/config.yml'
ENCODING = 'utf-8'


def boolify(configuration: ConfigType, boolean_keys: Iterable[str] = BOOLEAN_KEYS) -> list[ScopedMessage]:
    """Modify configuration in place toe nsure typical string like boolish representations are stored as booleans."""
    scoped_messages = []
    for key in boolean_keys:
        try:
            incoming = configuration[key]
        except KeyError as err:
            scoped_messages.append(
                (logging.CRITICAL, f'Reading config.yaml failed. Missing config key {key}: {err}.'),
            )
            continue

        try:
            if isinstance(incoming, bool):
                configuration[key] = incoming
                continue
            if incoming.strip().lower() in {'true', 'yes', '1', 'y'}:
                configuration[key] = True
                continue
            if incoming.strip().lower() in {'false', 'no', '0', 'n'}:
                configuration[key] = False
                continue
            raise ValueError('unexpected value')
        except (AttributeError, ValueError) as err:
            scoped_messages.append(
                (
                    logging.CRITICAL,
                    f'Reading config.yaml failed. Invalid value for config key {key}: {incoming} {err}.'
                ),
            )

    return scoped_messages


def load(external_path: Union[None, Pathlike] = None) -> ConfigType:
    """Load the configuration either from the package resources (default) or an external path."""
    if external_path:
        with open(external_path, 'rt', encoding=ENCODING) as handle:
            return yaml.safe_load(handle)
    else:
        return yaml.safe_load(pkgutil.get_data(__package__, CONFIG_RESOURCE).decode(encoding=ENCODING))  # type: ignore


def eject() -> str:
    """Dump the configuration from the package resources to a YAML string."""
    return pkgutil.get_data(__package__, CONFIG_RESOURCE).decode(encoding=ENCODING)  # type: ignore
Status
REPORTED
Submitter
~sthagen
Assigned to
Submitted
6 months ago
Updated
6 months ago
Labels
Feature