-
-
Notifications
You must be signed in to change notification settings - Fork 245
feat: add dynamic file structures in loop using yield-tag #1855
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
Merged
Merged
Changes from 13 commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
4329653
feat(add-dynamic-file-structures-in-loop-using-yield-tag): add jinja2…
kj-9 7164aa7
test(add-test-for-dynamic-file-structures-using-yield-tag): add a new…
kj-9 bc99b0d
fix(raise-error-if-yield-tag-is-used-when-rendering-file-content): ad…
kj-9 6f4acec
refactor(delete-unnecessary-statement-in-YieldTagInFileError): `pass`…
kj-9 3634d57
refactor(apply-review-comments): Improve docstrings, replace yield_co…
kj-9 8e08aea
fix(raise-error-for-yield-tag-in-render-file): Move YieldTagInFileErr…
kj-9 1aac269
refactor(reorder-parameters-in-yield-support-method): Change the orde…
kj-9 c6970f5
docs(add-docs-for-loops-using-yield-tag): Add documentation for loopi…
kj-9 847c1c6
Merge remote-tracking branch 'upstream/master' into HEAD
kj-9 ac042c5
docs(docs-for-yield-tag): Revise documentation for the yield tag
kj-9 b8033df
style(apply-lint): apply pre-commit lint
kj-9 3851329
style(main.py): add comment and fix unesessary diffs
kj-9 810f448
fix(add-treatment-for-multiple-yield-tags): add MultipleYieldTagsErro…
kj-9 5f11c99
fix(remove-unnecessary-method-overriding): remove unnecessary constru…
kj-9 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 hidden or 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 hidden or 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,126 @@ | ||
| """Jinja2 extensions built for Copier.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from typing import Any, Callable, Iterable | ||
|
|
||
| from jinja2 import nodes | ||
| from jinja2.exceptions import UndefinedError | ||
| from jinja2.ext import Extension | ||
| from jinja2.parser import Parser | ||
| from jinja2.sandbox import SandboxedEnvironment | ||
|
|
||
| from copier.errors import MultipleYieldTagsError | ||
|
|
||
|
|
||
| class YieldEnvironment(SandboxedEnvironment): | ||
| """Jinja2 environment with attributes from the YieldExtension. | ||
|
|
||
| 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. Of course we still have the post-copy tasks to worry about, but at least | ||
| they are more visible to the final user. | ||
| """ | ||
|
|
||
| yield_name: str | None | ||
| yield_iterable: Iterable[Any] | None | ||
|
|
||
| def __init__(self, *args: Any, **kwargs: Any): | ||
| super().__init__(*args, **kwargs) | ||
| self.extend(yield_name=None, yield_iterable=None) | ||
sisp marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
|
|
||
| class YieldExtension(Extension): | ||
| """Jinja2 extension for the `yield` tag. | ||
|
|
||
| If `yield` tag is used in a template, this extension sets following attribute to the | ||
| jinja environment: | ||
pawamoy marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| - `yield_name`: The name of the variable that will be yielded. | ||
| - `yield_iterable`: The variable that will be looped over. | ||
|
|
||
| Note that this extension just sets the attributes but renders templates as usual. | ||
| It is the caller's responsibility to use the `yield_context` attribute in the template to | ||
| generate the desired output. | ||
|
|
||
| !!! example | ||
|
|
||
| ```pycon | ||
yajo marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| >>> 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_name | ||
| 'single_var' | ||
| >>> env.yield_iterable | ||
| [1, 2, 3] | ||
| ``` | ||
| """ | ||
|
|
||
| tags = {"yield"} | ||
|
|
||
| environment: YieldEnvironment | ||
|
|
||
| def __init__(self, environment: YieldEnvironment): | ||
| super().__init__(environment) | ||
yajo marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| def preprocess( | ||
| self, source: str, _name: str | None, _filename: str | None = None | ||
| ) -> str: | ||
| """Preprocess hook to reset attributes before rendering.""" | ||
| self.environment.yield_name = self.environment.yield_iterable = None | ||
|
|
||
| return source | ||
|
|
||
| def parse(self, parser: Parser) -> nodes.Node: | ||
| """Parse the `yield` tag.""" | ||
| lineno = next(parser.stream).lineno | ||
|
|
||
| yield_name: nodes.Name = parser.parse_assign_target(name_only=True) | ||
| parser.stream.expect("name:from") | ||
| yield_iterable = parser.parse_expression() | ||
| body = parser.parse_statements(("name:endyield",), drop_needle=True) | ||
|
|
||
| return nodes.CallBlock( | ||
| self.call_method( | ||
| "_yield_support", | ||
| [nodes.Const(yield_name.name), yield_iterable], | ||
| ), | ||
| [], | ||
| [], | ||
| body, | ||
| lineno=lineno, | ||
| ) | ||
|
|
||
| def _yield_support( | ||
| self, yield_name: str, yield_iterable: Iterable[Any], caller: Callable[[], str] | ||
| ) -> str: | ||
| """Support function for the yield tag. | ||
|
|
||
| Sets the `yield_name` and `yield_iterable` attributes in the environment then calls | ||
| the provided caller function. If an UndefinedError is raised, it returns an empty string. | ||
| """ | ||
| if ( | ||
| self.environment.yield_name is not None | ||
| or self.environment.yield_iterable is not None | ||
| ): | ||
| raise MultipleYieldTagsError( | ||
| "Attempted to parse the yield tag twice. Only one yield tag is allowed per path name.\n" | ||
| f'A yield tag with the name: "{self.environment.yield_name}" and iterable: "{self.environment.yield_iterable}" already exists.' | ||
| ) | ||
|
|
||
| self.environment.yield_name = yield_name | ||
| self.environment.yield_iterable = yield_iterable | ||
yajo marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| 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 hidden or 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 hidden or 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.
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.
Uh oh!
There was an error while loading. Please reload this page.