diff --git a/scripts/generate_test_result.py b/scripts/generate_test_result.py index 5c42d40b..8a029fb2 100755 --- a/scripts/generate_test_result.py +++ b/scripts/generate_test_result.py @@ -185,23 +185,18 @@ def main(): args.sub = extr.subcategory args.base = extr.basecategory - path = util.path("test", "results", f"{args.cat}.py") - with util.open(path) as fp: - lines = fp.readlines() - LOG.info("Collecting data for '%s'", args.url) result = generate_test_result(args) - LOG.info("Writing '%s' results to '%s'", args.url, util.trim(path)) - insert_test_result(args, result, lines) - - with util.lazy(path) as fp: - fp.writelines(lines) + path = util.path("test", "results", f"{args.cat}.py") + path_tr = util.trim(path) + LOG.info("Writing '%s' results to '%s'", args.url, path_tr) + with util.lines(path) as lines: + insert_test_result(args, result, lines) if args.git: - path = util.trim(path) - LOG.info("git add %s", path) - util.git("add", "--", path) + LOG.info("git add %s", path_tr) + util.git("add", "--", path_tr) if __name__ == "__main__": diff --git a/scripts/init.py b/scripts/init.py index 98bfad63..64ac07bc 100755 --- a/scripts/init.py +++ b/scripts/init.py @@ -47,13 +47,9 @@ def init_extractor(args): LOG.info(util.trim(path)) if lines: - with util.open(path) as fp: - lines = fp.readlines() - if func(args, lines): - with util.lazy(path) as fp: - fp.writelines(lines) - else: - LOG.warning("'%s' already present", category) + with util.lines(path) as lines: + if not func(args, lines): + LOG.warning("'%s' already present", category) else: try: with util.open(path, args.open_mode) as fp: diff --git a/scripts/util.py b/scripts/util.py index 4e57d493..b077f5c9 100644 --- a/scripts/util.py +++ b/scripts/util.py @@ -64,3 +64,21 @@ class lazy(): else: # only update atime and mtime os.utime(self.path) + + +class lines(): + + def __init__(self, path, lazy=True): + self.path = path + self.lazy = lazy + self.lines = () + + def __enter__(self): + with open(self.path) as fp: + self.lines = lines = fp.readlines() + return lines + + def __exit__(self, exc_type, exc_value, traceback): + ctx = lazy(self.path) if self.lazy else open(self.path, "w") + with ctx as fp: + fp.writelines(self.lines)