From 5a643c383b712039eacb07fbe3e746fdd8254a7f Mon Sep 17 00:00:00 2001 From: cmdr2 Date: Fri, 30 Jun 2023 13:22:23 +0530 Subject: [PATCH] Verify a newly written config file before setting that as the actual config file. Helps prevent a corrupted write from overwriting the config file --- ui/easydiffusion/app.py | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/ui/easydiffusion/app.py b/ui/easydiffusion/app.py index 5b12ff81..26bbba45 100644 --- a/ui/easydiffusion/app.py +++ b/ui/easydiffusion/app.py @@ -160,10 +160,17 @@ def setConfig(config): yaml.indent(mapping=2, sequence=4, offset=2) try: - f = open(config_yaml_path, "w", encoding="utf-8") + f = open(config_yaml_path + ".tmp", "w", encoding="utf-8") yaml.dump(config, f) finally: - f.close() # do this explicitly to avoid NUL bytes (rare bug when using 'with') + f.close() # do this explicitly to avoid NUL bytes (possible rare bug when using 'with') + + # verify that the new file is valid, and only then overwrite the old config file + # helps prevent the rare NUL bytes error from corrupting the config file + yaml = YAML() + with open(config_yaml_path + ".tmp", "r", encoding="utf-8") as f: + yaml.load(f) + shutil.move(config_yaml_path + ".tmp", config_yaml_path) except: log.error(traceback.format_exc())