xenu_nntp/lib/xenu_nntp/config.py
2024-12-30 20:54:09 -05:00

78 lines
1.9 KiB
Python

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 ConfigOptionException(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(configparser.ConfigParser):
SEARCH_PATHS = [
'./server.conf',
'/usr/local/etc/xenu-nntp/server.conf',
'/etc/xenu-nntp/server.conf'
]
@staticmethod
def find():
for path in Config.SEARCH_PATHS:
if os.path.exists(path):
return path
return None
@staticmethod
def load(path: Optional[str]=None):
if path is None:
path = Config.find()
if path is None:
raise ConfigFileException(Config.SEARCH_PATHS)
config = Config()
config.read(path)
return config
def section(self, section: str):
if not self.has_section(section):
raise ConfigSectionException(section)
return self[section]
def get(self, section: str, option: str, *args, **kwargs):
if not self.has_section(section):
raise ConfigSectionException(section)
if not self.has_option(section, option):
raise ConfigOptionException(section, option)
return super().get(section, option, *args, **kwargs)