Add render: template file set with token substitution

This commit is contained in:
jay
2026-11-09 13:23:50 -05:00
parent c5522cc649
commit 91d55d6008
2 changed files with 71 additions and 0 deletions
+32
View File
@@ -0,0 +1,32 @@
"""Render the project template into a mapping of relative paths to file contents."""
from pathlib import Path
TEMPLATE_DIR = Path(__file__).resolve().parent.parent / "template"
DEFAULT_PYTHON = "3.12.4"
def render(name: str, python_version: str = DEFAULT_PYTHON) -> dict[str, str]:
"""Render the template for *name* into {relative path: content}.
The package name is derived from *name* by replacing hyphens with
underscores. Every {{PKG}}, {{NAME}}, and {{PYVER}} token is substituted;
just's own {{args}} interpolation is left untouched.
"""
package = name.replace("-", "_")
substitutions = {
"{{PKG}}": package,
"{{NAME}}": name,
"{{PYVER}}": python_version,
}
files: dict[str, str] = {}
for path in sorted(TEMPLATE_DIR.rglob("*")):
if not path.is_file():
continue
content = path.read_text()
for token, value in substitutions.items():
content = content.replace(token, value)
files[path.relative_to(TEMPLATE_DIR).as_posix()] = content
files[f"{package}/__init__.py"] = ""
return files
+39
View File
@@ -0,0 +1,39 @@
"""Tests for rendering the project template."""
from new_python.render import DEFAULT_PYTHON, render
TEMPLATE_FILES = {
".gitignore",
"AGENTS.md",
"Pipfile",
"conftest.py",
"hooks/pre-commit",
"justfile",
"pyproject.toml",
}
TEMPLATE_TOKENS = ("{{PKG}}", "{{NAME}}", "{{PYVER}}")
def test_render_substitutes_all_tokens_for_a_dashed_name():
"""Rendering a dashed name derives the package and substitutes every token."""
files = render("demo-project")
assert set(files) == TEMPLATE_FILES | {"demo_project/__init__.py"}
assert files["demo_project/__init__.py"] == ""
justfile = files["justfile"]
assert justfile.count("demo_project") == 7
assert "{{args}}" in justfile
assert 'known_first_party = ["demo_project"]' in files["pyproject.toml"]
assert files["AGENTS.md"].startswith("# demo-project\n")
assert f'python_version = "{DEFAULT_PYTHON}"' in files["Pipfile"]
assert "Put the repo root on sys.path" in files["conftest.py"]
assert "__pycache__/" in files[".gitignore"]
assert "just ci" in files["hooks/pre-commit"]
for rel, content in files.items():
for token in TEMPLATE_TOKENS:
assert token not in content, f"{token} left unsubstituted in {rel}"