From 97f8bb9a72cca124ab0928fc2eb14bc1458e87a5 Mon Sep 17 00:00:00 2001 From: Patrick Totzke Date: Sun, 11 Mar 2012 19:00:59 +0000 Subject: forgot to add missing settings.utils.py --- alot/settings/utils.py | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 alot/settings/utils.py (limited to 'alot/settings') diff --git a/alot/settings/utils.py b/alot/settings/utils.py new file mode 100644 index 00000000..613ece17 --- /dev/null +++ b/alot/settings/utils.py @@ -0,0 +1,41 @@ +from configobj import ConfigObj, ConfigObjError, flatten_errors +from validate import Validator +from errors import ConfigError + + +def read_config(configpath=None, specpath=None, checks={}): + """ + get a (validated) config object for given config file path. + + :param configpath: path to config-file + :type configpath: str + :param specpath: path to spec-file + :type specpath: str + :param checks: custom checks to use for validator. + see `validate docs `_ + :type checks: dict str->callable, + :raises: :class:`~alot.settings.errors.ConfigError` + :rtype: `configobj.ConfigObj` + """ + try: + config = ConfigObj(infile=configpath, configspec=specpath, + file_error=True, encoding='UTF8') + except (ConfigObjError, IOError), e: + raise ConfigError('Could not read "%s": %s' % (configpath, e)) + + if specpath: + validator = Validator() + validator.functions.update(checks) + results = config.validate(validator) + + if results != True: + error_msg = 'Validation errors occurred:\n' + for (section_list, key, _) in flatten_errors(config, results): + if key is not None: + msg = 'key "%s" in section "%s" failed validation' + msg = msg % (key, ', '.join(section_list)) + else: + msg = 'section "%s" is malformed' % ', '.join(section_list) + error_msg += msg + '\n' + raise ConfigError(error_msg) + return config -- cgit v1.2.3