Config: make the configparser always defined to allow to set options at any moment

This commit is contained in:
Benjamin Renard 2023-01-10 10:48:57 +01:00
parent e9477b1566
commit 5fefc1ed84

View file

@ -70,7 +70,7 @@ class BaseOption: # pylint: disable=too-many-instance-attributes
def _isset_in_config_file(self): def _isset_in_config_file(self):
""" Check if option is defined in the loaded configuration file """ """ Check if option is defined in the loaded configuration file """
return ( return (
self.config.config_parser self.config.config_filepath
and self.config.config_parser.has_option(self.section.name, self.name) and self.config.config_parser.has_option(self.section.name, self.name)
) )
@ -100,13 +100,10 @@ class BaseOption: # pylint: disable=too-many-instance-attributes
return self.default return self.default
def set(self, value): def set(self, value):
""" Set option value to config file """ """ Set option value to config file and options """
assert self.config.config_parser or (self.config.options and not self.no_arg), (
"Can't set option value: configuration file not configured, not options (or no argument)")
if value == '': if value == '':
value = None value = None
if self.config.config_parser:
if value == self.default or value is None: if value == self.default or value is None:
# Remove option from config (is section exists) # Remove option from config (is section exists)
if self.config.config_parser.has_section(self.section.name): if self.config.config_parser.has_section(self.section.name):
@ -622,6 +619,7 @@ class Config: # pylint: disable=too-many-instance-attributes
self._filepath = None self._filepath = None
self.config_file_env_variable = config_file_env_variable self.config_file_env_variable = config_file_env_variable
self.default_config_dirpath = default_config_dirpath self.default_config_dirpath = default_config_dirpath
self._init_config_parser()
def add_section(self, name, loaded_callback=None, **kwargs): def add_section(self, name, loaded_callback=None, **kwargs):
""" """
@ -638,7 +636,7 @@ class Config: # pylint: disable=too-many-instance-attributes
if loaded_callback: if loaded_callback:
self._loaded_callbacks.append(loaded_callback) self._loaded_callbacks.append(loaded_callback)
# If configuration is already loaded, execute callback immediatly # If configuration is already loaded, execute callback immediatly
if self.config_parser or self.options: if self._filepath or self.options:
self._loaded() self._loaded()
return self.sections[name] return self.sections[name]
@ -652,7 +650,6 @@ class Config: # pylint: disable=too-many-instance-attributes
def get(self, section, option): def get(self, section, option):
""" Get option value """ """ Get option value """
assert self.config_parser or self.options, 'Unconfigured options parser'
assert self.defined( assert self.defined(
section, option), f'Unknown option {section}.{option}' section, option), f'Unknown option {section}.{option}'
value = self.sections[section].get(option) value = self.sections[section].get(option)
@ -666,21 +663,24 @@ class Config: # pylint: disable=too-many-instance-attributes
return default return default
def __getitem__(self, key): def __getitem__(self, key):
assert self.config_parser or self.options, 'Unconfigured options parser'
assert key in self.sections, f'Unknown section {key}' assert key in self.sections, f'Unknown section {key}'
return ConfigSectionAsDictWrapper(self.sections[key]) return ConfigSectionAsDictWrapper(self.sections[key])
def set(self, section, option, value): def set(self, section, option, value):
""" Set option value """ """ Set option value """
assert self.config_parser, 'Unconfigured options parser'
assert self.defined( assert self.defined(
section, option), f'Unknown option {section}.{option}' section, option), f'Unknown option {section}.{option}'
self._init_config_parser()
self.sections[section].set(option, value) self.sections[section].set(option, value)
def _init_config_parser(self, force=False):
""" Initialize ConfigParser object """
if not self.config_parser or force:
self.config_parser = ConfigParser(defaults={'hash': '#'})
def load_file(self, filepath, execute_callback=True): def load_file(self, filepath, execute_callback=True):
""" Read configuration file """ """ Read configuration file """
self._init_config_parser(force=True)
self.config_parser = ConfigParser(defaults={'hash': '#'})
self._filepath = filepath self._filepath = filepath
# Checking access of configuration file # Checking access of configuration file
@ -693,7 +693,7 @@ class Config: # pylint: disable=too-many-instance-attributes
try: try:
self.config_parser.read(filepath, encoding=self.encoding) self.config_parser.read(filepath, encoding=self.encoding)
except Exception: # pylint: disable=broad-except except Exception: # pylint: disable=broad-except
self.config_parser = None self._init_config_parser(force=True)
log.exception('Failed to read configuration file %s', filepath) log.exception('Failed to read configuration file %s', filepath)
return False return False
@ -953,9 +953,6 @@ class Config: # pylint: disable=too-many-instance-attributes
section and their options value. section and their options value.
:rtype: bool of dict :rtype: bool of dict
""" """
# On set it mode, ensure configuration file parser is initialized
if set_it and not self.config_parser:
self.config_parser = ConfigParser()
result = {} result = {}
error = False error = False
for name, section in self.sections.items(): for name, section in self.sections.items():