2024-12-02 23:19:01 -05:00
|
|
|
import os
|
|
|
|
import configparser
|
|
|
|
|
|
|
|
from typing import Optional
|
|
|
|
|
|
|
|
class ConfigException(Exception):
|
2024-12-03 16:53:31 -05:00
|
|
|
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
|
2024-12-02 23:19:01 -05:00
|
|
|
|
|
|
|
def __str__(self):
|
2024-12-03 16:53:31 -05:00
|
|
|
return "Unable to locate configuration file in: %s" % (
|
|
|
|
", ".join(self.paths)
|
|
|
|
)
|
2024-12-02 23:19:01 -05:00
|
|
|
|
|
|
|
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:
|
2024-12-03 16:53:31 -05:00
|
|
|
raise ConfigFileException(Config.SEARCH_PATHS)
|
2024-12-02 23:19:01 -05:00
|
|
|
|
|
|
|
parser = configparser.ConfigParser()
|
|
|
|
parser.read(path)
|
|
|
|
|
|
|
|
return parser
|