From ac14858e85cfee06c1e19843b92d50e38bc969dd Mon Sep 17 00:00:00 2001 From: Joerg Bornemann Date: Wed, 8 Jul 2020 10:32:03 +0200 Subject: configurejson2cmake: Use a context manager for file special handling One can now write with special_cased_file("base/dir", "foo.txt") as fh: do_something(fh) This makes the code of processJson a bit clearer, and it allows us to easily add more files that support the special handling comments. Change-Id: Ia25d0c0d48df1802c5e2123d05345a88b42a2981 Reviewed-by: Alexandru Croitor --- util/cmake/configurejson2cmake.py | 34 +++++++++++++++++++++------------- 1 file changed, 21 insertions(+), 13 deletions(-) (limited to 'util') diff --git a/util/cmake/configurejson2cmake.py b/util/cmake/configurejson2cmake.py index e2e3890364..fdab8aba1c 100755 --- a/util/cmake/configurejson2cmake.py +++ b/util/cmake/configurejson2cmake.py @@ -1354,6 +1354,26 @@ def processSubconfigs(path, ctx, data): subconfCtx = ctx processJson(subconfDir, subconfCtx, subconfData) +class special_cased_file: + def __init__(self, base_dir : str, file_name : str): + self.base_dir = base_dir + self.file_path = posixpath.join(base_dir, file_name) + self.gen_file_path = self.file_path + ".gen" + + def __enter__(self): + self.file = open(self.gen_file_path, "w") + self.sc_handler = SpecialCaseHandler( + os.path.abspath(self.file_path), + os.path.abspath(self.gen_file_path), + os.path.abspath(self.base_dir), + debug=False, + ) + return self.file + + def __exit__(self, type, value, trace_back): + self.file.close() + if self.sc_handler.handle_special_cases(): + os.replace(self.gen_file_path, self.file_path) def processJson(path, ctx, data): ctx["project_dir"] = path @@ -1362,9 +1382,7 @@ def processJson(path, ctx, data): ctx = processFiles(ctx, data) - destination = posixpath.join(path, "configure.cmake") - generated_file = destination + '.gen' - with open(generated_file, "w") as cm_fh: + with special_cased_file(path, "configure.cmake") as cm_fh: cm_fh.write("\n\n#### Inputs\n\n") processInputs(ctx, data, cm_fh) @@ -1394,16 +1412,6 @@ def processJson(path, ctx, data): # do this late: processSubconfigs(path, ctx, data) - handler = SpecialCaseHandler( - os.path.abspath(destination), - os.path.abspath(generated_file), - os.path.abspath(path), - debug=False, - ) - if handler.handle_special_cases(): - os.replace(generated_file, destination) - - def main(): if len(sys.argv) != 2: print("This scripts needs one directory to process!") -- cgit v1.2.3