Skip to content

feat: Allow tasks to run in two stages, "before" or "after" copy #2050

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

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all 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
5 changes: 4 additions & 1 deletion copier/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -1016,14 +1016,17 @@ def run_copy(self) -> None:
f"\nCopying from template version {self.template.version}",
file=sys.stderr,
)
if not self.skip_tasks:
with Phase.use(Phase.TASKS):
self._execute_tasks(self.template.tasks("before"))
with Phase.use(Phase.RENDER):
self._render_template()
if not self.quiet:
# TODO Unify printing tools
print("") # padding space
if not self.skip_tasks:
with Phase.use(Phase.TASKS):
self._execute_tasks(self.template.tasks)
self._execute_tasks(self.template.tasks("after"))
except Exception:
if not was_existing and self.cleanup_on_error:
rmtree(self.subproject.local_abspath)
Expand Down
15 changes: 10 additions & 5 deletions copier/template.py
Original file line number Diff line number Diff line change
Expand Up @@ -509,26 +509,31 @@ def subdirectory(self) -> str:
"""
return self.config_data.get("subdirectory", "")

@cached_property
def tasks(self) -> Sequence[Task]:
def tasks(self, stage: Literal["before", "after"]) -> Sequence[Task]:
"""Get tasks defined in the template.

See [tasks][].
"""
extra_vars = {"stage": "task"}
extra_vars = {"stage": stage}
tasks = []
for task in self.config_data.get("tasks", []):
if isinstance(task, dict):
tasks.append(
Task(
cmd=task["command"],
extra_vars=extra_vars,
condition=task.get("when", "true"),
condition=task.get("when", "{{ _stage == 'after' }}"),
working_directory=Path(task.get("working_directory", ".")),
)
)
else:
tasks.append(Task(cmd=task, extra_vars=extra_vars))
tasks.append(
Task(
cmd=task,
extra_vars=extra_vars,
condition="{{ _stage == 'after' }}",
)
)
return tasks

@cached_property
Expand Down