2024-03-29 21:48:06 +01:00
|
|
|
import configparser
|
|
|
|
import os
|
|
|
|
|
|
|
|
|
|
|
|
class Conf(object):
|
|
|
|
_confobj = configparser.ConfigParser(os.environ)
|
|
|
|
_cfgfiles = []
|
|
|
|
debug = None
|
|
|
|
|
2024-03-30 00:24:55 +01:00
|
|
|
def __init__(self, filename=None, debug=None, force_filename=False):
|
2024-03-29 21:48:06 +01:00
|
|
|
if debug:
|
|
|
|
self.set_debug(debug)
|
|
|
|
filenames = []
|
|
|
|
if filename:
|
|
|
|
filenames.append(filename)
|
2024-03-30 00:24:55 +01:00
|
|
|
if not force_filename:
|
|
|
|
filenames.append(f'{os.environ.get("HOME")}/etc/userconfig2.conf')
|
2024-03-29 21:48:06 +01:00
|
|
|
ret = self.set_filenames(filenames)
|
|
|
|
if not ret:
|
|
|
|
raise ValueError(f'Cannot open either configuration file: {",".join(filenames)}')
|
|
|
|
|
|
|
|
def set_debug(self, debug):
|
|
|
|
self.debug = debug
|
|
|
|
|
|
|
|
def set_filenames(self, filenames):
|
|
|
|
ret = self._confobj.read(filenames)
|
|
|
|
if len(ret) == 0:
|
|
|
|
return None
|
|
|
|
if self.debug:
|
|
|
|
self.debug.stdout("Read config files: %s" % ", ".join(filenames), 2)
|
|
|
|
return ret
|
|
|
|
|
|
|
|
def get(self, option, boolean=False, section='userconfig'):
|
|
|
|
try:
|
|
|
|
if boolean:
|
|
|
|
return self._confobj.getboolean(section, option)
|
|
|
|
else:
|
|
|
|
return self._confobj.get(section, option)
|
|
|
|
except (configparser.NoOptionError, configparser.NoOptionError) as e:
|
|
|
|
raise ValueError(f'Option {option} does not exist in section {section}: {e}')
|
|
|
|
|
|
|
|
def set(self, option, value, section='userconfig'):
|
|
|
|
try:
|
|
|
|
self._confobj.set(section, option, value)
|
|
|
|
except configparser.NoSectionError as e:
|
|
|
|
raise ValueError(f'Section {section} does not exist: {e}')
|
|
|
|
|
|
|
|
def get_items(self, section='userconfig'):
|
|
|
|
try:
|
|
|
|
return self._confobj.items(section)
|
|
|
|
except configparser.NoSectionError as e:
|
|
|
|
raise ValueError(f'Section {section} does not exist: {e}')
|
|
|
|
|
|
|
|
def check(self, option, section='userconfig'):
|
|
|
|
return self._confobj.has_option(section, option)
|
|
|
|
|
|
|
|
def sections(self):
|
|
|
|
return self._confobj.sections()
|