copier-org / copier

Library and command-line utility for rendering projects templates.
https://readthedocs.org/projects/copier/
MIT License
1.9k stars 174 forks source link

Allow configuring Jinja with StrictUndefined #1522

Open yajo opened 6 months ago

yajo commented 6 months ago

Discussed in https://github.com/orgs/copier-org/discussions/1512

Originally posted by **coretl** February 9, 2024 I've been bitten a couple of times by this workflow: - Change the name of a variable in `copier.yml` - Forget to rename some of the references to that variable in my template - End up with that variable being rendered blank in a text file somewhere when using the template It would appear that Jinja does this by default, and the way it suggests to raise an error is by supplying [`undefined=StrictUndefined`](https://jinja.palletsprojects.com/en/3.1.x/api/#jinja2.StrictUndefined) in its [`Environment`](https://jinja.palletsprojects.com/en/3.1.x/api/#jinja2.Environment). I tried this in `copier.yml`: ```yaml _envops: undefined: StrictUndefined ``` But it fails because it can't turn the string into a callable: ```python File "/venv/lib/python3.11/site-packages/copier/main.py", line 1024, in run_copy with Worker(src_path=src_path, dst_path=Path(dst_path), **kwargs) as worker: File "/venv/lib/python3.11/site-packages/copier/main.py", line 205, in __exit__ raise value File "/venv/lib/python3.11/site-packages/copier/main.py", line 1025, in run_copy worker.run_copy() File "/venv/lib/python3.11/site-packages/copier/main.py", line 745, in run_copy self._ask() File "/venv/lib/python3.11/site-packages/copier/main.py", line 421, in _ask jinja_env=self.jinja_env, ^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/functools.py", line 1001, in __get__ val = self.func(instance) ^^^^^^^^^^^^^^^^^^^ File "/venv/lib/python3.11/site-packages/copier/main.py", line 500, in jinja_env env = SandboxedEnvironment( ^^^^^^^^^^^^^^^^^^^^^ File "/venv/lib/python3.11/site-packages/jinja2/sandbox.py", line 253, in __init__ super().__init__(*args, **kwargs) File "/venv/lib/python3.11/site-packages/jinja2/environment.py", line 366, in __init__ _environment_config_check(self) File "/venv/lib/python3.11/site-packages/jinja2/environment.py", line 126, in _environment_config_check assert issubclass( ^^^^^^^^^^^ TypeError: issubclass() arg 1 must be a class ``` Is there a way to make the `copier copy` command fail if you use an undefined name in a template? Related to #313 but with a different aim in mind
coretl commented 6 months ago

Would you like a PR for this?

yajo commented 6 months ago

Of course.

evalott100 commented 6 months ago

I'll start working on this now.