From 07ab4490d224e9fdefb983a4db2cfe0d21894ca5 Mon Sep 17 00:00:00 2001 From: Benjamin Renard Date: Thu, 14 Dec 2023 17:10:34 +0100 Subject: [PATCH] config: Add OctalOption --- mylib/config.py | 53 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/mylib/config.py b/mylib/config.py index b91f4af..8efd5af 100644 --- a/mylib/config.py +++ b/mylib/config.py @@ -385,6 +385,59 @@ class IntegerOption(BaseOption): print("Invalid answer. Must a integer value") +class OctalOption(BaseOption): + """Octal configuration option class""" + + @staticmethod + def octal(value): + """Convert configuration octal string as integer""" + return int(str(value), 8) + + @staticmethod + def octal_string(value): + """Convert integer to configuration octal string""" + return oct(value)[2:] + + @property + def _from_config(self): + """Get option value from ConfigParser""" + return self.octal(self.config.config_parser.getint(self.section.name, self.name)) + + def to_config(self, value=None): + """Format value as stored in configuration file""" + value = value if value is not None else self.get() + return self.octal_string(value) if value is not None else "" + + @property + def parser_type(self): + return self.octal + + @property + def parser_help(self): + """Get option help message in arguments parser options""" + if self.arg_help and self.default is not None: + # pylint: disable=consider-using-f-string + return "{} (Default: {})".format( + self.arg_help, + re.sub(r"%([^%])", r"%%\1", self.octal_string(self._default_in_config)), + ) + if self.arg_help: + return self.arg_help + return None + + def _ask_value(self, prompt=None, **kwargs): + """Ask to user to enter value of this option and return it""" + default_value = kwargs.pop("default_value", self.get()) + while True: + value = super()._ask_value(prompt, default_value=default_value, **kwargs) + if value in ["", None, default_value]: + return default_value + try: + return self.octal(value) + except ValueError: + print("Invalid answer. Must an octal value") + + class PasswordOption(StringOption): """Password configuration option class"""