3 from __future__ import print_function
6 from ConfigParser import RawConfigParser, NoSectionError, NoOptionError
7 except ImportError: # py3
8 from configparser import RawConfigParser, NoSectionError, NoOptionError
11 __all__ = ['get_config']
14 def _find_config_dirs_posix():
16 if 'XDG_CONFIG_HOME' in os.environ:
17 config_dirs.append(os.environ['XDG_CONFIG_HOME'])
18 if 'XDG_CONFIG_DIRS' in os.environ:
19 config_dirs.extend(os.environ['XDG_CONFIG_DIRS'].split(':'))
20 home_config = os.path.expanduser('~/.config')
21 if home_config not in config_dirs:
22 config_dirs.append(home_config)
26 def find_config_dirs():
27 if os.name == 'posix':
28 return _find_config_dirs_posix()
32 def find_config_file(config_dirs=None):
33 if config_dirs is None:
34 config_dirs = find_config_dirs()
36 ml_conf_file = os.path.join(d, 'm_librarian.conf')
37 if os.path.exists(ml_conf_file):
46 class ConfigWrapper(object):
47 def __init__(self, config):
50 def get(self, section, option, default=None):
52 return self.config.get(section, option)
53 except (NoSectionError, NoOptionError):
56 def set(self, section, option, value):
57 self.config.set(section, option, value)
59 def getint(self, section, option, default=0):
61 return self.config.getint(section, option)
62 except (NoSectionError, NoOptionError):
64 # Do not catch ValueError here, it must be propagated
66 def getpath(self, section, option, default=os.path.curdir):
67 path = self.get(section, option, default=default)
68 return os.path.expanduser(os.path.expandvars(path))
71 def get_config(config_path=None):
73 if _ml_config is None:
74 _ml_config = RawConfigParser()
75 if config_path is None:
76 config_path = find_config_file()
77 if config_path is not None:
78 _ml_config.read(config_path)
79 _ml_config = ConfigWrapper(_ml_config)
84 config_dirs = find_config_dirs()
85 print("Config dirs:", config_dirs)
86 print("Config file:", find_config_file(config_dirs))
89 if __name__ == '__main__':