X-Git-Url: https://git.phdru.name/?a=blobdiff_plain;f=m_librarian%2Fconfig.py;h=b4a7b603d23d0fe06c4c693fb5081f0b29f9b6ad;hb=18f8a04ae9135d026a4db5548f80b00e40b763e0;hp=04e64e0c9f99e8aa949e1500eb69d1e15b28bdae;hpb=d6ef04787834ffeded257d96af4c965ca7055a51;p=m_librarian.git diff --git a/m_librarian/config.py b/m_librarian/config.py index 04e64e0..b4a7b60 100755 --- a/m_librarian/config.py +++ b/m_librarian/config.py @@ -1,7 +1,12 @@ #! /usr/bin/env python +from __future__ import print_function import os -from ConfigParser import SafeConfigParser +try: + from ConfigParser import RawConfigParser, NoSectionError, NoOptionError +except ImportError: # py3 + from configparser import RawConfigParser, NoSectionError, NoOptionError + __all__ = ['get_config'] @@ -21,7 +26,7 @@ def _find_config_dirs_posix(): def find_config_dirs(): if os.name == 'posix': return _find_config_dirs_posix() - raise OSError("Unknow OS") + return None def find_config_file(config_dirs=None): @@ -32,21 +37,62 @@ def find_config_file(config_dirs=None): if os.path.exists(ml_conf_file): return ml_conf_file else: - raise IOError("Cannot find m_librarian.conf in %s" % config_dirs) + return None + + +_ml_config = None + + +class ConfigWrapper(object): + def __init__(self, config): + self.config = config + + def get(self, section, option, default=None): + try: + return self.config.get(section, option) + except (NoSectionError, NoOptionError): + return default + def set(self, section, option, value): + self.config.set(section, option, value) -def get_config(config_filename=None): - if config_filename is None: - config_filename = find_config_file() - ml_conf = SafeConfigParser() - ml_conf.read(config_filename) - return ml_conf + def getint(self, section, option, default=0): + try: + return self.config.getint(section, option) + except (NoSectionError, NoOptionError): + return default + # Do not catch ValueError here, it must be propagated + + def getlist(self, section, option, default=None, sep=None): + value = self.get(section, option) + if not value: + if default is None: + return [] + return default + return value.split(sep) + + def getpath(self, section, option, default=os.path.curdir): + path = self.get(section, option, default=default) + return os.path.expanduser(os.path.expandvars(path)) + + +def get_config(config_path=None): + global _ml_config + if _ml_config is None: + _ml_config = RawConfigParser() + if config_path is None: + config_path = find_config_file() + if config_path is not None: + _ml_config.read(config_path) + _ml_config = ConfigWrapper(_ml_config) + return _ml_config def test(): config_dirs = find_config_dirs() - print "Config dirs:", config_dirs - print "Config file:", find_config_file(config_dirs) + print("Config dirs:", config_dirs) + print("Config file:", find_config_file(config_dirs)) + if __name__ == '__main__': test()