|
| 1 | +"""Custom Jinja2 extension to include files without rendering them. |
| 2 | +
|
| 3 | +This solves the issue where GitHub Actions variables (${{ }}) conflict |
| 4 | +with Jinja2 syntax. |
| 5 | +""" |
| 6 | + |
| 7 | +from pathlib import Path |
| 8 | +from typing import TYPE_CHECKING, ClassVar |
| 9 | + |
| 10 | +from jinja2 import nodes |
| 11 | +from jinja2.ext import Extension |
| 12 | + |
| 13 | +if TYPE_CHECKING: |
| 14 | + from jinja2.parser import Parser |
| 15 | + |
| 16 | + |
| 17 | +class IncludeRawExtension(Extension): |
| 18 | + """A Jinja2 extension that adds an 'include_raw' tag to include files. |
| 19 | +
|
| 20 | + Without processing them through the Jinja2 template engine. |
| 21 | +
|
| 22 | + Usage: |
| 23 | + {% include_raw '.github/workflows/pre-commit.yml' %} |
| 24 | + """ |
| 25 | + |
| 26 | + tags: ClassVar[set[str]] = {"include_raw"} |
| 27 | + |
| 28 | + def parse(self, parser: "Parser") -> nodes.Output: |
| 29 | + # Get the tag token |
| 30 | + lineno = next(parser.stream).lineno |
| 31 | + |
| 32 | + # Parse the filename argument |
| 33 | + filename_node = parser.parse_expression() |
| 34 | + |
| 35 | + # Create a call node to our _include_raw method |
| 36 | + call_node = self.call_method("_include_raw", [filename_node]) |
| 37 | + |
| 38 | + # Return an output node |
| 39 | + return nodes.Output([call_node], lineno=lineno) |
| 40 | + |
| 41 | + def _include_raw(self, filename: str) -> str: |
| 42 | + """Read and return file contents without processing them. |
| 43 | +
|
| 44 | + Args: |
| 45 | + filename: Path to the file relative to template root |
| 46 | +
|
| 47 | + Returns: |
| 48 | + Raw file contents or error message |
| 49 | +
|
| 50 | + """ |
| 51 | + # Get the template directory from the environment |
| 52 | + template_dir_str = ( |
| 53 | + self.environment.loader.searchpath[0] |
| 54 | + if hasattr(self.environment.loader, "searchpath") |
| 55 | + else "." |
| 56 | + ) |
| 57 | + template_dir = Path(template_dir_str).resolve() |
| 58 | + |
| 59 | + # Security: Resolve the requested file path and check it's within template_dir |
| 60 | + requested_path = Path(filename) |
| 61 | + |
| 62 | + # Prevent absolute paths |
| 63 | + if requested_path.is_absolute(): |
| 64 | + msg = f"Absolute paths not allowed: {filename}" |
| 65 | + raise ValueError(msg) |
| 66 | + |
| 67 | + # Resolve the full path |
| 68 | + full_path = (template_dir / requested_path).resolve() |
| 69 | + |
| 70 | + # Security check: ensure the resolved path is within template_dir |
| 71 | + if not str(full_path).startswith(str(template_dir)): |
| 72 | + msg = f"Path outside template directory: {filename}" |
| 73 | + raise ValueError(msg) |
| 74 | + |
| 75 | + return full_path.read_text(encoding="utf-8") |
| 76 | + |
| 77 | + |
| 78 | +# Export the extension for Copier to use |
| 79 | +__all__ = ["IncludeRawExtension"] |
0 commit comments