summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorPatrick Totzke <patricktotzke@gmail.com>2012-02-18 10:35:14 +0000
committerPatrick Totzke <patricktotzke@gmail.com>2012-02-18 10:35:14 +0000
commit5e5fe4553852bd9360fcb98ba80d3103836506c6 (patch)
tree36dd188980847840fe970884e09065b18f45458f
parent9bfa8b4e643975c2b9798310827c3f42a48c0a22 (diff)
read and validate configs via configobj
-rw-r--r--alot/settings.py29
1 files changed, 29 insertions, 0 deletions
diff --git a/alot/settings.py b/alot/settings.py
index d88b5be0..0f1a627b 100644
--- a/alot/settings.py
+++ b/alot/settings.py
@@ -6,10 +6,39 @@ import json
import mailcap
import codecs
import logging
+from configobj import ConfigObj, ConfigObjError, flatten_errors, Section
+from validate import Validator
from collections import OrderedDict
from ConfigParser import SafeConfigParser, ParsingError, NoOptionError
+DEFAULTSPATH = os.path.join(os.path.dirname(__file__), 'defaults')
+
+class ConfigError(Exception):
+ pass
+
+def read_config(configpath=None, specpath=None):
+ try:
+ config = ConfigObj(infile=configpath, configspec=specpath, file_error=True)
+ 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" was missing' % ', '.join(section_list)
+ error_msg += msg + '\n'
+ raise ConfigError(error_msg)
+ return config
+
class FallbackConfigParser(SafeConfigParser):
""":class:`~ConfigParser.SafeConfigParser` that allows fallback values"""