From 4962b16099c03183828a0a8fba4a0db80afbbc37 Mon Sep 17 00:00:00 2001 From: Benjamin Renard Date: Fri, 15 Dec 2023 13:15:07 +0100 Subject: [PATCH] config: fix configure() method to validate configuration only if -V/--validate parameter is provided --- mylib/config.py | 49 +++++++++++++++++++++++++++++-------------------- 1 file changed, 29 insertions(+), 20 deletions(-) diff --git a/mylib/config.py b/mylib/config.py index fad492d..f420ca7 100644 --- a/mylib/config.py +++ b/mylib/config.py @@ -798,7 +798,7 @@ class Config: # pylint: disable=too-many-instance-attributes self._loaded_callbacks_executed.append(callback) return not error - def save(self, filepath=None): + def save(self, filepath=None, reload=True): """Save configuration file""" filepath = filepath if filepath else self._filepath assert filepath, "Configuration filepath is not set or provided" @@ -828,7 +828,8 @@ class Config: # pylint: disable=too-many-instance-attributes except Exception: # pylint: disable=broad-except log.exception("Failed to write generated configuration file %s", filepath) return False - self.load_file(filepath) + if reload: + return self.load_file(filepath) return True @property @@ -1158,32 +1159,40 @@ class Config: # pylint: disable=too-many-instance-attributes options = self.parse_arguments_options(argv, create=False, execute_callback=False) + def validate(): + """Validate configuration file""" + print("Validate your configuration...") + try: + if self.load_file(options.config): + print("Your configuration seem valid.") + else: + print("Error(s) occurred validating your configuration. See logs for details.") + sys.exit(1) + except Exception: # pylint: disable=broad-except + print( + "Exception occurred validating your configuration:\n" + f"{traceback.format_exc()}" + "\n\nSee logs for details." + ) + sys.exit(2) + if os.path.exists(options.config) and not options.overwrite: - print(f"Configuration file {options.config} already exists") + print( + f"Configuration file {options.config} already exists. " + "Use -O/--overwrite parameter to overwrite it." + ) + if options.validate: + validate() + sys.exit(0) sys.exit(1) if options.interactive: self.ask_values(set_it=True) - if self.save(options.config): + if self.save(options.config, reload=False): print(f"Configuration file {options.config} created.") if options.validate: - print("Validate your configuration...") - try: - if self._loaded(): - print("Your configuration seem valid.") - else: - print( - "Error(s) occurred validating your configuration. See logs for details." - ) - sys.exit(1) - except Exception: # pylint: disable=broad-except - print( - "Exception occurred validating your configuration:\n" - f"{traceback.format_exc()}" - "\n\nSee logs for details." - ) - sys.exit(2) + validate() else: print(f"Error occured creating configuration file {options.config}") sys.exit(1)