diff options
author | Patrick Totzke <patricktotzke@gmail.com> | 2012-03-11 19:00:59 +0000 |
---|---|---|
committer | Patrick Totzke <patricktotzke@gmail.com> | 2012-03-11 19:00:59 +0000 |
commit | 97f8bb9a72cca124ab0928fc2eb14bc1458e87a5 (patch) | |
tree | 99cf142d4dbd14f0538d74f061572142b14810eb /alot/settings | |
parent | 2df5086930726a7a1d814f1caf1f0569c548ad33 (diff) |
forgot to add missing settings.utils.py
Diffstat (limited to 'alot/settings')
-rw-r--r-- | alot/settings/utils.py | 41 |
1 files changed, 41 insertions, 0 deletions
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 <http://www.voidspace.org.uk/python/validate.html>`_ + :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 |