Skip to content

Commit 2a80d01

Browse files
committed
feat: Add _operation variable
1 parent 2e7629e commit 2a80d01

File tree

5 files changed

+176
-4
lines changed

5 files changed

+176
-4
lines changed

copier/main.py

Lines changed: 52 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,10 @@
66
import subprocess
77
import sys
88
from contextlib import suppress
9+
from contextvars import ContextVar
910
from dataclasses import asdict, field, replace
1011
from filecmp import dircmp
11-
from functools import cached_property, partial
12+
from functools import cached_property, partial, wraps
1213
from itertools import chain
1314
from pathlib import Path
1415
from shutil import rmtree
@@ -60,13 +61,38 @@
6061
MISSING,
6162
AnyByStrDict,
6263
JSONSerializable,
64+
Operation,
65+
ParamSpec,
6366
RelativePath,
6467
StrOrPath,
6568
)
6669
from .user_data import DEFAULT_DATA, AnswersMap, Question
6770
from .vcs import get_git
6871

6972
_T = TypeVar("_T")
73+
_P = ParamSpec("_P")
74+
75+
_operation: ContextVar[Operation] = ContextVar("_operation")
76+
77+
78+
def as_operation(value: Operation) -> Callable[[Callable[_P, _T]], Callable[_P, _T]]:
79+
"""Decorator to set the current operation context, if not defined already.
80+
81+
This value is used to template specific configuration options.
82+
"""
83+
84+
def _decorator(func: Callable[_P, _T]) -> Callable[_P, _T]:
85+
@wraps(func)
86+
def _wrapper(*args: _P.args, **kwargs: _P.kwargs) -> _T:
87+
token = _operation.set(_operation.get(value))
88+
try:
89+
return func(*args, **kwargs)
90+
finally:
91+
_operation.reset(token)
92+
93+
return _wrapper
94+
95+
return _decorator
7096

7197

7298
@dataclass(config=ConfigDict(extra="forbid"))
@@ -243,7 +269,7 @@ def _cleanup(self) -> None:
243269
for method in self._cleanup_hooks:
244270
method()
245271

246-
def _check_unsafe(self, mode: Literal["copy", "update"]) -> None:
272+
def _check_unsafe(self, mode: Operation) -> None:
247273
"""Check whether a template uses unsafe features."""
248274
if self.unsafe:
249275
return
@@ -296,8 +322,10 @@ def _execute_tasks(self, tasks: Sequence[Task]) -> None:
296322
Arguments:
297323
tasks: The list of tasks to run.
298324
"""
325+
operation = _operation.get()
299326
for i, task in enumerate(tasks):
300327
extra_context = {f"_{k}": v for k, v in task.extra_vars.items()}
328+
extra_context["_operation"] = operation
301329

302330
if not cast_to_bool(self._render_value(task.condition, extra_context)):
303331
continue
@@ -327,7 +355,7 @@ def _execute_tasks(self, tasks: Sequence[Task]) -> None:
327355
/ Path(self._render_string(str(task.working_directory), extra_context))
328356
).absolute()
329357

330-
extra_env = {k.upper(): str(v) for k, v in task.extra_vars.items()}
358+
extra_env = {k[1:].upper(): str(v) for k, v in extra_context.items()}
331359
with local.cwd(working_directory), local.env(**extra_env):
332360
subprocess.run(task_cmd, shell=use_shell, check=True, env=local.env)
333361

@@ -588,7 +616,14 @@ def _pathjoin(
588616
@cached_property
589617
def match_exclude(self) -> Callable[[Path], bool]:
590618
"""Get a callable to match paths against all exclusions."""
591-
return self._path_matcher(self.all_exclusions)
619+
# Include the current operation in the rendering context.
620+
# Note: This method is a cached property, it needs to be regenerated
621+
# when reusing an instance in different contexts.
622+
extra_context = {"_operation": _operation.get()}
623+
return self._path_matcher(
624+
self._render_string(exclusion, extra_context=extra_context)
625+
for exclusion in self.all_exclusions
626+
)
592627

593628
@cached_property
594629
def match_skip(self) -> Callable[[Path], bool]:
@@ -818,6 +853,7 @@ def template_copy_root(self) -> Path:
818853
return self.template.local_abspath / subdir
819854

820855
# Main operations
856+
@as_operation("copy")
821857
def run_copy(self) -> None:
822858
"""Generate a subproject from zero, ignoring what was in the folder.
823859
@@ -828,6 +864,11 @@ def run_copy(self) -> None:
828864
829865
See [generating a project][generating-a-project].
830866
"""
867+
with suppress(AttributeError):
868+
# We might have switched operation context, ensure the cached property
869+
# is regenerated to re-render templates.
870+
del self.match_exclude
871+
831872
self._check_unsafe("copy")
832873
self._print_message(self.template.message_before_copy)
833874
self._ask()
@@ -854,6 +895,7 @@ def run_copy(self) -> None:
854895
# TODO Unify printing tools
855896
print("") # padding space
856897

898+
@as_operation("copy")
857899
def run_recopy(self) -> None:
858900
"""Update a subproject, keeping answers but discarding evolution."""
859901
if self.subproject.template is None:
@@ -864,6 +906,7 @@ def run_recopy(self) -> None:
864906
with replace(self, src_path=self.subproject.template.url) as new_worker:
865907
new_worker.run_copy()
866908

909+
@as_operation("update")
867910
def run_update(self) -> None:
868911
"""Update a subproject that was already generated.
869912
@@ -911,6 +954,11 @@ def run_update(self) -> None:
911954
print(
912955
f"Updating to template version {self.template.version}", file=sys.stderr
913956
)
957+
with suppress(AttributeError):
958+
# We might have switched operation context, ensure the cached property
959+
# is regenerated to re-render templates.
960+
del self.match_exclude
961+
914962
self._apply_update()
915963
self._print_message(self.template.message_after_update)
916964

