From 665a3da99748f698b72a84be74761cc937ab7f4e Mon Sep 17 00:00:00 2001 From: XANTRONIX Industrial Date: Thu, 3 Apr 2025 23:22:40 -0400 Subject: [PATCH] Improve config class --- lib/xmet/config.py | 55 ++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 48 insertions(+), 7 deletions(-) diff --git a/lib/xmet/config.py b/lib/xmet/config.py index dde6fe2..3b218dd 100644 --- a/lib/xmet/config.py +++ b/lib/xmet/config.py @@ -4,22 +4,48 @@ 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 = ( + SEARCH_PATHS = [ './xmet.conf', os.environ['HOME'] + '/.xmet.conf', - '/etc/xmet/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.isfile(path): + if os.path.exists(path): return path @staticmethod @@ -28,9 +54,24 @@ class Config(configparser.ConfigParser): path = Config.find() if path is None: - raise ConfigFileException("Could not locate xmet configuration file") + 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)