From 7677b6859e171331ba27be9e78d07deedc7f189b Mon Sep 17 00:00:00 2001 From: shortcutme Date: Mon, 7 Nov 2016 22:51:43 +0100 Subject: [PATCH] Move config file modification to Config class --- src/Config.py | 31 +++++++++++++++++++++++++++++++ src/Ui/UiWebsocket.py | 31 +------------------------------ 2 files changed, 32 insertions(+), 30 deletions(-) diff --git a/src/Config.py b/src/Config.py index 2e813bb6..2e4938e4 100644 --- a/src/Config.py +++ b/src/Config.py @@ -303,5 +303,36 @@ class Config(object): ConfigPlugin(self) + def saveValue(self, key, value): + if not os.path.isfile(self.config_file): + content = "" + else: + content = open(self.config_file).read() + lines = content.splitlines() + + global_line_i = None + key_line_i = None + i = 0 + for line in lines: + if line.strip() == "[global]": + global_line_i = i + if line.startswith(key + " = "): + key_line_i = i + i += 1 + + if value is None: # Delete line + if key_line_i: + del lines[key_line_i] + else: # Add / update + new_line = "%s = %s" % (key, str(value).replace("\n", "").replace("\r", "")) + if key_line_i: # Already in the config, change the line + lines[key_line_i] = new_line + elif global_line_i is None: # No global section yet, append to end of file + lines.append("[global]") + lines.append(new_line) + else: # Has global section, append the line after it + lines.insert(global_line_i + 1, new_line) + + open(self.config_file, "w").write("\n".join(lines)) config = Config(sys.argv) diff --git a/src/Ui/UiWebsocket.py b/src/Ui/UiWebsocket.py index 857b9e57..4a6f1c19 100644 --- a/src/Ui/UiWebsocket.py +++ b/src/Ui/UiWebsocket.py @@ -712,34 +712,5 @@ class UiWebsocket(object): self.response(to, "denied") return - if not os.path.isfile(config.config_file): - content = "" - else: - content = open(config.config_file).read() - lines = content.splitlines() - - global_line_i = None - key_line_i = None - i = 0 - for line in lines: - if line.strip() == "[global]": - global_line_i = i - if line.startswith(key + " = "): - key_line_i = i - i += 1 - - if value is None: # Delete line - if key_line_i: - del lines[key_line_i] - else: # Add / update - new_line = "%s = %s" % (key, value.replace("\n", "").replace("\r", "")) - if key_line_i: # Already in the config, change the line - lines[key_line_i] = new_line - elif global_line_i is None: # No global section yet, append to end of file - lines.append("[global]") - lines.append(new_line) - else: # Has global section, append the line after it - lines.insert(global_line_i + 1, new_line) - - open(config.config_file, "w").write("\n".join(lines)) + config.saveValue(key, value) self.response(to, "ok")