From 642e2dee577ae904615418e4fb87b75768f2db53 Mon Sep 17 00:00:00 2001 From: milahu Date: Thu, 21 May 2026 09:37:28 +0200 Subject: [PATCH] Improve Jinja template error reporting by including the line number and context of the error --- conda_build/metadata.py | 20 +++++++++++++++++++- news/pull-5985.md | 3 +++ 2 files changed, 22 insertions(+), 1 deletion(-) create mode 100644 news/pull-5985.md diff --git a/conda_build/metadata.py b/conda_build/metadata.py index 54961d0b47..72d735276f 100644 --- a/conda_build/metadata.py +++ b/conda_build/metadata.py @@ -2094,9 +2094,27 @@ def _get_contents( except jinja2.TemplateError as ex: if "'None' has not attribute" in str(ex): ex = "Failed to run jinja context function" + raise CondaBuildUserError( + f"Failed to render jinja template in {self.meta_path}:\n{str(ex)}" + ) + if not isinstance(ex, jinja2.TemplateSyntaxError): + # TODO handle other error types? + raise CondaBuildUserError( + f"Failed to render jinja template in {self.meta_path}:\n" + f"{type(ex).__name__}: {str(ex)}\n" + ) + error_line = ex.source.splitlines()[ex.lineno - 1] + source_lines = list(enumerate(ex.source.splitlines())) + context_size = 3 + error_context_lines = source_lines[(ex.lineno - 1 - context_size):(ex.lineno + context_size)] + lineno_width = len(str(error_context_lines[-1][0] + 1)) + error_context_str = "\n".join(map(lambda L: f"{str(L[0] + 1).zfill(lineno_width)}: {L[1]}", error_context_lines)) raise CondaBuildUserError( - f"Failed to render jinja template in {self.meta_path}:\n{str(ex)}" + f"Failed to render jinja template in {self.meta_path}:\n" + f"{type(ex).__name__}: {str(ex)} in line {ex.lineno}\n" + + error_context_str ) + finally: if "CONDA_BUILD_STATE" in os.environ: del os.environ["CONDA_BUILD_STATE"] diff --git a/news/pull-5985.md b/news/pull-5985.md new file mode 100644 index 0000000000..9d5ddcab30 --- /dev/null +++ b/news/pull-5985.md @@ -0,0 +1,3 @@ +### Enhancements + +* Improve Jinja template error reporting by including the line number and context of the error