Improve config class
This commit is contained in:
parent
803e26510b
commit
665a3da997
1 changed files with 48 additions and 7 deletions
|
@ -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)
|
||||
|
|
Loading…
Add table
Reference in a new issue