Skip to content
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

refactor: Deprecate the "update" aspect of context hooks #5

Merged
merged 3 commits into from
Jul 15, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 1 addition & 21 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,28 +104,8 @@ from copier_templates_extensions import ContextHook


class ContextUpdater(ContextHook):
def hook(self, context):
new_context = {}
new_context["say"] = "hello " + context["name"]
return new_context
```

Using the above example, your context will be updated
with the `new_context` returned by the method.
If you prefer to modify the context in-place instead,
for example to *remove* items from it,
set the `update` class attribute to `False`:

```python
from copier_templates_extensions import ContextHook


class ContextUpdater(ContextHook):
update = False

def hook(self, context):
context["say"] = "hello " + context["name"]
del context["name"]
```

In your Jinja templates, you will now have access
Expand Down Expand Up @@ -197,7 +177,7 @@ from copier_templates_extensions import ContextHook

class ContextUpdater(ContextHook):
def hook(self, context):
return {"module_name": "app" if context["project_type"] == "webapi" else "cli"}
context["module_name"] = "app" if context["project_type"] == "webapi" else "cli"
```

```
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ classifiers = [
"Typing :: Typed",
]
dependencies = [
"copier>=6",
"copier>=9.2",
]
pawamoy marked this conversation as resolved.
Show resolved Hide resolved

[project.urls]
Expand Down
26 changes: 20 additions & 6 deletions src/copier_templates_extensions/extensions/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from __future__ import annotations

import warnings
from typing import TYPE_CHECKING

from jinja2.ext import Extension
Expand All @@ -10,11 +11,13 @@
from jinja2 import Environment
from typing import Any, Callable, MutableMapping

_sentinel = object()


class ContextHook(Extension):
"""Extension allowing to modify the Copier context."""

update = True
update = _sentinel

def __init__(extension_self: Extension, environment: Environment) -> None: # noqa: N805
"""Initialize the object.
Expand All @@ -33,11 +36,22 @@ def __init__(
blocks: dict[str, Callable],
globals: MutableMapping[str, Any] | None = None, # noqa: A002,ARG002
):
if "_copier_conf" in parent:
if extension_self.update: # type: ignore[attr-defined]
parent.update(extension_self.hook(parent)) # type: ignore[attr-defined]
else:
extension_self.hook(parent) # type: ignore[attr-defined]
if extension_self.update is not _sentinel: # type: ignore[attr-defined]
warnings.warn(
"The `update` attribute of `ContextHook` subclasses is deprecated. "
"The `hook` method should now always modify the `context` in place.",
DeprecationWarning,
stacklevel=1,
)
if "_copier_conf" in parent and (context := extension_self.hook(parent)) is not None: # type: ignore[attr-defined]
parent.update(context)
warnings.warn(
"Returning a dict from the `hook` method is deprecated. "
"It should now always modify the `context` in place.",
DeprecationWarning,
stacklevel=1,
)

super().__init__(env, parent, name, blocks)

environment.context_class = ContextClass
Expand Down
2 changes: 1 addition & 1 deletion src/copier_templates_extensions/extensions/loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ def __init__(self, environment: Environment):
def _patched_import_string(self, import_name: str, *, silent: bool = False) -> Any:
try:
return self._import_string(import_name)
except Exception: # noqa: BLE001
except Exception:
if not silent:
raise

Expand Down
2 changes: 0 additions & 2 deletions tests/fixtures/modifying_context/extensions.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,5 @@


class ContextUpdater(ContextHook):
update = False

def hook(self, context):
context["success"] = True
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@

class ContextUpdater(ContextHook):
def hook(self, context):
return {"success": True}
context["success"] = True
2 changes: 1 addition & 1 deletion tests/fixtures/updating_context/extensions.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@

class ContextUpdater(ContextHook):
def hook(self, context):
return {"success": True}
context["success"] = True
Loading