From 3bf87222fdd62a8de58a52afd8302f44b0c95ba8 Mon Sep 17 00:00:00 2001 From: Benjamin Renard Date: Fri, 13 May 2022 14:47:01 +0200 Subject: [PATCH] config: start adding support of multiline values --- mylib/config.py | 39 ++++++++++++++++++++++++++------------- 1 file changed, 26 insertions(+), 13 deletions(-) diff --git a/mylib/config.py b/mylib/config.py index 2cb6651..b592232 100644 --- a/mylib/config.py +++ b/mylib/config.py @@ -189,7 +189,7 @@ class BaseOption: # pylint: disable=too-many-instance-attributes """ Export option to configuration file """ lines = [] if self.comment: - lines.append('# ' + self.comment) + lines.append(f'# {self.comment}') value = self.to_config() default_value = ( '' if self.default is None else @@ -199,28 +199,41 @@ class BaseOption: # pylint: disable=too-many-instance-attributes 'export_to_config(%s, %s): value=%s / default=%s', self.section.name, self.name, value, default_value) if default_value: - lines.append( - '# Default: %s' % default_value - ) + if isinstance(default_value, str) and '\n' in default_value: + lines.append('# Default:') + lines.extend([f'# {line}' for line in default_value.split('\n')]) + else: + lines.append( + f'# Default: {default_value}' + ) if value and value != default_value: - lines.append( - '%s = %s' % - (self.name, value) - ) + if isinstance(value, str) and '\n' in value: + value_lines = value.split('\n') + lines.append(f'# Default: {value_lines[0]}') + lines.extend([f' {line.replace("#", "%(hash)s")}' for line in value_lines[1:]]) + else: + lines.append( + f'{self.name} = {value}' + ) else: - lines.append('# %s =' % self.name) + lines.append(f'# {self.name} =') lines.append('') return '\n'.join(lines) def _ask_value(self, prompt=None, **kwargs): """ Ask to user to enter value of this option and return it """ if self.comment: - print('# ' + self.comment) + print(f'# {self.comment}') default_value = kwargs.get('default_value', self.get()) if not prompt: - prompt = "%s: " % self.name + prompt = f'{self.name}: ' if default_value is not None: - prompt += "[%s] " % self.to_config(default_value) + if isinstance(default_value, str) and '\n' in default_value: + prompt += "[\n %s\n] " % "\n ".join( + self.to_config(default_value).split('\n') + ) + else: + prompt += f'[{self.to_config(default_value)}] ' value = input(prompt) return default_value if value == '' else value @@ -646,7 +659,7 @@ class Config: # pylint: disable=too-many-instance-attributes def load_file(self, filepath, execute_callback=True): """ Read configuration file """ - self.config_parser = ConfigParser() + self.config_parser = ConfigParser(defaults={'hash': '#'}) self._filepath = filepath # Checking access of configuration file