xmet/lib/xmet/config.py

77 lines
2 KiB
Python

import os
import configparser
from typing import Optional, Self
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 = [
'./xmet.conf',
os.environ['HOME'] + '/.xmet.conf',
'/usr/local/etc/xmet/xmet.conf',
'/etc/xmet/xmet.conf'
]
@staticmethod
def find() -> str:
for path in Config.SEARCH_PATHS:
if os.path.exists(path):
return path
@staticmethod
def load(path: Optional[str]=None) -> Self:
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)