diff options
Diffstat (limited to 'alot/helper.py')
-rw-r--r-- | alot/helper.py | 36 |
1 files changed, 36 insertions, 0 deletions
diff --git a/alot/helper.py b/alot/helper.py index 91aae324..b096df41 100644 --- a/alot/helper.py +++ b/alot/helper.py @@ -17,6 +17,9 @@ from twisted.internet.protocol import ProcessProtocol from twisted.internet.defer import Deferred import StringIO import logging +from configobj import ConfigObj, ConfigObjError, flatten_errors, Section +from validate import Validator +from alot.errors import ConfigError def safely_get(clb, E, on_error=''): @@ -396,3 +399,36 @@ def humanize_size(size): if size / factor < 1024: return format_string % (float(size) / factor) return format_string % (size / factor) + + +def read_config(configpath=None, specpath=None): + """ + 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 + :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() + 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 |