From 1233ff2fd99382c26e26de534772701c0ad5d1b5 Mon Sep 17 00:00:00 2001 From: Adrien Vannson Date: Wed, 15 Jan 2025 15:19:50 +0100 Subject: [PATCH] Write invalid generated code to a file --- src/betterproto2_compiler/plugin/compiler.py | 24 +++++++++++++------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/src/betterproto2_compiler/plugin/compiler.py b/src/betterproto2_compiler/plugin/compiler.py index 90e2ac8b..c35697e7 100644 --- a/src/betterproto2_compiler/plugin/compiler.py +++ b/src/betterproto2_compiler/plugin/compiler.py @@ -40,15 +40,23 @@ def outputfile_compiler(output_file: OutputTemplate) -> str: code = body_template.render(output_file=output_file) code = header_template.render(output_file=output_file, version=version) + "\n" + code - # Sort imports, delete unused ones - code = subprocess.check_output( - ["ruff", "check", "--select", "I,F401,TCH005", "--fix", "--silent", "-"], - input=code, - encoding="utf-8", - ) + try: + # Sort imports, delete unused ones + code = subprocess.check_output( + ["ruff", "check", "--select", "I,F401,TCH005", "--fix", "--silent", "-"], + input=code, + encoding="utf-8", + ) + + # Format the code + code = subprocess.check_output(["ruff", "format", "-"], input=code, encoding="utf-8") + except subprocess.CalledProcessError: + with open("invalid-generated-code.py", "w") as f: + f.write(code) - # Format the code - code = subprocess.check_output(["ruff", "format", "-"], input=code, encoding="utf-8") + raise SyntaxError( + f"Can't format the source code:\nThe invalid generated code has been written in `invalid-generated-code.py`" + ) # Validate the generated code. validator = ModuleValidator(iter(code.splitlines()))