import os import configparser from typing import Optional class ConfigException(Exception): pass class ConfigSectionException(ConfigException): def __init__(self, section: str): self.section = section def __str__(self): return "Missing configuration section '%s'" % ( self.section ) class ConfigValueException(ConfigException): def __init__(self, section: str, value: str): self.section = section self.value = value def __str__(self): return "Missing configuration value '%s' in section '%s'" % ( self.value, self.section ) class ConfigFileException(ConfigException): def __init__(self, paths: list): self.paths = paths def __str__(self): return "Unable to locate configuration file in: %s" % ( ", ".join(self.paths) ) class Config(): SEARCH_PATHS = [ './server.conf', '/etc/nntp-tiny/server.conf' ] @staticmethod def find(): for path in Config.SEARCH_PATHS: if os.path.exists(path): return path return None def load(path: Optional[str]=None): if path is None: path = Config.find() if path is None: raise ConfigFileException(Config.SEARCH_PATHS) parser = configparser.ConfigParser() parser.read(path) return parser