plone / cookiecutter-zope-instance

It bakes configuration for Zope 5
BSD 3-Clause "New" or "Revised" License
7 stars 4 forks source link

Use `Jinja2` custom filter to generate paths #7

Closed me-kell closed 7 months ago

me-kell commented 1 year ago

https://github.com/plone/cookiecutter-zope-instance/blob/475308ab6718a54febfcd0737768fb455cecb3cc/hooks/post_gen_project.py#L2

With a Jinja2 custom filter in an Extension this could be achieved:

from jinja2.ext import Extension, pass_context
from pathlib import Path

class AbsPathExtension(Extension):

    def __init__(self, environment):

        super(AbsPathExtension, self).__init__(environment)
        environment.filters['abspath'] = AbsPathExtension.abspath

    @pass_context
    def abspath(context, path, append_path=''):

        try:
            _context_cookiecutter = context.get('cookiecutter')
            if _context_cookiecutter:
                _output_dir = _context_cookiecutter.get('_output_dir')
                if _output_dir:
                    new_path = Path(_output_dir, path, append_path).resolve().as_posix()
        except Exception as e:
            raise Exception(f"Failed to filter {context.name}") from e

        return f"{new_path}"

Usage:

{{ "a/b/c" | abspath }}
{{ "../x/y/z" | abspath }}
{{ "../x/y/../z" | abspath }}

{{ cookiecutter.my_var }}
{{ cookiecutter.my_var | abspath(append_path="subdir") }}
/path/to/dir/output_dir/a/b/c
/path/to/dir/x/y/z
/path/to/dir/x/z

/path/to/dir/output_dir/my_dir
/path/to/dir/output_dir/my_dir/subdir

It is recommended not to use {{ cookiecutter.my_var | abspath }}/subdir. But to use {{ cookiecutter.my_var | abspath(append_path="subdir") }} instead.

This way the abspath filter takes care to output (forward and backward) slashes as posix forward slashes.

me-kell commented 1 year ago

Added commit to pull request 6#issue-1446627793

jensens commented 7 months ago

see 6