From 3ee87bbb12624a877b04bf697bd1a419a5719563 Mon Sep 17 00:00:00 2001 From: Marcus Stoegbauer Date: Sat, 27 Jul 2024 19:47:25 +0200 Subject: [PATCH] add new diff function --- userconfig/__init__.py | 33 ++++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/userconfig/__init__.py b/userconfig/__init__.py index 0804832..c13db7c 100644 --- a/userconfig/__init__.py +++ b/userconfig/__init__.py @@ -173,6 +173,7 @@ class Userconfig: ret.set(section="Main", option="dest", value=ret.get(section="Main", option="dest")+"/") return ret + # FIXME remove, unused now @staticmethod def read_skip_comment(fp, comment_string): """Read line from filehandle fp and skip all empty (whitespace) lines and lines starting with comment_string @@ -183,7 +184,8 @@ class Userconfig: not re.match(r"^\s+$", line)): yield line - def diff(self, dest_file, temp_file, comment_string): + # FIXME remove, unused now + def diff_old(self, dest_file, temp_file, comment_string): """diff dest_file and temp_file, returns True if files differ, False if they are the same""" self._cfg.debug.stdout(f'Diffing {dest_file} and {temp_file}, comment: {comment_string}', 3) if not os.path.isfile(dest_file): @@ -207,6 +209,35 @@ class Userconfig: self._cfg.debug.stdout(f'{dest_file} is the same as generated config', 3) return False + @staticmethod + def sanitize_input(fp, comment_string): + """Read line from filehandle fp and skip all empty (whitespace) lines and lines starting with comment_string + return result as set + """ + ret = set() + for line in fp: + line = line[:-1] + if ((comment_string != "" and not re.match("^"+re.escape(comment_string), line)) and line != "" and + not re.match(r"^\s+$", line)): + ret.add(line) + return ret + + def diff(self, dest_file, temp_file, comment_string): + """diff dest_file and temp_file, returns True if files differ, False if they are the same""" + self._cfg.debug.stdout(f'Diffing {dest_file} and {temp_file}, comment: {comment_string}', 3) + if not os.path.isfile(dest_file): + self._cfg.debug.stdout(f'dest_file {dest_file} does not exist.', 3) + return True + if not os.path.isfile(temp_file): + self._cfg.debug.stderr(f'Temporary file {temp_file} does not exist, this should not happen.', 0, 'ERROR') + sys.exit(1) + + # get temp_file and dest_file, remove comments and whitespaces + temp_lines = self.sanitize_input(open(temp_file), comment_string) + dest_lines = self.sanitize_input(open(dest_file), comment_string) + # differences of temp_file and dest_file in both directions, if > 0: files differ + return len(temp_lines.difference(dest_lines)) + len(dest_lines.difference(temp_lines)) != 0 + def user_config_generated(self, filename): """returns True if filename has been generated by userconfig, False else"""