Skip to content

Commit

Permalink
clean up cookiecutter; add babelizer_environment function
Browse files Browse the repository at this point in the history
  • Loading branch information
mcflugen committed Apr 2, 2024
1 parent 3b10450 commit 1eb959a
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 36 deletions.
72 changes: 52 additions & 20 deletions babelizer/_cookiecutter.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations

import os
from collections.abc import Iterable
from datetime import datetime
from typing import Any

Expand All @@ -9,20 +10,19 @@
from jinja2 import StrictUndefined
from jinja2 import Template

from babelizer._datadir import get_template_dir
from babelizer._post_hook import run
from babelizer._utils import as_cwd


def cookiecutter(
template: str,
extra_context: dict[str, Any] | None = None,
context: dict[str, Any] | None = None,
output_dir: str = ".",
no_input: bool = True,
overwrite_if_exists: bool = False,
) -> None:
if extra_context is None:
extra_context = {}
env = Environment(loader=FileSystemLoader(template), undefined=StrictUndefined)
if context is None:
context = {}
env = babelizer_environment(template)

def datetime_format(value: datetime, format_: str = "%Y-%M-%D") -> str:
return value.strftime(format_)
Expand All @@ -31,30 +31,62 @@ def datetime_format(value: datetime, format_: str = "%Y-%M-%D") -> str:

for dirpath, _dirnames, filenames in os.walk(template):
rel_path = os.path.relpath(dirpath, template)
target_dir = os.path.join(output_dir, render_path(rel_path, extra_context))
target_dir = os.path.join(output_dir, render_path(rel_path, context))

if not os.path.exists(target_dir):
os.makedirs(target_dir)

for filename in filenames:
target_path = os.path.join(target_dir, render_path(filename, extra_context))
target_path = os.path.join(target_dir, render_path(filename, context))

with open(target_path, "w") as fp:
fp.write(
env.get_template(os.path.join(rel_path, filename)).render(
**extra_context
)
env.get_template(os.path.join(rel_path, filename)).render(**context)
)

with as_cwd(output_dir):
run(extra_context)


def render_path(path: str, context: dict[str, Any]) -> str:
rendered_path = Template(path).render(**context)
run(context)


def babelizer_environment(template: str | None = None) -> Environment:
if template is None:
template = get_template_dir()

return Environment(loader=FileSystemLoader(template), undefined=StrictUndefined)


def render_path(
path: str,
context: dict[str, Any],
remove_extension: Iterable[str] = (".jinja", ".jinja2", ".j2"),
) -> str:
"""Render a path as though it were a jinja template.
Parameters
----------
path : str
A path.
context : dict
Context to use for substitution.
remove_extension : iterable of str, optional
If the provided path ends with one of these exensions,
the extension will be removed from the rendered path.
Examples
--------
>>> from babelizer._cookiecutter import render_path
>>> render_path("{{foo}}.py", {"foo": "bar"})
'bar.py'
>>> render_path("{{foo}}.py.jinja", {"foo": "bar"})
'bar.py'
>>> render_path("bar.py.j2", {"foo": "bar"})
'bar.py'
>>> render_path("{{bar}}.py.jinja", {"foo": "bar"})
Traceback (most recent call last):
...
jinja2.exceptions.UndefinedError: 'bar' is undefined
"""
rendered_path = Template(path, undefined=StrictUndefined).render(**context)

root, ext = os.path.splitext(rendered_path)
if ext == ".jinja":
rendered_path = root

return rendered_path
return rendered_path if ext not in remove_extension else root
11 changes: 2 additions & 9 deletions babelizer/_files/readme.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,10 @@

from typing import Any

from jinja2 import Environment
from jinja2 import FileSystemLoader
from jinja2 import StrictUndefined

from babelizer._datadir import get_template_dir
from babelizer._cookiecutter import babelizer_environment


def render(context: dict[str, Any]) -> str:
env = Environment(
loader=FileSystemLoader(get_template_dir()), undefined=StrictUndefined
)
template = env.get_template("templates/README.rst")
template = babelizer_environment().get_template("README.rst")

return template.render(**context)
8 changes: 1 addition & 7 deletions babelizer/render.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,13 +71,7 @@ def render(
if os.path.exists(output):
raise OutputDirExistsError(output)

cookiecutter(
template,
extra_context=context,
output_dir=output,
no_input=True,
overwrite_if_exists=clobber,
)
cookiecutter(template, context=context, output_dir=output)

path = os.path.realpath(output)

Expand Down

0 comments on commit 1eb959a

Please sign in to comment.