-
-
Notifications
You must be signed in to change notification settings - Fork 182
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: add dynamic file structures in loop using yield-tag #1855
Open
kj-9
wants to merge
3
commits into
copier-org:master
Choose a base branch
from
kj-9:feat/loop_file_structures
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+419
−41
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,109 @@ | ||
"""Jinja2 extensions built for Copier.""" | ||
|
||
from __future__ import annotations | ||
|
||
from typing import Any, Callable, Sequence | ||
|
||
from jinja2 import nodes | ||
from jinja2.exceptions import UndefinedError | ||
from jinja2.ext import Extension | ||
from jinja2.parser import Parser | ||
from jinja2.sandbox import SandboxedEnvironment | ||
|
||
|
||
class YieldEnvironment(SandboxedEnvironment): | ||
"""Jinja2 environment with a `yield_context` attribute. | ||
|
||
This is simple environment class that extends the SandboxedEnvironment | ||
for use with the YieldExtension, mainly for avoiding type errors. | ||
|
||
We use the SandboxedEnvironment because we want to minimize the risk of hidden malware | ||
in the templates so we use the SandboxedEnvironment instead of the regular one. | ||
Of course we still have the post-copy tasks to worry about, but at least | ||
they are more visible to the final user. | ||
""" | ||
|
||
yield_context: dict[str, Any] | ||
|
||
def __init__(self, *args: Any, **kwargs: Any): | ||
super().__init__(*args, **kwargs) | ||
self.extend(yield_context=dict()) | ||
|
||
|
||
class YieldExtension(Extension): | ||
"""`Jinja2 extension for the `yield` tag. | ||
|
||
If `yield` tag is used in a template, this extension sets the `yield_context` attribute to the | ||
jinja environment. `yield_context` is a dictionary with the following keys: | ||
- `single_var`: The name of the variable that will be yielded. | ||
- `looped_var`: The variable that will be looped over. | ||
|
||
Note that this extension just sets the `yield_context` attribute but renders template | ||
as usual. It is caller's responsibility to use the `yield_context` attribute in the | ||
template to generate the desired output. | ||
|
||
Example: | ||
template: "{% yield single_var from looped_var %}" | ||
context: {"looped_var": [1, 2, 3], "single_var": "item"} | ||
|
||
then, | ||
>>> from copier.jinja_ext import YieldEnvironment, YieldExtension | ||
>>> env = YieldEnvironment(extensions=[YieldExtension]) | ||
>>> template = env.from_string("{% yield single_var from looped_var %}{{ single_var }}{% endyield %}") | ||
>>> template.render({"looped_var": [1, 2, 3]}) | ||
'' | ||
>>> env.yield_context | ||
{'single_var': 'single_var', 'looped_var': [1, 2, 3]} | ||
""" | ||
|
||
tags = {"yield"} | ||
|
||
environment: YieldEnvironment | ||
|
||
def __init__(self, environment: YieldEnvironment): | ||
super().__init__(environment) | ||
|
||
def parse(self, parser: Parser) -> nodes.Node: | ||
"""Parse the `yield` tag.""" | ||
lineno = next(parser.stream).lineno | ||
|
||
single_var: nodes.Name = parser.parse_assign_target(name_only=True) | ||
parser.stream.expect("name:from") | ||
looped_var = parser.parse_expression() | ||
body = parser.parse_statements(("name:endyield",), drop_needle=True) | ||
|
||
return nodes.CallBlock( | ||
self.call_method( | ||
"_yield_support", | ||
[looped_var, nodes.Const(single_var.name)], | ||
), | ||
[], | ||
[], | ||
body, | ||
lineno=lineno, | ||
) | ||
|
||
def _yield_support( | ||
self, looped_var: Sequence[Any], single_var_name: str, caller: Callable[[], str] | ||
) -> str: | ||
"""Support function for the yield tag. | ||
|
||
Sets the yield context in the environment with the given | ||
looped variable and single variable name, then calls the provided caller | ||
function. If an UndefinedError is raised, it returns an empty string. | ||
|
||
""" | ||
self.environment.yield_context = { | ||
"single_var": single_var_name, | ||
"looped_var": looped_var, | ||
} | ||
|
||
try: | ||
res = caller() | ||
|
||
# expression like `dict.attr` will always raise UndefinedError | ||
# so we catch it here and return an empty string | ||
except UndefinedError: | ||
res = "" | ||
|
||
return res |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
pass
is unnecessary if there's a docstring 🙂