copier/types.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
"""Complex types, annotations, validators."""
22

3+
import sys
34
from pathlib import Path
45
from typing import (
56
Annotated,
@@ -16,6 +17,11 @@
1617

1718
from pydantic import AfterValidator
1819

20+
if sys.version_info >= (3, 10):
21+
from typing import ParamSpec as ParamSpec
22+
else:
23+
from typing_extensions import ParamSpec as ParamSpec
24+
1925
# simple types
2026
StrOrPath = Union[str, Path]
2127
AnyByStrDict = Dict[str, Any]
@@ -35,6 +41,7 @@
3541
Env = Mapping[str, str]
3642
MissingType = NewType("MissingType", object)
3743
MISSING = MissingType(object())
44+
Operation = Literal["copy", "update"]
3845

3946

4047
# Validators

docs/configuring.md

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -893,6 +893,18 @@ to know available options.
893893

894894
The CLI option can be passed several times to add several patterns.
895895

896+
Each pattern can be templated using Jinja.
897+
898+
!!! example
899+
900+
Templating `exclude` patterns using `_operation` allows to have files
901+
that are rendered once during `copy`, but are never updated:
902+
903+
```yaml
904+
_exclude:
905+
- "{% if _operation == 'update' -%}src/*_example.py{% endif %}"
906+
```
907+
896908
!!! info
897909

898910
When you define this parameter in `copier.yml`, it will **replace** the default
@@ -1351,6 +1363,8 @@ configuring `secret: true` in the [advanced prompt format][advanced-prompt-forma
13511363
exist, but always be present. If they do not exist in a project during an `update`
13521364
operation, they will be recreated.
13531365

1366+
Each pattern can be templated using Jinja.
1367+
13541368
!!! example
13551369

13561370
For example, it can be used if your project generates a password the 1st time and
@@ -1501,6 +1515,9 @@ other items not present.
15011515
- [invoke, end-process, "--full-conf={{ _copier_conf|to_json }}"]
15021516
# Your script can be run by the same Python environment used to run Copier
15031517
- ["{{ _copier_python }}", task.py]
1518+
# Run a command during the initial copy operation only, excluding updates
1519+
- command: ["{{ _copier_python }}", task.py]
1520+
when: "{{ _operation == 'copy' }}"
15041521
# OS-specific task (supported values are "linux", "macos", "windows" and `None`)
15051522
- command: rm {{ name_of_the_project }}/README.md
15061523
when: "{{ _copier_conf.os in ['linux', 'macos'] }}"

docs/creating.md

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,16 @@ The absolute path of the Python interpreter running Copier.
125125

126126
The name of the project root directory.
127127

128+
## Variables (context-dependent)
129+
130+
Some variables are only available in select contexts:
131+
132+
### `_operation`
133+
134+
The current operation, either `"copy"` or `"update"`.
135+
136+
Availability: [`exclude`](configuring.md#exclude), [`tasks`](configuring.md#tasks)
137+
128138
## Variables (context-specific)
129139

130140
Some rendering contexts provide variables unique to them:

tests/test_context.py

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
import json
2+
from pathlib import Path
3+
4+
import pytest
5+
from plumbum import local
6+
7+
import copier
8+
9+
from .helpers import build_file_tree, git_save
10+
11+
12+
def test_exclude_templating_with_operation(
13+
tmp_path_factory: pytest.TempPathFactory,
14+
) -> None:
15+
"""
16+
Ensure it's possible to create one-off boilerplate files that are not
17+
managed during updates via `_exclude` using the `_operation` context variable.
18+
"""
19+
src, dst = map(tmp_path_factory.mktemp, ("src", "dst"))
20+
21+
template = "{% if _operation == 'update' %}copy-only{% endif %}"
22+
with local.cwd(src):
23+
build_file_tree(
24+
{
25+
"copier.yml": f'_exclude:\n - "{template}"',
26+
"{{ _copier_conf.answers_file }}.jinja": "{{ _copier_answers|to_yaml }}",
27+
"copy-only": "foo",
28+
"copy-and-update": "foo",
29+
}
30+
)
31+
git_save(tag="1.0.0")
32+
build_file_tree(
33+
{
34+
"copy-only": "bar",
35+
"copy-and-update": "bar",
36+
}
37+
)
38+
git_save(tag="2.0.0")
39+
copy_only = dst / "copy-only"
40+
copy_and_update = dst / "copy-and-update"
41+
42+
copier.run_copy(str(src), dst, defaults=True, overwrite=True, vcs_ref="1.0.0")
43+
for file in (copy_only, copy_and_update):
44+
assert file.exists()
45+
assert file.read_text() == "foo"
46+
47+
with local.cwd(dst):
48+
git_save()
49+
50+
copier.run_update(str(dst), overwrite=True)
51+
assert copy_only.read_text() == "foo"
52+
assert copy_and_update.read_text() == "bar"
53+
54+
55+
def test_task_templating_with_operation(
56+
tmp_path_factory: pytest.TempPathFactory, tmp_path: Path
57+
) -> None:
58+
"""
59+
Ensure that it is possible to define tasks that are only executed when copying.
60+
"""
61+
src, dst = map(tmp_path_factory.mktemp, ("src", "dst"))
62+
# Use a file outside the Copier working directories to ensure accurate tracking
63+
task_counter = tmp_path / "task_calls.txt"
64+
with local.cwd(src):
65+
build_file_tree(
66+
{
67+
"copier.yml": (
68+
f"""\
69+
_tasks:
70+
- command: echo {{{{ _operation }}}} >> {json.dumps(str(task_counter))}
71+
when: "{{{{ _operation == 'copy' }}}}"
72+
"""
73+
),
74+
"{{ _copier_conf.answers_file }}.jinja": "{{ _copier_answers|to_yaml }}",
75+
}
76+
)
77+
git_save(tag="1.0.0")
78+
79+
copier.run_copy(str(src), dst, defaults=True, overwrite=True, unsafe=True)
80+
assert task_counter.exists()
81+
assert len(task_counter.read_text().splitlines()) == 1
82+
83+
with local.cwd(dst):
84+
git_save()
85+
86+
copier.run_recopy(dst, defaults=True, overwrite=True, unsafe=True)
87+
assert len(task_counter.read_text().splitlines()) == 2
88+
89+
copier.run_update(dst, defaults=True, overwrite=True, unsafe=True)
90+
assert len(task_counter.read_text().splitlines()) == 2

0 commit comments

Comments
 (0)