Source

tutagx / tutagx / config.py

Full commit
import os
import logging
from tutagx.meta import to_yaml, from_yaml, model
# We have a circular dependency here, as ttg_path is used to find the config
# file to load, but ttg_path also needs ttg_config for some functions (nothing
# we access from here, so no real problem).
# Thus we import it in load() where it is needed.
#import tutagx.util.path as ttg_path
from tutagx.meta import validate

__all__ = ['get', 'set', 'load', 'save']

log = logging.getLogger(__name__)


class Config(model.Model):
    is_value_type = True
    # These paths are intended to be cross-platform. Both / and \ are accepted
    # as seperator, and on use they are transformed to use the one the
    # underlying platform uses.
    core_asset_dir = model.String()
    gameset_dir = model.String()
    savegame_dir = model.String()
    language = model.String()

_CONFIG_OBJ = None
_CONFIG_LOADER = from_yaml.YAMLReader(Config)


def get(attr):
    return getattr(_CONFIG_OBJ, attr)


def set(attr, val):
    setattr(_CONFIG_OBJ, attr, val)


def load():
    # global state, ugh. But then again, YAGNI...
    global _CONFIG_OBJ
    import tutagx.util.path as ttg_path
    config_path = ttg_path.below_home('config.yaml')
    with open(config_path) as f:
        obj, errors = _CONFIG_LOADER.load(f)
    if errors:
        log.error('Configuration file is invalid:')
        for line in validate.format_errors(errors):
            log.error('%s', line)
        raise RuntimeError('config.yaml is invalid')
    _CONFIG_OBJ = obj


def save():
    config_path = ttg_path.below_home('config.yaml')
    with open(config_path, 'w') as f:
        to_yaml.YAMLWriter(Config).dump(_CONFIG_OBJ, f)